package nckd.jxccl.hr.homs.business.application.event;

import kd.bos.bec.api.IEventServicePlugin;
import kd.bos.bec.model.EntityEvent;
import kd.bos.bec.model.KDBizEvent;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.coderule.opplugin.util.OrgUtil;
import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.QueryEntityType;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.business.servicehelper.HRQueryEntityHelper;
import kd.hr.hbp.common.util.HRArrayUtils;
import kd.hr.hbp.common.util.HRDateTimeUtils;
import kd.hr.hbp.common.util.HRObjectUtils;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.sdk.hr.hbp.business.helper.ruleengine.RuleEngineServiceHelper;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.hr.homs.common.application.event.GECEventConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 入职生成劳动合同事件服务插件
 * @author: jtd
 * @date: 2025/11/23 20:56
 */
public class GenerateEmploymentContractEventServicePlugin implements IEventServicePlugin {
    private static final Log LOGGER = LogFactory.getLog(GenerateEmploymentContractEventServicePlugin.class);
    /** 入职变动大类ID */
    private static final Long CHGEVENT_ID = 1010L;
    /** 应用编码 */
    private static final String BIZAPP = "hlcm";
    /** 场景编码 */
    private static final String SCENE_NUMBER = "ContractApplyNew";
    /** 业务组织编码 */
    private static final String BU_NUMBER = "01";
    /** 场景输入参数-劳动合同新签申请 */
    private static final String HLCM_CONTRACTAPPLYNEW = "hlcm_contractapplynew";
    /** 场景输出参数-合同模板 */
    private static final String HLCM_CONTRACTTEMPLATE = "hlcm_contracttemplate";
    /** 根据组织分配查询员工信息 */
    private static final String GET_EMPLOYEE_INFO_QUERY = "getemployeeinfoquery";

    @Override
    public Object handleEvent(KDBizEvent evt) {
        try {
            EntityEvent entityEvent = (EntityEvent) evt;
            // 获取 事务变动记录ID
            List<String> businessKeys = entityEvent.getBusinesskeys();
            if (CollectionUtils.isEmpty(businessKeys)) {
                LOGGER.warn("GenerateEmploymentContractEventServicePlugin businessKeys is empty, nothing to process.");
                return null;
            }
            // 根据变动事务ID判断变动大类是否入职
            List<Long> longList = entityEvent.getBusinesskeys().stream().map(Long::valueOf).collect(Collectors.toList());
            // 变动大类
            String chgeventKey = String.join(".", GECEventConstant.CHGCATEGORY_KEY, GECEventConstant.CHGEVENT_KEY);
            // 数据idKey
            String dataidKey = String.join(".", GECEventConstant.ENTRY_ENTITY_KEY, GECEventConstant.DATAID_KEY);
            // 过滤 事务变动ID 并且 变动大类=入职 并且 变动实体编码=组织分配 并且 数据变化=新增
            QFilter qFilter = new QFilter(GECEventConstant.ID_KEY, QCP.in, longList)
                    .and(new QFilter(chgeventKey, QCP.equals, CHGEVENT_ID))
                    .and(new QFilter(String.join(".", GECEventConstant.ENTRY_ENTITY_KEY, GECEventConstant.CHGENTITY_KEY, GECEventConstant.NUMBER_KEY), QCP.equals, GECEventConstant.ASSIGNMENT_ENTITYID))
                    .and(new QFilter(String.join(".", GECEventConstant.ENTRY_ENTITY_KEY, GECEventConstant.CHGMODE_KEY), QCP.equals, "0"));
            // 获取事务变动记录
            DynamicObject[] records = HRBaseServiceHelper.create(GECEventConstant.HPFS_CHGRECORD_ENTITY).queryOriginalArray(dataidKey, new QFilter[]{qFilter});
            if (HRArrayUtils.isEmpty(records)) {
                LOGGER.warn("GenerateEmploymentContractEventServicePlugin is empty, nothing to process.");
                return null;
            }
            // 获取组织分配ID
            List<Long> assignmentIds = Arrays.stream(records).map(record -> record.getLong(dataidKey)).collect(Collectors.toList());
            // 生成劳动合同
            generateEmploymentContract(assignmentIds);
            return null;
        } catch (Exception e) {
            LOGGER.error("GenerateEmploymentContractEventServicePlugin Error processing KDBizEvent: {}", e.getMessage(), e);
            throw e;
        }
    }

