package nckd.jxccl.sit.hcsi.business.coordination.api;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.business.coordination.api.ext.CoordBizSaveHandler;
import kd.hr.hbp.business.coordination.model.CoordBizContext;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;

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

/**
 * Tyx 2025-10-28
 * 社保档案处理器，生成社保档案头之后，保存核定单分录的险种基数设置信息。
 */
public class SinsurCoordBizSaveHandler implements CoordBizSaveHandler {

    private static final Log log = LogFactory.getLog(SinsurCoordBizSaveHandler.class);
    private static HRBaseServiceHelper SIBASE_HELPER = new HRBaseServiceHelper("hcsi_sibase");
    private static String SIBASE_ENTITY = "hcsi_sibase";
    //字段对应的Map, k = 核定单分录字段标识, v = 社保档案险种基数设置字段标识
    private static Map<String, String> fieldMap = new HashMap<String, String>();
    static {
        fieldMap.put("nckd_welfaretype","welfaretype");
        fieldMap.put("nckd_insured","insured");
        fieldMap.put("nckd_paybaseofemployee","paybaseofemployee");
        fieldMap.put("nckd_paybaseofcompany","paybaseofcompany");
        fieldMap.put("nckd_startdate","startdate");
        fieldMap.put("nckd_enddate","enddate");
        fieldMap.put("nckd_description","description");
        fieldMap.put("nckd_sinsurdimension","nckd_sinsurdimension");
    }

    /**
     * 实际处理方法
     * @param map key = hcsi_sinsurfile, value = 社保档案Dyn
     * @param map1 unknown
     * @param dynamicObject 核定单Dyn
     * @param coordBizContext 协作业务上下文
     * @return
     */
    @Override
    public Map<String, Object> handle(Map<String, DynamicObject> map, Map<String, Map<String, Object>> map1, DynamicObject dynamicObject, CoordBizContext coordBizContext) {
        log.info(" -------- begin SinsurCoordBizSaveHandler handle --------");
        // 返回的Map
        Map<String, Object> returnMap = new HashMap<String, Object>();
        DynamicObject sinsurFile = map.get("hcsi_sinsurfile");
        if(!ObjectUtils.isEmpty(sinsurFile)) {
            log.info("-------- 当前处理社保档案编号 = " + sinsurFile.getString("number"));
            DynamicObjectCollection sibaseCols = new DynamicObjectCollection();
            // 获取档案Id
            Long fileId = sinsurFile.getLong("id");
            // 获取核定单分录数据
            DynamicObjectCollection entryCols = dynamicObject.getDynamicObjectCollection("nckd_entryentity");

            // 只处理分录数据中实际参保单位与单头一致的数据
            Long welfarePayerId = dynamicObject.getLong("welfarepayer_r31.id");
            List<DynamicObject> list = entryCols.stream().filter(entry -> entry.getLong("nckd_welfarepayer.id") == welfarePayerId).collect(Collectors.toList());
            for (DynamicObject entry : list) {
                // 新建数据包
                DynamicObject dyn = BusinessDataServiceHelper.newDynamicObject(SIBASE_ENTITY);
                // 设置字段，单独处理下【档案，计薪人员，实际参保单位，理论参保单位】其余字段从fieldMap从处理；
                dyn.set("sinsurfile", sinsurFile);
                dyn.set("employee", sinsurFile.getDynamicObject("employee"));
                dyn.set("welfarepayer", sinsurFile.getDynamicObject("welfarepayer"));
                dyn.set("nckd_welfarepayertheory", sinsurFile.getDynamicObject("welfarepayertheory"));
                //dyn.set("id", UUID.randomUUID().toString());
                Iterator it = fieldMap.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next().toString();
                    dyn.set(fieldMap.get(key), entry.get(key));
                }
                sibaseCols.add(dyn);
            }
            if (sibaseCols.size() > 0) {
                OperationResult result = SaveServiceHelper.saveOperate(SIBASE_ENTITY, sibaseCols.stream().toArray(DynamicObject[]::new), OperateOption.create());
                // 标品SinSurFileCoordServiceHelper.saveBizObject方法中，判断success写反了，这里暂时反着写，后续等标品调整
                // TODO
                if (result.isSuccess()) {
                    returnMap.put("success", false);
                } else {
                    throw new KDBizException("-------- 险种基数保存失败：" + result.getMessage());
                    //returnMap.put("success",true);
                    //returnMap.put("msg", result.getMessage());
                }
                log.info("-------- bizSaveHandler result = " + result + " --------");
            }
            else {
                returnMap.put("success", false);
            }
        }
        return returnMap;
    }
}
