package nckd.jxccl.sit.hcsi.utils;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.util.StringUtils;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.sit.sitbp.common.StdDimDTO;
import kd.sdk.sit.sitbp.common.StdInsuranceItemDTO;
import kd.sdk.sit.sitbp.common.StdResultInfoDTO;
import nckd.jxccl.sit.hcsi.common.constant.SitConstant;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class SITCoordinationUtils {

    /**
     * 处理参保标准的结果
     * @param stdResultInfoDTO
     * @param sinSurStd
     * @param welfaretype
     * @param sinSurDimension Key = 险种属性ID， value = 参保标准中设置的值
     * @return
     */
    public Map<Long, Object> dealStdResult (StdResultInfoDTO stdResultInfoDTO, DynamicObject sinSurStd, DynamicObject welfaretype, DynamicObject sinSurDimension) {
        List<StdResultInfoDTO.StdInsurTypeResultInfoDTO> stdInsurTypeResultInfoDTOS = stdResultInfoDTO.getStdInsurTypeResultInfoDTOS();
        // 根据 insurTypeId 和 baseDataId 查找目标数据
        Long insurTypeId = welfaretype.getLong("id"); // 险种ID
        Long baseDataId = 0L;
        if(sinSurDimension != null) {
            baseDataId = sinSurDimension.getLong("id");
        }

        Map<Long, Object> result = new HashMap<>();

        for (StdResultInfoDTO.StdInsurTypeResultInfoDTO dto : stdInsurTypeResultInfoDTOS) {
            // 匹配 insurTypeId
            if (dto.getInsurTypeId() != null && dto.getInsurTypeId().equals(insurTypeId)) {
                // 遍历 stdDimRlslnfos
                List<StdResultInfoDTO.StdDimRsInfo> stdDimRlslnfos = dto.getStdDimRsInfos();
                if (stdDimRlslnfos != null) {
                    for (StdResultInfoDTO.StdDimRsInfo stdDimRlslnfo : stdDimRlslnfos) {
                        List<StdDimDTO> stdDimDTOs = stdDimRlslnfo.getStdDimDTOs();
                        if (stdDimDTOs.size() > 0) {
                            for (StdDimDTO stdDimDTO : stdDimDTOs) {
                                // 查找匹配的 baseDataId
                                if(stdDimDTO.getBaseDataId().equals(baseDataId)) {
                                    List<StdInsuranceItemDTO> list = stdDimRlslnfo.getStdInsuranceItemDTOs();
                                    for (StdInsuranceItemDTO itemDTO : list) {
                                        if(itemDTO.getInsurPropId() == 1030L || itemDTO.getInsurPropId() == 1040L) {
                                            BigDecimal itemValue = itemDTO.getItemValue() == null ? BigDecimal.ZERO : itemDTO.getItemValue();
                                            result.put(itemDTO.getInsurPropId(), itemValue.multiply(new BigDecimal("100")));
                                        }
                                        else {
                                            BigDecimal itemValue = itemDTO.getItemValue() == null ? BigDecimal.ZERO : itemDTO.getItemValue();
                                            result.put(itemDTO.getInsurPropId(), itemValue);
                                        }
                                    }
                                }
                            }
                        }
                        else if (stdDimDTOs.size() == 0 && baseDataId == 0L){
                            List<StdInsuranceItemDTO> list = stdDimRlslnfo.getStdInsuranceItemDTOs();
                            for (StdInsuranceItemDTO itemDTO : list) {
                                if(itemDTO.getInsurPropId() == 1030L || itemDTO.getInsurPropId() == 1040L) {
                                    BigDecimal itemValue = itemDTO.getItemValue() == null ? BigDecimal.ZERO : itemDTO.getItemValue();
                                    result.put(itemDTO.getInsurPropId(), itemValue.multiply(new BigDecimal("100")));
                                }
                                else {
                                    BigDecimal itemValue = itemDTO.getItemValue() == null ? BigDecimal.ZERO : itemDTO.getItemValue();
                                    result.put(itemDTO.getInsurPropId(), itemValue);
                                }
                            }
                        }
                    }
                }
            }
        }

        return result; // 返回空 map 表示未找到
    }

    public List<Long> queryDimensionValue(Long stdId, Long welfaretypeId) {
        List<Long> dimIds = new ArrayList<Long>();
        List<Long> baseDataIds = new ArrayList<Long>();
        DynamicObject stdDyn = SitConstant.SINSURSTD_HELPER.loadOne(stdId);
        DynamicObjectCollection entryCols = stdDyn.getDynamicObjectCollection("stdentryentity");
        for (DynamicObject entry : entryCols) {
            if(entry.getLong("insurtype.id") != welfaretypeId) {
                continue;
            }
            else {
                DynamicObjectCollection mulDatas = entry.getDynamicObjectCollection("mulstddimrs");
                dimIds.addAll(mulDatas.stream().map(obj -> obj.getDynamicObject("fbasedataid").getLong("id")).collect(Collectors.toList()));
            }
        }

        if(dimIds.size() > 0) {
            QFilter filter = new QFilter("id", QCP.in, dimIds);
            DynamicObjectCollection dynCols = SitConstant.STDDIMRS_HELPER.queryOriginalCollection("dimentryentity.basedata", filter.toArray());
            baseDataIds.addAll(dynCols.stream().map(dyn -> dyn.getLong("dimentryentity.basedata")).collect(Collectors.toList()));
        }

        return baseDataIds;
    }

    /**
     * 获取险种可编辑的字段配置
     * @param welfareTypeIds
     * @param insuranceTypeAttrs
     * @return
     */
    public static Map<Long, Map<Long, Boolean>> queryInsuranceTypeAttrSetting(Collection<Long> welfareTypeIds, Collection<Long> insuranceTypeAttrs) {
        // 初始化结果Map，使用类型安全的声明
        Map<Long, Map<Long, Boolean>> result = new HashMap<>(welfareTypeIds.size());

        // 初始化每个险种类型的属性映射
        for (Long welfareTypeId : welfareTypeIds) {
            Map<Long, Boolean> map = new HashMap<>(insuranceTypeAttrs.size());
            for (Long insuranceTypeAttrId : insuranceTypeAttrs) {
                map.put(insuranceTypeAttrId, Boolean.FALSE);
            }
            result.put(welfareTypeId, map);
        }

        // 构建查询条件
        QFilter inSurTypeQFilter = new QFilter("insurtype", "in", welfareTypeIds);
        QFilter enableQFilter = new QFilter("enable", "=", "1");
        QFilter statusQFilter = new QFilter("status", "=", "C");
        QFilter currentQFilter = new QFilter("iscurrentversion", "=", Boolean.TRUE);

        inSurTypeQFilter.and(enableQFilter)
                .and(statusQFilter)
                .and(currentQFilter);

        // 执行查询
        DynamicObject[] sinSurStdCfgDynamicObjects = new HRBaseServiceHelper("sitbs_sinsurstdcfg")
                .load("rentryentity.insuritem,insurtype", new QFilter[]{inSurTypeQFilter});

        // 处理查询结果
        for (DynamicObject sinSurStdCfgDynamicObject : sinSurStdCfgDynamicObjects) {
            Long welfareTypeId = sinSurStdCfgDynamicObject.getLong("insurtype.id");
            Map<Long, Boolean> insuranceTypeAttrMap = result.get(welfareTypeId);

            if (insuranceTypeAttrMap != null) {
                DynamicObjectCollection rentryentity = sinSurStdCfgDynamicObject.getDynamicObjectCollection("rentryentity");
                for (DynamicObject dynamicObject : rentryentity) {
                    DynamicObject insuranceItem = dynamicObject.getDynamicObject("insuritem");
                    if (insuranceItem != null) {
                        Long attrId = insuranceItem.getLong("insurancetypeattr.id");
                        if (insuranceTypeAttrMap.containsKey(attrId)) {
                            insuranceTypeAttrMap.put(attrId, Boolean.TRUE);
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * 根据险种判断参保标准是否启用了险种维度
     * @param map
     * @param insurTypeId 险种ID
     */
    public boolean getEnableDimByInsurTypeId(Map<Long, StdResultInfoDTO.StdInsurTypeResultInfoDTO> map, Long insurTypeId) {
        StdResultInfoDTO.StdInsurTypeResultInfoDTO infoDTO = map.get(insurTypeId);
        List<StdResultInfoDTO.StdDimRsInfo> stdDimRsInfoList = infoDTO.getStdDimRsInfos();
        for (StdResultInfoDTO.StdDimRsInfo stdDimRsInfo : stdDimRsInfoList) {
            List<StdDimDTO> stdDimDTOList = stdDimRsInfo.getStdDimDTOs();
            for (StdDimDTO stdDimDTO : stdDimDTOList) {
                String fieldKey = stdDimDTO.getField();
                if(!StringUtils.isEmpty(fieldKey)) {
                    if(fieldKey.contains("nckd_sinsurdima")) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 根据员工获取所有参保中的险种基数
     * 社保基数.开始日期 <= 当前日期 <= 社保基数.结束日期
     * 社保基数.是否参保 = 是
     * 社保基数.社保档案.社保状态 = 正常缴纳
     * @param employeeId
     * @return
     */
    public static DynamicObject[] getSiBaseByEmployeeId(Long employeeId) {
        QFilter filter = new QFilter("employee.id", QCP.equals, employeeId);
        filter.and("insured", QCP.equals, true);
        filter.and("startdate", QCP.less_equals, new Date());
        filter.and("enddate", QCP.large_equals, new Date());
        filter.and("sinsurfile.sinsurstatus", QCP.equals, "normal");
        String selectFields = "startdate,enddate,insured,welfaretype,paybaseofemployee,paybaseofcompany,nckd_sinsurdimension,welfarepayer,nckd_welfarepayertheory,description";
        DynamicObject[] sibaseCols = SitConstant.SIBASE_HELPER.load(selectFields, filter.toArray());
        return sibaseCols;
    }


    /**
     * 字段映射：
     * 用于调入类型核定单自动携带险种基数信息时
     * k = 社保基数设置上字段名， v = 核定单分录上字段名
     * @return
     */
    public static Map<String, String> getFieldsMappingMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("nckd_welfarepayertheory","nckd_welfarepayertheory");
        map.put("welfarepayer","nckd_welfarepayer");
        map.put("welfaretype","nckd_welfaretype");
        map.put("nckd_sinsurdimension","nckd_sinsurdimension");
        map.put("insured","nckd_insured");
        map.put("paybaseofemployee","nckd_paybaseofemployee");
        map.put("paybaseofcompany","nckd_paybaseofcompany");
        map.put("startdate","nckd_startdate");
        map.put("enddate","nckd_enddate");
        map.put("description","nckd_description");
        return map;
    }


}
