package com.friday.custody.context;

import com.friday.custody.exception.RRException;
import com.friday.custody.service.basicService.DataDictionaryDirectoryService;
import com.friday.custody.service.logicService.DataDictionaryBasicService;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class DataDictionaryStrategyContext {
    private final Map<String, DataDictionaryBasicService> dicStrategyMap = new ConcurrentHashMap<>();
    @Autowired
    private DataDictionaryDirectoryService dictionaryDirectoryService;


    @Autowired
    public void dpStrategyContext(Map<String, DataDictionaryBasicService> strategyMap) {
        strategyMap.forEach(this.dicStrategyMap::put);
    }


    public R getDataDictionary(String type) {
        try {
            String service = getServiceNameByType(type);
            R r = dicStrategyMap.get(service).queryData(null);
            //处理返回数据含有\t问题
            Map data = (HashMap) r.get("data");
            Iterator it = data.keySet().iterator();
            if (!ObjectUtils.isEmpty(data)) {
                data.forEach((k, v) -> {
                    data.put(k, v.toString().trim());
                });
            }
            r.setData(data);
            return r;
        } catch (Exception e) {
            log.error("查询字典表失败：", e);
            return R.error(RetCodeEnum.SYS_ERROR.getCode(), "查询字典表失败！");
        }
    }


    private String getServiceNameByType(String type) {
        String serviceName = dictionaryDirectoryService.queryByType(type);
        if (serviceName == null) {
            log.warn("查询数据配置为空, 请联系管理员配置后再启任务!");
            throw new RRException("查询数据配置为空, 请联系管理员配置后再启任务! type:" + type);
        }
        return serviceName;
    }
}