package nckd.jxccl.swc.mas.plugin.form.empmgt;

import kd.bos.common.enums.EnableEnum;
import kd.bos.consts.PermItemConst;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.common.model.AuthorizedOrgResultWithSub;
import kd.sdk.hr.hbp.business.helper.permission.HRPermissionServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.common.utils.ShowOperExecuteResult;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.hrpi.helper.EmpPosOrgRelHelper;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.swc.constants.MasConstant;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* 子企业负责人任职情况-列表插件
* 实体标识：nckd_subcoheadservice
* @author W.Y.C
* @date 2025/11/27 18:36
* @version 1.0
*/
public class SubCoHeadServiceListPlugin extends AbstractListPlugin implements Plugin {

   /* @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        if(e.getOperationResult() != null && e.getOperationResult().isSuccess()){
            if(MasConstant.LOADPARTYPOSITION_OP.equals(operateKey)){
                //载入党政职务履历
                loadParTyPosition();
            }
        }
    }*/


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        if(e.getOperationResult() != null && e.getOperationResult().isSuccess()){
            if(MasConstant.LOADPARTYPOSITION_OP.equals(operateKey)){
                //载入党政职务履历
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId(MasConstant.LOADPPDATEPOPUP_ENTITYID);
                showParameter.getOpenStyle().setShowType(ShowType.Modal);
                showParameter.setCaption("载入党政职务履历");
                showParameter.setSendToClient(true);
                showParameter.setCloseCallBack(new CloseCallBack(this, MasConstant.LOADPPDATEPOPUP_ENTITYID));
                this.getView().showForm(showParameter);
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        String actionId = closedCallBackEvent.getActionId();
        if(MasConstant.LOADPPDATEPOPUP_ENTITYID.equalsIgnoreCase(actionId)){
            Object returnData = closedCallBackEvent.getReturnData();
            if(returnData != null) {
                Map<String, Object> map = ConvertUtil.toMap(returnData);
                Date date = ConvertUtil.toDate(map.get("date"));
                DynamicObjectCollection mulPayUnit = ConvertUtil.toDynamicObjectCollectionOrNull(map.get(MasConstant.NCKD_MULPAYUNIT));
                loadParTyPosition(date,mulPayUnit);
            }
        }
    }
    
    /**
     * 载入党政职务履历
     * @return: void
     * @author W.Y.C
     * @date: 2025/11/27 18:40
     */
    private void loadParTyPosition(Date date,DynamicObjectCollection payUnitColl){
        /*假设今年是2025年，那么符合查询条件的数据应该满足：
        开始日期 <= 2025-12-31 且 结束日期 >= 2025-01-01
       符合条件的例子：
            开始日期: 2025-03-01, 结束日期: 2025-09-30
            在今年范围内开始和结束

            开始日期: 2024-06-01, 结束日期: 2025-06-01
            跨年度，但在今年有有效期

            开始日期: 2025-08-01, 结束日期: 2026-07-31
            从今年开始延续到明年

            开始日期: 2020-01-01, 结束日期: 2030-12-31
            长期有效，覆盖今年全年
         */
        List<Long> payUnitIdList = new ArrayList<>();
        if(payUnitColl != null && !payUnitColl.isEmpty()){
            for (DynamicObject item : payUnitColl) {
                // 获取基础资料的动态对象（包含基础资料的详细信息，如名称、编码等）
                long id = item.getLong(FormConstant.FBASEDATAID_ID_KEY);
                payUnitIdList.add(id);
            }
        }
        LocalDateTime now = ConvertUtil.toLocalDateTime(date);

        LocalDateTime beginYear = DateUtil.beginOfYear(now);
        LocalDateTime endYear = DateUtil.endOfYear(now);

        Date startOfYear = DateUtil.toDate(DateUtil.beginOfYear(now));
        Date endOfYear = DateUtil.toDate(DateUtil.endOfYear(now));

        QueryFieldBuilder subCoHeadServiceFieldBuilder = QueryFieldBuilder.create()
                .addIdNumberName(MasConstant.NCKD_EMPLOYEE);
        //查询当年已生成子企业负责人任职情况的人员
        QFilter subCoHeadServiceFilter = new QFilter(MasConstant.NCKD_YEAR, QCP.large_equals, startOfYear)
                .and(MasConstant.NCKD_YEAR, QCP.less_equals, endOfYear);
        // 只处理权限范围内的人员
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_mas", MasConstant.SUBCOHEADSERVICE_ENTITYID,
                PermItemConst.ITEM_VIEW, new HashMap<>());
        if (dataRule != null) {
            subCoHeadServiceFilter.and(dataRule);
        }
        DynamicObjectCollection subCoHeadServiceFilterQuery = QueryServiceHelper.query(MasConstant.SUBCOHEADSERVICE_ENTITYID, subCoHeadServiceFieldBuilder.buildSelect(), new QFilter[]{subCoHeadServiceFilter});
        List<Long> employeeIds = subCoHeadServiceFilterQuery.stream()
                .map(dynamicObject -> dynamicObject.getLong(String.join(".", MasConstant.NCKD_EMPLOYEE, FormConstant.ID_KEY)))
                .collect(Collectors.toList());

        //查询党政履历
//        nckd_hrpi_partyposh
        QueryFieldBuilder partyPoshFieldBuilder = QueryFieldBuilder.create()
                .addIdNumberName(MasConstant.NCKD_PAYUNIT)
                //变动时间
                .add(MasConstant.NCKD_CHANGETIME)
                .add(MasConstant.NCKD_POSNAME)
                .addIdNumberName(MasConstant.NCKD_POSCHTP)
                .addIdNumberName(MasConstant.NCKD_POSGRADE)
                .addIdNumberName(MasConstant.NCKD_APPRWAY)
                .add(MasConstant.NCKD_OFFICEDEPT)
                .add(MasConstant.NCKD_APPRDOCNO)
                .add(MasConstant.NCKD_ISDIRCADRE)
                .addIdNumberName(MasConstant.NCKD_ORGPOSGRD)
                .addIdNumberName(MasConstant.EMPLOYEE_KEY)
                .orderDesc(MasConstant.STARTDATE, MasConstant.ENDDATE);
        QFilter allPartyPoshFilter = new QFilter(String.join(".",MasConstant.EMPLOYEE_KEY,FormConstant.ID_KEY), QCP.not_in, employeeIds);
        if(!payUnitIdList.isEmpty()){
            allPartyPoshFilter.and(String.join(".",MasConstant.NCKD_PAYUNIT,FormConstant.ID_KEY), QCP.in, payUnitIdList);
        }
        DynamicObjectCollection allPartyPoshQuery = QueryServiceHelper.query(FormConstant.NCKD_HRPI_PARTYPOSH, partyPoshFieldBuilder.buildSelect(), new QFilter[]{allPartyPoshFilter});
        //按员工ID分组
        Map<Long, List<DynamicObject>> groupedPartyPoshQuery = allPartyPoshQuery.stream()
                .collect(Collectors.groupingBy(
                        obj -> obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))
                ));

        // 找出当年范围内的党政履历信息（如果有多条则取开始时间最新一条）
        Map<Long, DynamicObject> latestPartyPoshRecordMap = new HashMap<>();
        // 用于存储下一条党政履历记录的映射
        Map<Long, DynamicObject> nextPartyPoshRecordMap = new HashMap<>();
        for (Map.Entry<Long, List<DynamicObject>> entry : groupedPartyPoshQuery.entrySet()) {
            Long employeeId = entry.getKey();
            List<DynamicObject> records = entry.getValue();

            // 筛选出在当年时间范围内的记录，然后取STARTDATE最新的那一条
            Optional<DynamicObject> latestRecord = records.stream()
                    .filter(record -> {
                        if(record.getDate(MasConstant.NCKD_CHANGETIME) == null){
                            return false;
                        }
                        LocalDateTime changeTime = DateUtil.toLocalDateTime(record.getDate(MasConstant.NCKD_CHANGETIME));
                        // 判断变动时间是否小于等于当前日期
                        return  changeTime.isBefore(LocalDateTime.now()) || changeTime.isEqual(LocalDateTime.now());
                    })
                    .max(Comparator.comparing(record -> record.getDate(MasConstant.NCKD_CHANGETIME),
                            Comparator.nullsFirst(Comparator.naturalOrder())));

            // 如果没有当年范围内的记录，则取所有记录中最新的那条
            if (!latestRecord.isPresent()) {
                latestRecord = records.stream()
                        .max(Comparator.comparing(record -> record.getDate(MasConstant.NCKD_CHANGETIME),
                                Comparator.nullsFirst(Comparator.naturalOrder())));
            }

            if (latestRecord.isPresent()) {
                DynamicObject currentRecord = latestRecord.get();
                latestPartyPoshRecordMap.put(employeeId, currentRecord);

                // 根据当前记录的结束时间查找下一条记录
                Date currentChangeTime = currentRecord.getDate(MasConstant.NCKD_CHANGETIME);
                if (currentChangeTime != null) {
                    // 查找开始时间等于当前记录结束时间的下一条记录
                    Optional<DynamicObject> nextRecord = records.stream()
                            .filter(record -> {
                                Date changeTime = record.getDate(MasConstant.NCKD_CHANGETIME);
                                // 查找开始时间大于等于当前记录结束时间的记录
                                return changeTime != null && changeTime.compareTo(currentChangeTime) > 0;
                            })
                            .findFirst();

                    nextRecord.ifPresent(record -> nextPartyPoshRecordMap.put(employeeId, record));
                }
            }
        }


        //查询企业负责人信息
        QueryFieldBuilder entHeadFieldBuilder = QueryFieldBuilder.create()
                .add(MasConstant.STARTDATE)
                .add(MasConstant.ENDDATE)
                .addIdNumberName(MasConstant.NCKD_HEADTYPE)
                .add(MasConstant.NCKD_ISPROFMAN)
                .addIdNumberName(MasConstant.NCKD_PROFMANTYP)
                .add(MasConstant.NCKD_ISMANAGER)
                .addIdNumberName(MasConstant.NCKD_SALCALCPOST)
                .add(MasConstant.NCKD_SALNEGOT)
                .addIdNumberName(MasConstant.NCKD_TERM)
                .addIdNumberName(MasConstant.NCKD_MGTLVLDTL)
                .addIdNumberName(MasConstant.NCKD_LEGPOSTLV)
                .addIdNumberName(MasConstant.EMPLOYEE_KEY)
                .add(MasConstant.NCKD_TERMCONT)
                .orderDesc(MasConstant.STARTDATE, MasConstant.ENDDATE);

        //查询下一段的企业负责人信息；用于后续逻辑查找下一段的负责人信息
        QFilter allEntHeadFilter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.not_in, employeeIds)
                //法人岗位层级为高管
                .and(String.join(".", MasConstant.NCKD_LEGPOSTLV, MasConstant.NCKD_ISEXEC),QCP.equals, EnableEnum.YES.getCode());
        //查询出人员所有的企业负责人信息
        DynamicObjectCollection allEntHeadQuery = QueryServiceHelper.query(FormConstant.NCKD_HRPI_ENTHEAD, entHeadFieldBuilder.buildSelect(), new QFilter[]{allEntHeadFilter});
        Map<Long, List<DynamicObject>> groupedEntHeadQuery = allEntHeadQuery.stream()
                .collect(Collectors.groupingBy(
                        obj -> obj.getLong(String.join(".", MasConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))
                ));
        // 找出当年范围内的企业负责人信息（如果有多条则取开始时间最新一条）
        Map<Long, DynamicObject> entHeadRecordMap = new HashMap<>();
        // 用于存储下一条记录的映射
        Map<Long, DynamicObject> nextEntHeadRecordMap = new HashMap<>();
        for (Map.Entry<Long, List<DynamicObject>> entry : groupedEntHeadQuery.entrySet()) {
            Long employeeId = entry.getKey();
            List<DynamicObject> records = entry.getValue();

            // 筛选出在当年时间范围内的记录，然后取STARTDATE最新的那一条
            Optional<DynamicObject> latestRecord = records.stream()
                    .filter(record -> {
                        Date startDate = record.getDate(MasConstant.STARTDATE);
                        Date endDate = record.getDate(MasConstant.ENDDATE);
                        // 判断记录是否在当年范围内
                        return startDate != null && beginYear.getYear() >= DateUtil.getYear(startDate)  &&  DateUtil.now().getYear() <= DateUtil.getYear(endDate);
                    })
                    .max(Comparator.comparing(record -> record.getDate(MasConstant.STARTDATE),
                            Comparator.nullsFirst(Comparator.naturalOrder())));

            if (latestRecord.isPresent()) {
                DynamicObject currentRecord = latestRecord.get();
                entHeadRecordMap.put(employeeId, currentRecord);
                // 根据当前记录的结束时间查找下一条记录
                Date currentEndDate = currentRecord.getDate(MasConstant.ENDDATE);
                if (currentEndDate != null) {
                    // 查找开始时间等于当前记录结束时间的下一条记录
                    Optional<DynamicObject> nextRecord = records.stream()
                            .filter(record -> {
                                Date startDate = record.getDate(MasConstant.STARTDATE);
                                // 查找开始时间等于当前记录结束时间的记录
                                // 查找开始时间大于等于当前记录结束时间的记录
                                return startDate != null && !startDate.before(currentEndDate);
                            })
                            .findFirst();

                    nextRecord.ifPresent(record -> nextEntHeadRecordMap.put(employeeId, record));
                }
            }
        }


        //查询人员最新任职经历
        DynamicObject[] empPosOrgRelArray = EmpPosOrgRelHelper.queryEmpPosOrgRelByEmployees(entHeadRecordMap.keySet());
        List<Long> empPosOrgRelIds = Arrays.stream(empPosOrgRelArray).map(empPosOrgRel -> empPosOrgRel.getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
        //查询人员法人单位
        QueryFieldBuilder legalPostFieldBuilder = QueryFieldBuilder.create()
                .add(MasConstant.STARTDATE)
                .add(MasConstant.ENDDATE)
                .addIdNumberName(FormConstant.NCKD_EMPPOSORGREL,FormConstant.EMPLOYEE_KEY)
                .addIdNumberName(MasConstant.NCKD_LAWENTITY);
        QFilter legalPostFilter = QFilterCommonHelper.getValidDateFilter(MasConstant.STARTDATE, MasConstant.ENDDATE)
                .and(FormConstant.NCKD_EMPPOSORGREL,QCP.in, empPosOrgRelIds);
        DynamicObjectCollection legalPostQuery = QueryServiceHelper.query(FormConstant.NCKD_HRPI_LEGALPOST, legalPostFieldBuilder.buildSelect(), new QFilter[]{legalPostFilter});
        Map<Long, DynamicObject> legalPostMap = legalPostQuery.stream()
                .collect(Collectors.toMap(obj -> obj.getLong(String.join(".",FormConstant.NCKD_EMPPOSORGREL, FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY)), Function.identity(), BinaryOperator.maxBy(Comparator.comparing(
                        // 按 STARTDATE 字段比较
                        obj -> obj.getDate(MasConstant.STARTDATE)
                ))));


        /*//获取组织
        List<Long> createOrgList = BaseDataServiceHelper.getCreateOrgList(MasConstant.SUBCOHEADSERVICE_ENTITYID);
        MainEntityType bosOrgEntityType = EntityMetadataCache.getDataEntityType(FormConstant.BOS_ORG);
        DynamicObject org = new DynamicObject(bosOrgEntityType);
        if (!createOrgList.isEmpty()) {
            org.set(FormConstant.ID_KEY, createOrgList.get(0));
        }
        //获取控制策略
        String ctrlStrategy = BaseDataServiceHelper.getBdCtrlStrgy(MasConstant.SUBCOHEADSERVICE_ENTITYID,org.getLong(FormConstant.ID_KEY)+"");*/
        //构建子企业负责人任职情况实体
        List<DynamicObject> saveSubCoHeadServiceList = new ArrayList<>();
        for (Map.Entry<Long, DynamicObject> entHeadRecordEntry : entHeadRecordMap.entrySet()) {
            //企业负责人信息
            DynamicObject entHead = entHeadRecordEntry.getValue();
            //党政履历
            DynamicObject partyPosh = latestPartyPoshRecordMap.get(entHeadRecordEntry.getKey());
            DynamicObject newSubCoHeadService = EntityHelper.newEntity(MasConstant.SUBCOHEADSERVICE_ENTITYID);
            newSubCoHeadService.set(MasConstant.NCKD_YEAR,DateUtil.toDate(beginYear));
            newSubCoHeadService.set(MasConstant.NCKD_EMPLOYEE,entHeadRecordEntry.getKey());
            newSubCoHeadService.set(MasConstant.STATUS, StatusEnum.B.toString());
            newSubCoHeadService.set(MasConstant.ENABLE, EnableEnum.YES.getCode());
            DynamicObject employee = null;
            //党政履历
            if(partyPosh != null) {
                long employeeId = partyPosh.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY));
                if(employeeId > 0) {
                    employee = EntityHelper.newEntity(MasConstant.HSBS_EMPLOYEE, employeeId);
                    employee.set(FormConstant.NAME_KEY, partyPosh.getString(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.NAME_KEY)));
                }
                //所属二级单位（发薪单位）
                long payOrgId = partyPosh.getLong(String.join(".", MasConstant.NCKD_PAYUNIT, FormConstant.ID_KEY));
                DynamicObject payOrg = EntityHelper.newEntity(FormConstant.ADMINORG_ENTITYID, payOrgId);
                newSubCoHeadService.set(MasConstant.NCKD_PAYUNIT, payOrg);
                //职务
                newSubCoHeadService.set(MasConstant.NCKD_POSNAME,partyPosh.getString(MasConstant.NCKD_POSNAME));
                //是否直管干部
                newSubCoHeadService.set(MasConstant.NCKD_ISDIRCADRE,partyPosh.getString(MasConstant.NCKD_ISDIRCADRE));
                //任职开始时间（变动日期）
                Date changeTime = partyPosh.getDate(MasConstant.NCKD_CHANGETIME);

                if(changeTime != null){
                    newSubCoHeadService.set(MasConstant.NCKD_STARTDATE,changeTime);
                    DynamicObject nextPartyPoshRecord = nextPartyPoshRecordMap.get(entHeadRecordEntry.getKey());
                    if(nextPartyPoshRecord != null){
                        //任职结束时间（下一段的变动时间）
                        Date nextChangeTime = nextPartyPoshRecord.getDate(MasConstant.NCKD_CHANGETIME);
                        if(nextChangeTime != null) {
                            newSubCoHeadService.set(MasConstant.NCKD_ENDDATE, nextChangeTime);
                        }else{
                            newSubCoHeadService.set(MasConstant.NCKD_ENDDATE, DateUtil.getMaxDateAsDate());
                        }
                    }else{
                        newSubCoHeadService.set(MasConstant.NCKD_ENDDATE, DateUtil.getMaxDateAsDate());
                    }
                    //【变动时间】的次月到当年年底的月数（ChronoUnit.MONTHS是从0开始的，所以不用加月份）
//                    LocalDateTime newMonths = DateUtil.addMonths(DateUtil.toLocalDateTime(changeTime), 1);
                    Date endChangeTime = DateUtil.endOfYear(changeTime);
                    long between = DateUtil.between(DateUtil.toLocalDateTime(changeTime), DateUtil.toLocalDateTime(endChangeTime), ChronoUnit.MONTHS);
                    newSubCoHeadService.set(MasConstant.NCKD_SERVICEMONTHS,between);
                }

            }
            DynamicObject legalPost = legalPostMap.get(entHeadRecordEntry.getKey());
            if(legalPost != null){
                long lawEntityId = legalPost.getLong(String.join(".", MasConstant.NCKD_LAWENTITY, FormConstant.ID_KEY));
                //法人单位
                DynamicObject lawentity = EntityHelper.newEntity(FormConstant.HBSS_LAWENTITY, lawEntityId);
                newSubCoHeadService.set(MasConstant.NCKD_LAWENTITY,lawentity);
            }
            //企业负责人信息
            if(entHead != null){
                long employeeId = entHead.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY));
                if(employeeId > 0) {
                    employee = EntityHelper.newEntity(MasConstant.HSBS_EMPLOYEE, employeeId);
                    employee.set(FormConstant.NAME_KEY, entHead.getString(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.NAME_KEY)));
                }
                //是否职业经理人
                newSubCoHeadService.set(MasConstant.NCKD_ISPROFMAN,entHead.getString(MasConstant.NCKD_ISPROFMAN));
                //是否经理层成员
                newSubCoHeadService.set(MasConstant.NCKD_ISMANAGER,entHead.getString(MasConstant.NCKD_ISMANAGER));
                //薪酬核算岗位
                DynamicObject salCalcPost = EntityHelper.newEntity(FormConstant.HBPM_POSITIONHR, entHead.getLong(String.join(".", MasConstant.NCKD_SALCALCPOST, FormConstant.ID_KEY)));
                newSubCoHeadService.set(MasConstant.NCKD_SALCALCPOST,salCalcPost);
                //薪酬是否一人一议
                newSubCoHeadService.set(MasConstant.NCKD_SALNEGOT,entHead.getString(MasConstant.NCKD_SALNEGOT));
                DynamicObject postLevel = EntityHelper.newEntity(FormConstant.NCKD_HPFS_POSTLEVEL, entHead.getLong(String.join(".", MasConstant.NCKD_MGTLVLDTL, FormConstant.ID_KEY)));
                newSubCoHeadService.set(MasConstant.NCKD_MGTLVLDTL,postLevel);
                //法人岗位层级
                DynamicObject legPostLv = EntityHelper.newEntity(FormConstant.NCKD_HBSS_LEGPOSTLV, entHead.getLong(String.join(".", MasConstant.NCKD_LEGPOSTLV,FormConstant.ID_KEY)));
                newSubCoHeadService.set(MasConstant.NCKD_LEGPOSTLV,legPostLv);

            }
            //员工信息
            newSubCoHeadService.set(FormConstant.NCKD_EMPLOYEE,employee);
            saveSubCoHeadServiceList.add(newSubCoHeadService);

        }
        if(!saveSubCoHeadServiceList.isEmpty()) {
            //调用save op
            OperateOption option = OperateOption.create();
            option.setVariableValue("load", Boolean.TRUE+"");
            OperationResult operationResult = SaveServiceHelper.saveOperate(MasConstant.SUBCOHEADSERVICE_ENTITYID, saveSubCoHeadServiceList.toArray(new DynamicObject[0]), option);
            if (!operationResult.isSuccess()) {
                this.getView().showForm(ShowOperExecuteResult.getOperResultForm("载入党政职务履历", this.getView(), operationResult));
                this.getView().invokeOperation(FormConstant.REFRESH_OP);
            } else {
                //刷新列表
                Map<String, String> customData = operationResult.getCustomData();
                Map<Object, Object> successMap = new HashMap<>();
                //成功的记录
                for (Object successPkId : operationResult.getSuccessPkIds()) {
                    successMap.put(successPkId, customData.get(successPkId.toString()));
                }
                if (!successMap.isEmpty()) {
                    this.getView().showForm(ShowOperExecuteResult.getOperResultForm("载入党政职务履历",this.getView(), operationResult));
                    this.getView().invokeOperation(FormConstant.REFRESH_OP);
                } else {
                    this.getView().invokeOperation(FormConstant.REFRESH_OP);
                    this.getView().showConfirm("提示", operationResult.getMessage(), MessageBoxOptions.OK, null, null, null, null);
                }
            }
        }else {
            this.getView().showTipNotification("没有需要载入的数据！");
        }

    }
}