package net.northking.cctp.scriptcase.tools;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.service.AtuInputSetService;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuScriptInputSetFeignDto;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuScriptInputSetQuoteFeignDto;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuScriptInputSetQuoteFieldDto;
import net.northking.cctp.scriptcase.dto.inputSet.AtuInputDataSetDto;
import net.northking.cctp.scriptcase.enums.ScriptCaseAppError;
import net.northking.cctp.scriptcase.feign.DataMgrFeignClient;
import net.northking.cctp.scriptcase.feign.dto.AtuDataSetFeignDto;
import net.northking.cctp.scriptcase.feign.dto.DataContentDto;
import net.northking.cctp.scriptcase.feign.dto.DataSetsSaveDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class DataMgrUtils {

    private static final Logger logger = LoggerFactory.getLogger(DataMgrUtils.class);

    @Autowired
    private DataMgrFeignClient dataMgrFeignClient;

    @Autowired
    private DownloadFileUtils downloadFileUtils;

    @Autowired
    private AtuInputSetService atuInputSetService;

    public List<Map<String,Object>> dealWithQuoteFiled(List<Map<String,Object>> mTmp, String envId) {
        //输入项中静态数据的位置
        Map<Integer, Map<String, AtuScriptInputSetQuoteFieldDto>> updateMap = new HashMap<>();
        //静态数据集id集合
        Set<String> dataSetList = new HashSet<>();
        Set<String> fuzzyDataSetList = new HashSet<>();
        //1、找出对应的静态数据
        for (int i = 0; i < mTmp.size(); i++) {
            //每一行里的静态数据
            Map<String, AtuScriptInputSetQuoteFieldDto> contentMap = new HashMap<>();
            for (String key : mTmp.get(i).keySet()) {//key为单个表头名称 找出每一行的静态数据
                try {
                    AtuScriptInputSetQuoteFieldDto dto = JSONObject.parseObject(mTmp.get(i).get(key).toString(), AtuScriptInputSetQuoteFieldDto.class);
                    // 模糊数据没有行列之分，设置默认的行
                    if (dto.getType().equals(ScriptConstant.INPUT_SET_QUOTE_TYPE_FUZZY)){
                        dto.setRow(ScriptConstant.INPUT_SET_QUOTE_DEFAULT_ROW);
                    }
                    if (!dto.isValid()) {
                        throw new PlatformRuntimeException(ScriptCaseAppError.IT_IS_INVALID_QUOTE_DATA);
                    }
                    if (dto.getType().equals(ScriptConstant.INPUT_SET_QUOTE_TYPE_FUZZY)){
                        fuzzyDataSetList.add(dto.getSetId());
                    }else{
                        dataSetList.add(dto.getSetId());
                    }
                    contentMap.put(key, dto);
                } catch (Exception e) {
                    //logger.error("----当前key对应的值不是静态数据!!!!---");
                }
            }
            //记录到map里面
            if (contentMap.keySet().size() > 0) {//根据行号记录每一行对应的静态数据
                updateMap.put(i, contentMap);
            }
        }
        //2、存在静态数据 调用feign获取文件地址 并且下载文件解析
        // key为setId
        Map<String, AtuScriptInputSetQuoteFeignDto> resultMap = new HashMap<>();
        // 文件内容 key为setId
        Map<String, DataSetsSaveDto> saveDtoMap = new HashMap<>();
        if (dataSetList.size() > 0){
            AtuDataSetFeignDto setFeignDto = new AtuDataSetFeignDto();
            setFeignDto.setDataSetList(dataSetList);
            setFeignDto.setEnvId(envId);
            resultMap = dataMgrFeignClient.queryDataSetFile(setFeignDto);
            for (String setId : resultMap.keySet()) {
                AtuScriptInputSetQuoteFeignDto fieldDto = resultMap.get(setId);
                JSONObject dataSetObj = downloadFileUtils.downloadDataSetFile(fieldDto.getFilePath());
                DataSetsSaveDto dataSetsSaveDto = dataSetObj.toJavaObject(DataSetsSaveDto.class);
                saveDtoMap.put(setId, dataSetsSaveDto);
            }
        }
        Map<String, String> fuzzyDataNameMap = new HashMap<>();
        if (fuzzyDataSetList.size() > 0){
            AtuDataSetFeignDto setFeignDto = new AtuDataSetFeignDto();
            setFeignDto.setDataSetList(fuzzyDataSetList);
            fuzzyDataNameMap = dataMgrFeignClient.queryFuzzyDataNameMap(setFeignDto);
        }
        if (dataSetList.size() > 0 || fuzzyDataSetList.size() > 0) {//根据静态数据id去查找对应的文件
            for (Integer integer : updateMap.keySet()) {
                Map<String, AtuScriptInputSetQuoteFieldDto> contentMap = updateMap.get(integer);
                for (String key : contentMap.keySet()) {
                    //前端保存的
                    AtuScriptInputSetQuoteFieldDto dto = contentMap.get(key);
                    if (dto.getType().equals(ScriptConstant.INPUT_SET_QUOTE_TYPE_FUZZY)){
                        if (CollUtil.isNotEmpty(fuzzyDataNameMap) &&
                                fuzzyDataNameMap.containsKey(dto.getSetId())){
                            dto.setPath(fuzzyDataNameMap.get(dto.getSetId()));
                            dto.setValue(ScriptConstant.FUZZY_DATA_QUOTE_PREFIX + fuzzyDataNameMap.get(dto.getSetId())
                                    + ScriptConstant.FUZZY_DATA_QUOTE_SUFFIX);
                        }
                    }else {
                        //feign返回的
                        AtuScriptInputSetQuoteFeignDto fieldDto = resultMap.get(dto.getSetId());
                        DataSetsSaveDto dataSetsSaveDto = saveDtoMap.get(dto.getSetId());
                        if (null != fieldDto) {
                            //拼接path
                            int row = dto.getRow() + 1;
                            String path = fieldDto.getFullName() + ":" + fieldDto.getName() + "." + dto.getColumn() + ".[" + row + "]";
                            dto.setPath(path);
                            //获取最新value
                            try {
                                Map<String, List<DataContentDto>> tableContent = dataSetsSaveDto.getTableContent();
                                dto.setValue(tableContent.get(dto.getColumn()).get(dto.getRow()).getValue());
                            } catch (Exception e) {
                                dto.setValue(null);
                            }
                        }
                    }
                    AtuScriptInputSetFeignDto resultDto = new AtuScriptInputSetFeignDto();
                    BeanUtils.copyProperties(dto, resultDto);
                    resultDto.setTip(dto.getPath());
                    mTmp.get(integer).put(key, resultDto);
                }
            }
        }
        //填值到jsonObject中
        return mTmp;
    }

    public void queryInputAndDataLink(List<Map<String,Object>> mapList,String envId,String inputSetId,String source){
        AtuInputDataSetDto delDto = new AtuInputDataSetDto();
        delDto.setInputSetId(inputSetId);
        delDto.setEnvId(envId);
        delDto.setSource(source);
        this.atuInputSetService.deleteDataSetLink(delDto);
        List<AtuInputDataSetDto> dataSetList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(mapList)) {
            for (Map<String, Object> map : mapList) {
                //每一行里的静态数据
                for (String key : map.keySet()) {
                    try {
                        Object checkObj = map.get(key);
                        //logger.info("-------->value:{}", JSONObject.toJSONString(checkObj));
                        AtuScriptInputSetQuoteFieldDto dto = JSONObject.parseObject(JSONObject.toJSONString(checkObj), AtuScriptInputSetQuoteFieldDto.class);
                        if (dto.getType().equals(ScriptConstant.INPUT_SET_QUOTE_TYPE_FUZZY)){
                            dto.setRow(ScriptConstant.INPUT_SET_QUOTE_DEFAULT_ROW);
                        }
                        if (!dto.isValid()) {
                            throw new PlatformRuntimeException(ScriptCaseAppError.IT_IS_INVALID_QUOTE_DATA);
                        }
                        AtuInputDataSetDto dataSetDto = new AtuInputDataSetDto();
                        dataSetDto.setId(UUIDUtil.create32UUID());
                        dataSetDto.setInputSetId(inputSetId);
                        dataSetDto.setEnvId(envId);
                        dataSetDto.setSource(source);
                        dataSetDto.setDataSetId(dto.getSetId());
                        dataSetDto.setSetColumn(dto.getColumn());
                        dataSetDto.setRowNum(dto.getRow());

                        dataSetList.add(dataSetDto);
                    } catch (Exception e) {
                        //logger.error("----当前key对应的值不是静态数据!!!!---");
                    }
                }
            }
        }
        if (dataSetList.size()>0) {
            this.atuInputSetService.insertDataSetLink(dataSetList);
        }

    }




}
