package com.lideeyunji.core.framework.config.btncommand.filter;

import com.lideeyunji.core.framework.entity.FormFieldEntity;
import com.lideeyunji.core.framework.mapper.AdapterMapper;
import com.lideeyunji.core.framework.mapper.FormFieldWebMapper;
import com.lideeyunji.core.framework.service.IFormService;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.tool.framework.yunji.tool.spring.SpringUtils;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import com.lideeyunji.tool.framework.yunji.utils.lideeYunJiUtils;
import com.lideeyunji.tool.framework.ip.core.Area;
import com.lideeyunji.tool.framework.ip.core.utils.AreaUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 格式化字段显示
 */
public class FormatCriteriaList implements CriteriaList{


    @Override
    public void meetCriteria(Long dbformId,List<Map<String, Object>> dataMapList) {
        FormFieldWebMapper fieldWebMapper = SpringUtils.getBean(FormFieldWebMapper.class);
        AdapterMapper adapterMapper = SpringUtils.getBean(AdapterMapper.class);
        IFormService formService = SpringUtils.getBean(IFormService.class);

        if (FuncBase.isEmpty(dataMapList)) {
            return;
        }

        //处理用户和部门
        List<String> userKeyList = fieldWebMapper.getUserControlTypeFieldCodeList(dbformId);//那些字段是用户控件
        List<String> deptKeyList = fieldWebMapper.getDeptControlTypeFieldCodeList(dbformId);//那些字段是部门控件
        List<String> areaKeyList = fieldWebMapper.getAreaControlTypeFieldCodeList(dbformId);//那些字段是区域控件

        //用户
        Map<Long, String> nickNameMap = new HashMap<>();
        if (FuncBase.isNotEmpty(userKeyList)) {
            List<Map<String, Object>> allNickNameList = adapterMapper.getAllNickNameList();
            nickNameMap = allNickNameList.stream()
                    .collect(Collectors.toMap(
                            map -> Func.getMap2Long(map, "id"),
                            map -> Func.getMap2Str(map, "nickname"),
                            (existing, replacement) -> existing)); // 处理重复key的情况，保留第一个值
        }
        //部门
        Map<Long, String> deptNameMap = new HashMap<>();
        if (FuncBase.isNotEmpty(deptKeyList)) {
            List<Map<String, Object>> deptNameMapList = adapterMapper.getAllDeptNameList();
            deptNameMap = deptNameMapList.stream()
                    .collect(Collectors.toMap(
                            map -> Func.getMap2Long(map, "id"),
                            map -> Func.getMap2Str(map, "name"),
                            (existing, replacement) -> existing)); // 处理重复key的情况，保留第一个值
        }


        //字典集合
        List<FormFieldEntity> fieldList = formService.getFieldList(dbformId);
        Map<String, Map<String, String>> dictMaps = new HashMap<>();
        List<String> dictKeyList = new ArrayList<>();
        for (FormFieldEntity formFieldEntity : fieldList) {
            String fieldCode = formFieldEntity.getFieldCode();
            Map<String, String> dictMap = formService.getDictKeyLabelMap(dbformId, fieldCode);//字典列表
            if (FuncBase.isNotEmpty(dictMap)) {//有配置字典
                dictMaps.put(fieldCode, dictMap);
                dictKeyList.add(fieldCode);
            }
        }
        //数据里面会存在id，或者字典等，如：1=男，需要转为文字
        Map<Long, String> finalNickNameMap = nickNameMap;
        Map<Long, String> finalDeptNameMap = deptNameMap;
        dataMapList.forEach(dataMap -> {
            //处理字典
            for (String key : dictKeyList) {
                String val = lideeYunJiUtils.getMap2Str(dataMap, key);
                if (FuncBase.isEmpty(val)) {
                    continue;
                }
                Map<String, String> valMap = dictMaps.get(key);
                String valStr = valMap.get(val);
                if (Func.isEmpty(valStr) && val.contains(",")) {
                    List<String> valList = Func.toStrList(val);
                    for (String tmpVal : valList) {//有可能是多选的情况下111,222,333
                        String tmpValStr = valMap.get(tmpVal);
                        if (Func.isEmpty(tmpValStr)) {
                            continue;
                        }
                        if (Func.isEmpty(valStr)) {
                            valStr = tmpValStr;
                        } else {
                            valStr += "、" + tmpValStr;
                        }

                    }
                }

                if (FuncBase.isEmpty(valStr)) {
                    continue;
                }
                dataMap.put(key, valStr);
            }
            //处理用户
            for(String key : userKeyList){
                String valStr = lideeYunJiUtils.getMap2Str(dataMap, key);
                if (FuncBase.isEmpty(valStr)) {
                    continue;
                }
                String nicknames="";
                //有可能是多选
                List<String> userIdList = Func.toStrList(valStr);
                for (String userId : userIdList) {//有可能是多选的情况下111,222,333
                    //获取名称
                    String nickname = finalNickNameMap.get(Func.toLong(userId));

                    if (Func.isEmpty(nickname)) {
                        continue;
                    }
                    if (Func.isEmpty(nicknames)) {
                        nicknames = nickname;
                    } else {
                        nicknames += "、" + nickname;
                    }
                }

                if (FuncBase.isEmpty(nicknames)) {
                    continue;
                }
                dataMap.put(key, nicknames);
            }
            //处理部门
            for(String key : deptKeyList){
                String valStr = lideeYunJiUtils.getMap2Str(dataMap, key);
                if (FuncBase.isEmpty(valStr)) {
                    continue;
                }
                String deptnames="";
                //有可能是多选
                List<String> deptIdList = Func.toStrList(valStr);
                for (String deptId : deptIdList) {//有可能是多选的情况下111,222,333
                    //获取名称
                    String deptName = finalDeptNameMap.get(Func.toLong(deptId));

                    if (Func.isEmpty(deptName)) {
                        continue;
                    }
                    if (Func.isEmpty(deptnames)) {
                        deptnames = deptName;
                    } else {
                        deptnames += "、" + deptName;
                    }
                }

                if (FuncBase.isEmpty(deptnames)) {
                    continue;
                }
                dataMap.put(key, deptnames);
            }
            //处理区域
            for(String key : areaKeyList){
                String valStr = lideeYunJiUtils.getMap2Str(dataMap, key);
                if (FuncBase.isEmpty(valStr)) {
                    continue;
                }
                //转为字符串
                String areaListStr = Func.formatArea(valStr);
                if(Func.isEmpty(areaListStr)){
                    continue;
                }
                List<String> areaList = Func.toStrList(areaListStr);
                if(Func.isEmpty(areaList)){
                    continue;
                }
                List<String> nameList = new ArrayList<>();
                for(String area : areaList){
                    List<String> areaIdList = Func.toStrList("/", area);
                    List<String> areaNameList = new ArrayList<>();
                    for(String areaId:areaIdList){
                        try{
                            Area areaObj = AreaUtils.getArea(Func.toInt(areaId));
                            String name = areaObj.getName();
                            areaNameList.add(name);
                        }catch (Exception e){

                        }
                    }
                    nameList.add(String.join("/", areaNameList));
                }

                if (FuncBase.isEmpty(nameList)) {
                    continue;
                }
                dataMap.put(key, String.join("、", nameList));
            }

            // 转换并格式化所有值
            Map<String, String> formattedMap = dataMap.entrySet().stream()
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            entry -> lideeYunJiUtils.formatDate(entry.getValue())
                    ));

            // 使用格式化后的映射替换原始映射
            dataMap.clear();
            dataMap.putAll(formattedMap);
        });

    }


}
