package nckd.jxccl.sit.hcsi.business.datacomparison;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.swc.hsas.business.helper.HSASBizDataServiceHelper;
import nckd.jxccl.sit.hcsi.common.constant.SitConstant;

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

/**
 * 2025-11-19 Tyx
 * 数据比对推送前端业务数据服务类
 */
public class DataComparisonPushService {

    private static final Log logger = LogFactory.getLog(DataComparisonPushService.class);

    public DataComparisonPushService() {

    }

    /**
     * 实际执行推送数据
     */
    public Map doPush(List<DynamicObject> entryList, Date bsed) {
        Map param = buildParam(entryList, bsed);
        Map response = HSASBizDataServiceHelper.synBizData(param);
        logger.info("推送数据返回结果：" + response);
        return response;
    }

    /**
     * 构建参数，数据比对中一行分录会生成两行业务数据
     *
     * @return
     */
    public Map buildParam(List<DynamicObject> entryList, Date bsed) {
        Map map = new HashMap();
        map.put("operate", "1");    //1-新增 2-更正
        map.put("opsystem", "社保数据比对");

        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        Map<String,Long> bizItemMap = getBizItemId();

        Map<Long, Long> empposorgMap = getEmpPosOrgRelIds(entryList, bsed);

        for(DynamicObject entry : entryList) {
            // 个人缴费金额
            Map<String, Object> dataMapA = new HashMap();
            // 个人补缴金额
            Map<String, Object> dataMapB = new HashMap();
            //获取险种编码
            String welfaretypeNo = entry.getString("welfaretypeid.number");

            //bizdatacode 前端业务数据识别码（唯一） 这里用分录ID+分隔符判断
            dataMapA.put("bizdatacode", entry.getPkValue().toString() + SitConstant.SeparatorA);
            dataMapB.put("bizdatacode", entry.getPkValue().toString() + SitConstant.SeparatorB);
            //batchcode 批次号 直接用分录ID
            dataMapA.put("batchcode", entry.getPkValue().toString());
            dataMapB.put("batchcode", entry.getPkValue().toString());
            //业务项目ID 业务项目上新增了一个字段【nckd_matchkey】 = 险种编码 + _A / _B， A : 个人缴费，B ： 个人补缴
            dataMapA.put("bizitemid", bizItemMap.get(welfaretypeNo + SitConstant.SeparatorA));
            dataMapB.put("bizitemid", bizItemMap.get(welfaretypeNo + SitConstant.SeparatorB));
            //employee
            dataMapA.put("employeeid", entry.getLong("employee.id"));
            dataMapB.put("employeeid", entry.getLong("employee.id"));
            //value
            BigDecimal valueA = entry.getBigDecimal("personsysvalue");
            BigDecimal valueB = entry.getBigDecimal("personsysvaluea");
            dataMapA.put("value", valueA);
            dataMapB.put("value", valueB);
            //empposorgrelid 计薪人员任职经历
            Long empPosOrgRelId = empposorgMap.get(entry.getLong("employee.id"));
            dataMapA.put("empposorgrelid", empPosOrgRelId);
            dataMapB.put("empposorgrelid", empPosOrgRelId);
            //datasources 数据来源 90 - 社保数据比对
            dataMapA.put("datasources", "90");
            dataMapB.put("datasources", "90");
            //srcsystem 前端系统
            dataMapA.put("srcsystem", "hpdi");
            dataMapB.put("srcsystem", "hpdi");

            //startdate
            dataMapA.put("startdate", bsed);
            dataMapB.put("startdate", bsed);

            //currencyid
            dataMapA.put("currencyid", "1");
            dataMapB.put("currencyid", "1");

            //备注 description
            dataMapA.put("description", entry.getString("nckd_remark"));
            dataMapB.put("description", entry.getString("nckd_remark"));

            //2026-01-08 Tyx 为0不跳过
            data.add(dataMapA);
            data.add(dataMapB);
//            // 如果value = 0 则跳过这条数据
//            if(valueA.compareTo(BigDecimal.ZERO) > 0) {
//                data.add(dataMapA);
//            }
//            if(valueB.compareTo(BigDecimal.ZERO) > 0) {
//                data.add(dataMapB);
//            }
         }
        map.put("data", data);
        return map;
    }


    /**
     * 获取业务项目ID
     * 取业务项目类别.编码 = JT004
     * @return
     */
    public Map<String, Long> getBizItemId() {
        QFilter filter = new QFilter("bizitemcategory.number", QCP.equals, "JT004");
        String selectFields = "id,nckd_matchkey";
        DynamicObjectCollection cols = SitConstant.BIZITEM_HELPER.queryOriginalCollection(selectFields, new QFilter[]{filter});
        Map<String,Long> map = cols.stream().collect(Collectors.toMap((dyx) -> {
            return dyx.getString("nckd_matchkey");
        }, (dyx) -> {
            return dyx.getLong("id");
        }, (key1, key2) -> {
            return key2;
        }));
        return map;
    }

    public Map<Long, Long> getEmpPosOrgRelIds(List<DynamicObject> list, Date date) {
        Set employeeIds = list.stream().map(i -> i.getLong("employee.id")).collect(Collectors.toSet());
        QFilter filter = new QFilter("employee.id", QCP.in, employeeIds);
        filter.and("startdate", QCP.less_equals, date);
        filter.and("enddate", QCP.large_equals, date);
        filter.and("isprimary", QCP.equals, "1");
        HRBaseServiceHelper helper = new HRBaseServiceHelper("hrpi_empposorgrel");
        String selectFields = "id,employee.id";
        DynamicObjectCollection cols = helper.queryOriginalCollection(selectFields, new QFilter[]{filter});
        Map<Long, Long> map = cols.stream().collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("employee.id");
        }, (dyx) -> {
            return dyx.getLong("id");
        }, (key1, key2) -> {
            return key2;
        }));
        return map;
    }


}