    private void generateEmploymentContract(List<Long> assignmentIds) throws KDException {
        LOGGER.info("GenerateEmploymentContractEventServicePlugin assignmentIds: [{}]", assignmentIds);
        // hrpi_assignment.id
        String assignmentIdKey = String.join(".", GECEventConstant.ASSIGNMENT_ENTITYID, GECEventConstant.ID_KEY);
        // 查询字段
        String queryFields = QueryFieldBuilder.create()
                .add(GECEventConstant.HRPI_PERCONTACT_PHONE)
                .add(GECEventConstant.HRPI_TRIALPERIOD_PROBATION)
                .add(GECEventConstant.HRPI_TRIALPERIOD_PROBATIONUNIT)
                .add(GECEventConstant.HRPI_TRIALPERIOD_PREENDDATE)
                .add(GECEventConstant.HRPI_TRIALPERIOD_TRIALSTARTDATE)
                .add(GECEventConstant.HOUSEHOLDREGISTER_ADDRESSTYPE_ID)
                .add(GECEventConstant.HOUSEHOLDREGISTER_ADDRESSINFO)
                .add(GECEventConstant.RESIDENTIALADDRESS_ADDRESSTYPE_ID)
                .add(GECEventConstant.RESIDENTIALADDRESS_ADDRESSINFO)
                .add(GECEventConstant.HRPI_PERCRE_CREDENTIALSTYPE_ID)
                .add(GECEventConstant.HRPI_PERCRE_NUMBER)
                .add(GECEventConstant.CNIDCARD_CREDENTIALSTYPE_ID)
                .add(GECEventConstant.CNIDCARD_NUMBER)
                .add(GECEventConstant.HAOS_ADMINORGHRF7_CORPORATEORG_ID)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_STARTDATE)
                .add(GECEventConstant.HRPI_EMPLOYEE_ID)
                .add(GECEventConstant.HRPI_EMPLOYEE_EMPNUMBER)
                .add(GECEventConstant.HRPI_EMPLOYEE_NAME)
                .add(GECEventConstant.HRPI_EMPLOYEE_NATIONALITY_ID)
                .add(GECEventConstant.HRPI_EMPLOYEE_NATIONALITY_NUMBER)
                .add(GECEventConstant.HAOS_ADMINORGHRF7_BELONGCOMPANY_ID)
                .add(GECEventConstant.HAOS_ADMINORGHRF7_BELONGCOMPANY_SOURCEVID)
                .add(GECEventConstant.HAOS_ADMINORGHRF7_ID)
                .add(GECEventConstant.HAOS_ADMINORGHRF7_SOURCEVID)
                .add(GECEventConstant.HBPM_POSITIONHR_ID)
                .add(GECEventConstant.HBPM_POSITIONHR_SOURCEVID)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_JOB_NUMBER)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_POSTYPE_NUMBER)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_ORGRELSEQ)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_ASSIGNMENT_NUMBER)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_ASSIGNMENT_ORG_NUMBER)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_ASSIGNMENT_EMPLOYEE_EMPNUMBER)
                .add(GECEventConstant.HRPI_EMPPOSORGREL_WORKPLACE_NUMBER)
                .buildSelect();
        // 过滤条件
        QFilter qFilter = new QFilter(assignmentIdKey, QCP.in, assignmentIds);
        qFilter.and(GECEventConstant.ISPRIMARY_KEY, QCP.equals, EnableEnum.YES.getCode());
        // 排序字段
        String orderBys = QueryFieldBuilder.create().orderBy(GECEventConstant.HRPI_EMPPOSORGREL_STARTDATE, assignmentIdKey).buildOrder();
        // 根据组织分配获取员工信息
        QueryEntityType queryEntityType = (QueryEntityType) MetadataServiceHelper.getDataEntityType(GET_EMPLOYEE_INFO_QUERY);
        DynamicObjectCollection personInfoColl = HRQueryEntityHelper.getInstance().getQueryDyoColl(queryEntityType, queryFields, new QFilter[]{qFilter}, orderBys);
        // 获取法律实体
        List<Long> corporateorgIds = personInfoColl.stream().map(personInfo -> personInfo.getLong(GECEventConstant.HAOS_ADMINORGHRF7_CORPORATEORG_ID)).collect(Collectors.toList());
        // 获取聘用单位
        DynamicObject[] signCompanyDyos = HRBaseServiceHelper.create(GECEventConstant.HBSS_SIGNCOMPANY_ENTITY).query(String.join(",", GECEventConstant.LAWENTITY_KEY, GECEventConstant.VID_KEY), new QFilter[]{new QFilter(GECEventConstant.LAWENTITY_KEY, QCP.in, corporateorgIds)});
        // 处理成 key->法律实体ID value->聘用单位ID
        Map<Long, DynamicObject> signCompanyMap = Arrays.stream(signCompanyDyos).collect(Collectors.toMap(signCompanyDyo -> signCompanyDyo.getDynamicObject(GECEventConstant.LAWENTITY_KEY).getLong(GECEventConstant.ID_KEY), signCompanyDyo -> signCompanyDyo, (oldValue, newValue) -> newValue));
        // 构建 劳动合同新签对象
        List<DynamicObject> contractApplyNewDyoList = new ArrayList<DynamicObject>();
        HRBaseServiceHelper contractApplyNewServiceHelper = new HRBaseServiceHelper(GECEventConstant.HLCM_CONTRACTAPPLYNEW_ENTITY);
        for (DynamicObject personInfo : personInfoColl) {
            DynamicObject contractApplyNewDyo = contractApplyNewServiceHelper.generateEmptyDynamicObject();

            // 组织分配ID
            Long assignmentId = personInfo.getLong(assignmentIdKey);
            // 设置 单据编号和合同编号
            CodeRuleInfo codeRuleInfo = CodeRuleServiceHelper.getCodeRule(contractApplyNewDyo.getDataEntityType().getName(), contractApplyNewDyo, OrgUtil.getMainOrgId(contractApplyNewDyo));
            if (codeRuleInfo == null) {
                throw new KDBizException(String.format("没有可使用的编码规则,组织分配ID[%s]", assignmentId));
            }
            String number = CodeRuleServiceHelper.readNumber(codeRuleInfo, contractApplyNewDyo);
            contractApplyNewDyo.set(GECEventConstant.BILL_NO_KEY, number);
            contractApplyNewDyo.set(GECEventConstant.CONTRACTNUMBER_KEY, number);
            // 设置 签署业务类型
            contractApplyNewDyo.set(GECEventConstant.BUSINESSTYPE_KEY, "1");// 默认新签
            // 设置 合同协议类型
            contractApplyNewDyo.set(GECEventConstant.PROTOCOLTYPE_KEY, "1");// 默认劳动合同
            // 设置 单据状态
            contractApplyNewDyo.set(GECEventConstant.BILL_STATUS_KEY, "A");// 默认暂存
            // 设置 审批状态
            contractApplyNewDyo.set(GECEventConstant.AUDIT_STATUS, "A");// 默认劳动合同
            // 设置 人事管理组织
            contractApplyNewDyo.set(GECEventConstant.ORG_KEY, personInfo.getDynamicObject(GECEventConstant.ASSIGNMENT_KEY).getDynamicObject(GECEventConstant.ORG_KEY));
            // 设置 员工
            contractApplyNewDyo.set(GECEventConstant.ASSIGNMENT_KEY, personInfo.getDynamicObject(GECEventConstant.ASSIGNMENT_KEY));
            // 设置 员工
            contractApplyNewDyo.set(GECEventConstant.EMPLOYEE_KEY, personInfo.getDynamicObject(GECEventConstant.ASSIGNMENT_KEY).getDynamicObject(GECEventConstant.EMPLOYEE_KEY));
            // 设置 工号
            contractApplyNewDyo.set(GECEventConstant.EMP_NUMBER_KEY, personInfo.getString(GECEventConstant.HRPI_EMPLOYEE_EMPNUMBER));
            // 设置 姓名
            contractApplyNewDyo.set(GECEventConstant.EMPNAME_KEY, personInfo.getString(GECEventConstant.HRPI_EMPLOYEE_NAME));
            // 设置 国籍
            contractApplyNewDyo.set(GECEventConstant.NATION_KEY, EntityHelper.newEntity(GECEventConstant.HBSS_NATIONALITY_ENTITY, personInfo.getLong(GECEventConstant.HRPI_EMPLOYEE_NATIONALITY_ID)));
            // 设置 任职类型
            contractApplyNewDyo.set(GECEventConstant.POSTYPE_KEY, personInfo.getDynamicObject(GECEventConstant.HRPI_EMPPOSORGREL_POSTYPE));
            // 设置 任职序号
            contractApplyNewDyo.set(GECEventConstant.ORGRELSEQ_KEY, personInfo.getInt(GECEventConstant.HRPI_EMPPOSORGREL_ORGRELSEQ));
            // 设置 常驻工作地
            contractApplyNewDyo.set(GECEventConstant.BASELOCATION_KEY, personInfo.getDynamicObject(GECEventConstant.HRPI_EMPPOSORGREL_WORKPLACE));
            // 设置 公司
            contractApplyNewDyo.set(GECEventConstant.CURCOMPANY_KEY, EntityHelper.newEntity(GECEventConstant.ADMINORG_ENTITYID, personInfo.getLong(GECEventConstant.HAOS_ADMINORGHRF7_BELONGCOMPANY_ID)));
            // 设置 公司历史
            contractApplyNewDyo.set(GECEventConstant.SIGNEDCOMPANYHIS_KEY, EntityHelper.newEntity(GECEventConstant.ADMINORG_ENTITYID, personInfo.getLong(GECEventConstant.HAOS_ADMINORGHRF7_BELONGCOMPANY_SOURCEVID)));
            // 设置 部门
            contractApplyNewDyo.set(GECEventConstant.CURDEPT_KEY, EntityHelper.newEntity(GECEventConstant.ADMINORG_ENTITYID, personInfo.getLong(GECEventConstant.HAOS_ADMINORGHRF7_ID)));
            // 设置 部门历史
            contractApplyNewDyo.set(GECEventConstant.DEPARTMENTHIS_KEY, EntityHelper.newEntity(GECEventConstant.ADMINORG_ENTITYID, personInfo.getLong(GECEventConstant.HAOS_ADMINORGHRF7_SOURCEVID)));
            // 设置 岗位
            contractApplyNewDyo.set(GECEventConstant.CURPOSTION_KEY, EntityHelper.newEntity(GECEventConstant.HBPM_POSITIONHR, personInfo.getLong(GECEventConstant.HBPM_POSITIONHR_ID)));
            // 设置 岗位历史
            contractApplyNewDyo.set(GECEventConstant.POSTIONHIS_KEY, EntityHelper.newEntity(GECEventConstant.HBPM_POSITIONHR, personInfo.getLong(GECEventConstant.HBPM_POSITIONHR_SOURCEVID)));
            // 设置 职位
            contractApplyNewDyo.set(GECEventConstant.CURJOB_KEY, personInfo.getDynamicObject(GECEventConstant.HRPI_EMPPOSORGREL_JOB));
            // 设置 证件类型
            Long cardTypeId = personInfo.getLong(GECEventConstant.HRPI_PERCRE_CREDENTIALSTYPE_ID);
            cardTypeId = HRObjectUtils.isEmpty(cardTypeId) ? personInfo.getLong(GECEventConstant.CNIDCARD_CREDENTIALSTYPE_ID) : cardTypeId;
            if (HRObjectUtils.isEmpty(cardTypeId)) {
                throw new KDBizException(String.format("没有可使用的证件类型,组织分配ID[%s]", assignmentId));
            }
            contractApplyNewDyo.set(GECEventConstant.CARDTYPE_KEY, EntityHelper.newEntity(GECEventConstant.HBSS_CREDENTIALSTYPE_ENTITY, cardTypeId));
            // 设置 证件号码
            String cardNumber = personInfo.getString(GECEventConstant.HRPI_PERCRE_NUMBER);
            cardNumber = HRStringUtils.isBlank(cardNumber) ? personInfo.getString(GECEventConstant.CNIDCARD_NUMBER) : cardNumber;
            if (HRStringUtils.isBlank(cardNumber)) {
                throw new KDBizException(String.format("没有可使用的证件号码,组织分配ID[%s]", assignmentId));
            }
            contractApplyNewDyo.set(GECEventConstant.CARDNUMBER_KEY, cardNumber);
            // 设置 户籍地址
            contractApplyNewDyo.set(GECEventConstant.HOUSEHOLDREGISTER_KEY, personInfo.getString(GECEventConstant.HOUSEHOLDREGISTER_ADDRESSINFO));
            // 设置 居住地址
            contractApplyNewDyo.set(GECEventConstant.RESIDENTIALADDRESS_KEY, personInfo.getString(GECEventConstant.RESIDENTIALADDRESS_ADDRESSINFO));
            // 设置 联系方式
            contractApplyNewDyo.set(GECEventConstant.EMPPHONE_KEY, personInfo.getString(GECEventConstant.HRPI_PERCONTACT_PHONE));
            // 设置应签单位、实签单位
            DynamicObject signCompanyDyo = signCompanyMap.get(personInfo.getLong(GECEventConstant.HAOS_ADMINORGHRF7_CORPORATEORG_ID));
            if (HRObjectUtils.isEmpty(signCompanyDyo)) {
                throw new KDBizException(String.format("没有可使用的应签/实签单位,组织分配ID[%s]", assignmentId));
            }
            contractApplyNewDyo.set(GECEventConstant.SUGGESTSIGNCOMPANY_KEY, signCompanyDyo);
            contractApplyNewDyo.set(GECEventConstant.ACTUALSIGNCOMPANY_KEY, signCompanyDyo);
            // 设置 应签单位历史、实签单位历史
            DynamicObject signCompanyHisDyo = EntityHelper.newEntity(GECEventConstant.HBSS_SIGNCOMPANYHIS_ENTITY, signCompanyDyo.getLong(GECEventConstant.VID_KEY));
            contractApplyNewDyo.set(GECEventConstant.SUGGESTSIGNCOMPHIS_KEY, signCompanyHisDyo);
            contractApplyNewDyo.set(GECEventConstant.ACTUALSIGNCOMPANYHIS_KEY, signCompanyHisDyo);
            // 设置 合同类型
            contractApplyNewDyo.set(GECEventConstant.CONTRACTTYPE_KEY, EntityHelper.newEntity(GECEventConstant.HBSS_CONTRACTTYPES_ENTITY, 1406559486235128832L));// 默认劳动合同
            // 设置 合同期限类型
            contractApplyNewDyo.set(GECEventConstant.PERIODTYPE_KEY, EntityHelper.newEntity(GECEventConstant.HBSS_TIMELIMITTYPE_ENTITY, 1383941525804767232L));// 默认固定期限
            // 设置 合同开始日期
            Date startDate = personInfo.getDate(GECEventConstant.HRPI_EMPPOSORGREL_STARTDATE);
            contractApplyNewDyo.set(GECEventConstant.STARTDATE_KEY, startDate);
            // 设置 合同期限
            contractApplyNewDyo.set(GECEventConstant.PERIOD_KEY, 5);// 默认5年
            // 设置 合同期限单位
            contractApplyNewDyo.set(GECEventConstant.PERIODUNIT_KEY, "1");// 默认年
            // 设置 合同结束日期
            Date endDate = HRDateTimeUtils.addDay(HRDateTimeUtils.addYear(startDate, 5), -1);// +5年-1天
            contractApplyNewDyo.set(GECEventConstant.ENDDATE_KEY, endDate);
            // 设置 试用期开始日期
            contractApplyNewDyo.set(GECEventConstant.PROBATIONSTARTDATE_KEY, personInfo.getDate(GECEventConstant.HRPI_TRIALPERIOD_TRIALSTARTDATE));
            // 设置 试用结束日期
            contractApplyNewDyo.set(GECEventConstant.PROBATIONENDDATE_KEY, personInfo.getDate(GECEventConstant.HRPI_TRIALPERIOD_PREENDDATE));
            // 设置 试用期限
            contractApplyNewDyo.set(GECEventConstant.PROBATIONPERIOD_KEY, personInfo.getInt(GECEventConstant.HRPI_TRIALPERIOD_PROBATION));
            // 设置 试用期单位
            contractApplyNewDyo.set(GECEventConstant.PROBATIONUNIT_KEY, personInfo.getString(GECEventConstant.HRPI_TRIALPERIOD_PROBATIONUNIT));
            // 设置 签署方式
            contractApplyNewDyo.set(GECEventConstant.SIGNWAY_KEY, "2");// 默认纸质签署
            // 设置 创建人
            contractApplyNewDyo.set(GECEventConstant.CREATOR_KEY, UserServiceHelper.getCurrentUserId());

            // 构建 规则引擎所需参数
            Map requestMap = new HashMap();
            // 应用ID
            requestMap.put("bizApp", BIZAPP);
            // 场景编码
            requestMap.put("sceneNumber", SCENE_NUMBER);
            // 组织ID
            requestMap.put("buNumber", BU_NUMBER);
            Map inputParams = new HashMap();
            // 构建参数所需对象 劳动合同新签申请
            inputParams.put(HLCM_CONTRACTAPPLYNEW, contractApplyNewDyo);
            requestMap.put("inputParams", inputParams);
            // 调用规则引擎设置合同信息
            setContractInfoByRuleEngine(requestMap, contractApplyNewDyo);
            if (HRObjectUtils.isEmpty(contractApplyNewDyo.get(GECEventConstant.CONTRACTEMPLATE_KEY))) {
                throw new KDBizException(String.format("没有可使用的合同模板,组织分配ID[%s]", assignmentId));
            }
            // 放入集合
            contractApplyNewDyoList.add(contractApplyNewDyo);
        }
        // 查询出合同模板所有属性,否则界面不显示数据,界面通过contractemplatehis显示合同模板数据,数据来源于合同模板中的vid属性和其他相关属性
        Set<Long> contracTemplateIds = contractApplyNewDyoList.stream().map(contractApplyNewDyo -> contractApplyNewDyo.getLong(String.join(".", GECEventConstant.CONTRACTEMPLATE_KEY, GECEventConstant.ID_KEY))).collect(Collectors.toSet());
        DynamicObject[] contractTemplateDyos = BusinessDataServiceHelper.load(contracTemplateIds.toArray(), MetadataServiceHelper.getDataEntityType(GECEventConstant.HLCM_CONTRACTTEMPLATE_ENTITY));
        // 处理成 key->合同模板ID value->合同模板dyo
        Map<Long, DynamicObject> contractTemplateMap = Arrays.stream(contractTemplateDyos).collect(Collectors.toMap(dynamicObject -> dynamicObject.getLong(GECEventConstant.ID_KEY), dynamicObject -> dynamicObject, (oldValue, newValue) -> newValue));
        for (DynamicObject contractApplyNewDyo : contractApplyNewDyoList) {
            contractApplyNewDyo.set(GECEventConstant.CONTRACTEMPLATE_KEY, contractTemplateMap.get(contractApplyNewDyo.getLong(String.join(".", GECEventConstant.CONTRACTEMPLATE_KEY, GECEventConstant.ID_KEY))));
        }
        // 生成合同
        SaveServiceHelper.saveOperate(GECEventConstant.HLCM_CONTRACTAPPLYNEW_ENTITY, contractApplyNewDyoList.toArray(new DynamicObject[0]));
    }

    private void setContractInfoByRuleEngine(Map requestMap, DynamicObject contractApplyNewDyo) {
        Map responseMap = RuleEngineServiceHelper.callRuleEngine(requestMap);
        if (HRStringUtils.equals("200", (String) responseMap.get("responseCode"))) {
            List<Map<String, Object>> policyResultList = (List)responseMap.get("policyResults");
            if (policyResultList != null && !policyResultList.isEmpty()) {
                // 倒转 有多条策略命中的情况下取第一条作为最终数据进行覆盖
                Collections.reverse(policyResultList);
                for (Map<String, Object> policyResult : policyResultList) {
                    List<Map<String, Object>> ruleResultList = (List) policyResult.get("ruleResults");
                    if (ruleResultList != null && !ruleResultList.isEmpty()) {
                        for (Map<String, Object> ruleResult : ruleResultList) {
                            Map<String, Object> matchResults = (Map<String, Object>) ruleResult.get("matchResults");
                            setContractInfoTemplate(matchResults, contractApplyNewDyo);
                        }
                    }
                    Map<String, Object> defaultResultList = (Map<String, Object>) policyResult.get("defaultResults");
                    setContractInfoTemplate(defaultResultList, contractApplyNewDyo);
                }
            }
        }
    }

    private void setContractInfoTemplate(Map<String, Object> results, DynamicObject contractApplyNewDyo) {
        if (!CollectionUtils.isEmpty(results)) {
            Object tempObject = results.get(HLCM_CONTRACTTEMPLATE);
            DynamicObject[] dynamicObjects = new DynamicObject[0];
            if (tempObject instanceof DynamicObject) {
                dynamicObjects = new DynamicObject[]{(DynamicObject)tempObject};
            } else if (tempObject instanceof DynamicObject[]) {
                dynamicObjects = (DynamicObject[]) tempObject;
            } else if (tempObject instanceof DynamicObjectCollection) {
                dynamicObjects = ((DynamicObjectCollection) tempObject).toArray(new DynamicObject[0]);
            }
            // 遍历取到第一个
            for(int index = dynamicObjects.length - 1; index >= 0; --index) {
                DynamicObject dy = dynamicObjects[index];
                if (!HRObjectUtils.isEmpty(dy)) {
                    // 因为在循环内，没法根据合同ID查询类型，所以这里直接赋值
                    contractApplyNewDyo.set(GECEventConstant.CONTRACTEMPLATE_KEY, dy);
                    /*Long contractTypeGroupId = dy.getLong(String.join(".", GECEventConstant.CONTRACTTYPE_KEY, GECEventConstant.GROUP_KEY, GECEventConstant.ID_KEY));
                    if (contractTypeGroupId.equals(ContractTypeCatEnum.CON.getPkId()) || contractTypeGroupId.equals(ContractTypeCatEnum.EMP.getPkId())) {
                        contractApplyNewDyo.set(GECEventConstant.CONTRACTEMPLATE_KEY, dy);
                        break;
                    }*/
                }
            }
        }
    }

}
