package com.malk.aiwei.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.aiwei.service.AWYDClient;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AWYDImplClient implements AWYDClient {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDService ydService;

    /**
     * 提供verifier数据读取服务
     */
    @Override
    public List<Map> syncVerifier(String projectCode) {
        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .formUuid("FORM-23B67983E91C4ED3B063F9B629D6E964SGHH")
                .searchCondition(JSON.toJSONString(UtilMap.map("textField_lt6xd8lm", projectCode)))
                .build());

        return dataList.stream().map(item -> {
            return item;
        }).collect(Collectors.toList());
    }


    /************************************* 0906 产品需求导入逻辑变革, 弃用保留 *************************************/
    
    @Override
    public Map checkImportData(Map data) {
        List<Map> dataList = UtilMap.getList(data, "dataList");
        String charter = UtilMap.getString(data, "charter");
        // 根据charter查询需求库
        List<Map> list = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_YQY0OH7953OKBTM57PLL")
                .systemToken("PGC66MB1H2RLXMFQ7XKW4BC3BDFJ2UDM909XL18")
                .formUuid("FORM-7A52930D0E834522AD65A4CFE2C0818F1KQO")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_lth2h04b", charter))).build());
        Map<String, Map> charterMap = new HashMap();
        Map<String, String> instIdList = new HashMap<>();
        for (int j = 0; j < list.size(); j++) {
            Map item = list.get(j);
            instIdList.put(UtilMap.getString(item, "textField_lt2d2x79"), UtilMap.getString(item, "instanceId"));
            String no = getCode(UtilMap.getString(item, "textField_lt2d2x79"));
            charterMap.put(no, item);
            list.get(j).put("id", no);
        }
        Boolean flag = true;
        Map noList = new HashMap();
        // 数据校验
        for (int i = 0; i < dataList.size(); i++) {
            String errmsg = "";
            Map item = dataList.get(i);
            String category = UtilMap.getString(item, "selectField_lronu2g3");
            if (StringUtils.isBlank(category)) {
                errmsg = errmsg + "需求大类不能为空；";
            } else {
                category = category.split("（")[1].replace("）", "");
                String no = noCP(UtilMap.getString(item, "textField_lt2d2x79"), category);
                String fno = noCP(UtilMap.getString(item, "textField_m0afm8pd"), category);
                if (!isValidVersion(no)) {
                    errmsg = errmsg + "需求编号格式错误；";
                }
                if (noList.containsKey(category + no)) {
                    errmsg = errmsg + "需求编号重复；";
                }
                noList.put(category + no, category + no);
                int cj = getSize(no);
                if (cj == 1) {
                    dataList.get(i).put("textField_m0afm8pd", "");
                } else {
                    if (!isValidVersion(fno)) {
                        errmsg = errmsg + "父需求编号格式错误；";
                    }
                    if (cj - 1 != getSize(fno)) {
                        errmsg = errmsg + "父需求编号层级错误；";
                    }
                    if (StringUtils.isNotBlank(fno) && !noList.containsKey(category + fno)) {
                        // 导入数据前父需求编号不存在
                        if (!charterMap.containsKey(getCode(UtilMap.getString(item, "textField_m0afm8pd")))) {
                            errmsg = errmsg + "父需求编号数据不存在；";
                        }
                    }
                }
                if (fno == no) {
                    errmsg = errmsg + "需求编号于父需求编号不能相同；";
                }
                dataList.get(i).put("selectField_lr4y2xcj", cj + "级");
                if (String.valueOf(item.get("multiSelectField_lw678e43")).length() > 0) {
                    List multi = UtilMap.getList(item, "multiSelectField_lw678e43");
                    dataList.get(i).put("multiSelectField_lw678e43_str", multi == null || multi.size() < 1 ? "" : String.join(",", multi));
                }
            }
            if (errmsg != "") {
                dataList.get(i).put("result", errmsg);
                flag = false;
            }
        }
        if (flag) {
            for (int i = 0; i < dataList.size(); i++) {
                Map item = dataList.get(i);
                String no = UtilMap.getString(item, "textField_lt2d2x79");
                String codeNo = getCode(no);
                if (charterMap.containsKey(codeNo)) {
                    dataList.get(i).put("associationFormField_lvy7yjq8", getAss(no, instIdList.get(no)));
                    dataList.get(i).put("textField_lyqprdyf", codeNo); // 序号
                } else {
                    // 新增
                    String category = UtilMap.getString(item, "selectField_lronu2g3");
                    String categoryNew = category.split("（")[1].replace("）", "");
                    no = noCP(UtilMap.getString(item, "textField_lt2d2x79"), categoryNew);
                    String fno = "";
                    int level = getSize(no);
                    dataList.get(i).put("selectField_lr4y2xcj", level + "级");
                    // 根据层级查询序号
                    String noNew = "";
                    // 处理结果
                    if (level > 1) {
                        fno = getCodeNo(categoryNew, noCP(UtilMap.getString(item, "textField_m0afm8pd"), categoryNew));
                    }
                    Map reMap = getMaxValue(list, level + "级", category, fno);
                    if (reMap != null) {
                        String id = UtilMap.getString(reMap, "id");
                        noNew = incrementLastPart(id);
                    } else {
                        noNew = level == 1 ? categoryNew + "001" : fno + ".1";
                    }
                    codeNo = noNew;
                    fno = getFnoValue(list, fno);
                    String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MMddHHmmssS"));
                    dataList.get(i).put("textField_lt2d2x79", noNew + "_" + nowTime);
                    dataList.get(i).put("textField_m0afm8pd", fno);
                    dataList.get(i).put("textField_lyqprdyf", codeNo); // 序号
                    // 拼装数据并新增需求
                    Map mapNew = dataList.get(i);
                    mapNew.put("textField_lth2h04b", charter);
                    mapNew.put("radioField_lroozhse", "是");
                    mapNew.put("textField_m0m3dyk4", fno);
                    mapNew.put("textField_lyqpt99s", codeNo);
                    mapNew.put("radioField_m0ow50wn", "是"); // 是否草稿
                    String id = (String) ydClient.operateData(YDParam.builder().appType("APP_YQY0OH7953OKBTM57PLL")
                            .systemToken("PGC66MB1H2RLXMFQ7XKW4BC3BDFJ2UDM909XL18")
                            .formUuid("FORM-7A52930D0E834522AD65A4CFE2C0818F1KQO")
                            .formDataJson(JSONObject.toJSONString(mapNew))
                            .build(), YDConf.FORM_OPERATION.create);
                    dataList.get(i).put("associationFormField_lvy7yjq8", getAss(noNew + "_" + nowTime, id));
                    mapNew.put("instanceId", id);
                    mapNew.put("id", codeNo);
                    list.add(mapNew);
                }
            }
        }
        return UtilMap.map("data, flag", dataList, flag);
    }

    private static String incrementLastPart(String input) {
        // 查找最后一个点号的位置
        int lastDotIndex = input.lastIndexOf('.');
        // 如果没有点号，则整个字符串都需要加1
        if (lastDotIndex == -1) {
            String q = input.substring(0, input.length() - 3);
            String h = input.substring(input.length() - 3);
            return q + String.format("%03d", Integer.parseInt(h) + 1);
        }
        // 分割字符串
        String prefix = input.substring(0, lastDotIndex + 1);
        String lastPart = input.substring(lastDotIndex + 1);
        // 对最后一部分加1
        String incrementedLastPart = incrementPart(lastPart);
        // 返回拼接后的结果
        return prefix + incrementedLastPart;
    }

    private static String incrementPart(String part) {
        // 将字符串转换为整数并加1
        int number = Integer.parseInt(part);
        number++;
        // 将整数转换回字符串
        return String.valueOf(number);
    }

    private static String getCodeNo(String category, String no) {
        int dotIndex = no.indexOf('.');
        String beforeDot = dotIndex == -1 ? no : no.substring(0, dotIndex);
        String afterDot = dotIndex == -1 ? "" : no.substring(dotIndex);
        // 对第一部分进行补零
        String paddedBeforeDot = String.format("%03d", Integer.parseInt(beforeDot));
        return category + paddedBeforeDot + afterDot;
    }

    private String getFnoValue(List<Map> list, String fno) {
        if (StringUtils.isBlank(fno)) {
            return "";
        }
        List<Map> list1 = list.stream()
                .filter(map -> UtilMap.getString(map, "textField_lt2d2x79").contains(fno + "_")).collect(Collectors.toList()); // 父编号查询编号
        if (list1 != null && list1.size() > 0) {
            return UtilMap.getString(list1.get(0), "textField_lt2d2x79");
        }
        return "";
    }

    private Map getMaxValue(List<Map> list, String level, String category, String fno) {
        // 查找符合条件的最大 id
        List<Map> list1 = list.stream()
                .filter(map -> UtilMap.getString(map, "selectField_lr4y2xcj").equals(level)) // 层级
                .filter(map -> UtilMap.getString(map, "textField_lt2d2x79").contains(fno)) // 父编号查询编号
                .filter(map -> UtilMap.getString(map, "selectField_lronu2g3").equals(category)).collect(Collectors.toList()); // 前缀
        Optional<Map> maxMap = list1.stream()
                .max(Comparator.comparing(map -> UtilMap.getString(map, "id")));
        return maxMap.orElse(null);
    }

    private Object getAss(String title, String id) {
        return Arrays.asList(UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_YQY0OH7953OKBTM57PLL", "FORM-7A52930D0E834522AD65A4CFE2C0818F1KQO", "receipt", id, title, ""));
    }

    private static int getSize(String value) {
        return value.split("\\.").length;
    }

    private Boolean isValidVersion(String version) {
        Pattern pattern = Pattern.compile("^([0-9]{1,3}(\\.[0-9]{1,3}){0,2})$");
        Matcher matcher = pattern.matcher(version);
        return matcher.matches();
    }

    private String noCP(String value, String category) {
        if (value.contains(category)) {
            return getCode(value).replace(category, "").replaceAll("^0+", "");
        } else {
            return value;
        }
    }

    private String getCode(String pCode) {
        if (!pCode.contains("_")) {
            return pCode;
        }
        if (isNumeric(pCode.split("_")[0])) {
            // 时间_序号
            return pCode.split("_")[1];
        } else if (isNumeric(pCode.split("_")[1])) {
            // 序号_时间
            return pCode.split("_")[0];
        }
        return pCode;
    }

    private boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^\\d+$");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
}
