package nckd.jxccl.hr.psms.plugin.operate.adjust;

import kd.bos.common.enums.EnableEnum;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.CloneUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
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.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.pm.helper.PerformanceManagerHelper;
import nckd.jxccl.hr.psms.business.JobLevelCalculatorService;
import nckd.jxccl.hr.psms.business.ManagerAllowanceService;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;
import nckd.jxccl.hr.psms.common.bo.PositionAppointmentBO;
import nckd.jxccl.hr.psms.helper.PositionFileHelper;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;

/**
* 新建动态调整OP
* @author W.Y.C
* @date 2025/9/17 22:02
* @version 1.0
*/
public class NewDynamicAdjustmentOperationPlugIn extends AbstractOperationServicePlugIn{

    protected final static Log logger = LogFactory.getLog(NewDynamicAdjustmentOperationPlugIn.class);

    /** 记录上一次职位档案（key：人员ID） */
    Map<Long,DynamicObject> latsPersonPosFileMap;

    /** 记录上年度考核结果（key：人员ID）*/
    Map<Long,DynamicObject> lastYearPerformanceResultMap;

    @Override
    public void onAddValidators(AddValidatorsEventArgs e){
        latsPersonPosFileMap = new HashMap<>(e.getDataEntities().length);
        lastYearPerformanceResultMap = new HashMap<>(e.getDataEntities().length);
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                if (!this.getValidateContext().getValidateResults().isSuccess()) {
                    //前面的校验器失败跳过本校验器
                    return;
                }
                for (ExtendedDataEntity rowDataEntity : getDataEntities()) {
                    DynamicObject data = rowDataEntity.getDataEntity();
                    if(data.containsProperty(FormConstant.NCKD_ENTRYENTITY)){
                        //批量调整
                        DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                        // 检查人员ID重复
                        Set<Long> personIds = new HashSet<>();
                        for (DynamicObject dynamicObject : dynamicObjectCollection) {
                            if (dynamicObject.containsProperty(FormConstant.NCKD_PERSON)) {
                                DynamicObject person = dynamicObject.getDynamicObject(FormConstant.NCKD_PERSON);
                                Long personId = person.getLong(FormConstant.ID_KEY);
                                if (!personIds.add(personId)) {
                                    addFatalErrorMessage(rowDataEntity,
                                            StrFormatter.format("人员【{}】在列表中重复，请保留一条信息",
                                                    person.getString(FormConstant.NAME_KEY)));
                                }
                            }
                        }
                        if(!this.getValidateResult().isSuccess()){
                            return;
                        }

                        for (DynamicObject dynamicObject : dynamicObjectCollection) {
                            validator(rowDataEntity, dynamicObject);
                        }
                    }else{
                        //单次调整
                        validator(rowDataEntity, data);
                    }
                }
            }

            private void validator(ExtendedDataEntity rowDataEntity, DynamicObject data) {
                DynamicObject person = data.getDynamicObject(FormConstant.NCKD_PERSON);
                if(person == null){
                    addFatalErrorMessage(rowDataEntity,"请选择要调整的员工");
                    return;
                }
                Date adjustDate = data.getDate(PositionStructureConstant.NCKD_ADJUSTDATE);
                if (adjustDate == null) {
                    addFatalErrorMessage(rowDataEntity,StrFormatter.format("人员【{}】调整时间不能为空",person.getString(FormConstant.NAME_KEY)));
                }
                DynamicObject latsPersonPosFileByPerson = PositionFileHelper.getLatsPersonPosFileByPerson(person.getLong(FormConstant.ID_KEY));
                if(latsPersonPosFileByPerson == null){
                    addFatalErrorMessage(rowDataEntity, StrFormatter.format("当前无法为【{}】进行动态调整，因为他/她尚未建立职位档案。请前往“职位及积分初定” -> 进行初定！", person.getString(FormConstant.NAME_KEY)));
                }
                //判断当前年是否已执行过年度调整
                DynamicObject[] personPosFileByAdjust = PositionFileHelper.getPersonPosFileByPersonAndState(person.getLong(FormConstant.ID_KEY), new String[]{"4"},
                        null,
                        new QFilter(PositionStructureConstant.NCKD_ADJUSSTATUS, QCP.equals, EnableEnum.NO.getCode()));
                if(personPosFileByAdjust != null && personPosFileByAdjust.length > 0){
                    StringJoiner executeYear = new StringJoiner(",");
                    for (DynamicObject dynamicObject : personPosFileByAdjust) {
                        executeYear.add(dynamicObject.getInt(PositionStructureConstant.NCKD_EXECUTEYEAR)+"");
                    }
                    addFatalErrorMessage(rowDataEntity, StrFormatter.format("当前无法为【{}】进行动态调整，因为存在【{}】年度未生效的动态调整！", person.getString(FormConstant.NAME_KEY), executeYear.toString()));
                }
                //最近一次职位档案开始时间
                if(latsPersonPosFileByPerson != null) {
                    Date date = latsPersonPosFileByPerson.getDate(PositionStructureConstant.NCKD_BEGINDATE);
                    //校验【本次调整时间】不得早于上一笔时间
                    if (adjustDate != null && adjustDate.compareTo(date) <= 0) {
                        addFatalErrorMessage(rowDataEntity, StrFormatter.format("人员【{}】最近一次的职位档案变动时间是【{}】，请勿选择早于该时间段的调整时间！", person.getString(FormConstant.NAME_KEY), DateUtil.format(date, DateUtil.NORM_DATE_PATTERN)));
                    }
                }
                //获取上年度绩效结果
                if(adjustDate != null) {
                    LocalDateTime lastYearDateTime = DateUtil.minusYears(DateUtil.toLocalDateTime(adjustDate), 1);
                    DynamicObject lastYearPerformanceResult = PerformanceManagerHelper.getPerformanceResult(person.getLong(FormConstant.ID_KEY), lastYearDateTime);
                    if (lastYearPerformanceResult == null) {
                        addFatalErrorMessage(rowDataEntity, StrFormatter.format("人员【{}】没有【{}】年度考核结果，无法新建调整", person.getString(FormConstant.NAME_KEY),DateUtil.getYear(lastYearDateTime)));
                    }
                    lastYearPerformanceResultMap.put(person.getLong(FormConstant.ID_KEY),lastYearPerformanceResult);
                }
                latsPersonPosFileMap.put(person.getLong(FormConstant.ID_KEY),latsPersonPosFileByPerson);

            }
        });
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        if(!this.getOperationResult().isSuccess()){
            e.setCancel(true);
        }
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {

        logger.info("【职位体系】-动态调整-开始");
        List<Long> personIds = new ArrayList<>(e.getDataEntities().length);
        List<DynamicObject> newPersonPosFiles = new ArrayList<>(e.getDataEntities().length);
        for (DynamicObject data : e.getDataEntities()) {
            if(data.containsProperty(FormConstant.NCKD_ENTRYENTITY)){
                //批量调整
                DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection(FormConstant.NCKD_ENTRYENTITY);
                for (DynamicObject dynamicObject : dynamicObjectCollection) {
                    execute(dynamicObject, personIds, newPersonPosFiles);
                }
            }else{
                //单次调整
                execute(data, personIds, newPersonPosFiles);
            }

        }

//        SaveServiceHelper.save(newPersonPosFiles.toArray(new DynamicObject[0]));
        OperationResult operationResult = SaveServiceHelper.saveOperate(PositionStructureConstant.PERSONPOSFILE_ENTITYID, newPersonPosFiles.toArray(new DynamicObject[0]), OperateOption.create());
        if (!operationResult.isSuccess()) {
            StringJoiner errorMsg = new StringJoiner("\n");
            for (IOperateInfo error : operationResult.getAllErrorOrValidateInfo()) {
                errorMsg.add(error.getMessage());
            }
            if (!ObjectUtils.isEmpty(operationResult.getMessage())) {
                errorMsg.add(operationResult.getMessage());
            }
            throw new ValidationException("保存职位档案失败，原因：" + errorMsg.toString());
        }
        PositionFileHelper.markAsNotCurrentNewest(personIds.toArray(new Long[0]));
        PositionFileHelper.markAsCurrentNewest(null,personIds.toArray(new Long[0]));

        //职位津贴
        ManagerAllowanceService.generateMgrPostAllow(newPersonPosFiles);
    }

    private void execute(DynamicObject data, List<Long> personIds, List<DynamicObject> newPersonPosFiles) {
        DynamicObject person = data.getDynamicObject(FormConstant.NCKD_PERSON);
        long personId = person.getLong(FormConstant.ID_KEY);
        String personNumber = person.getString(FormConstant.NUMBER_KEY);
        String personName = person.getString(FormConstant.NAME_KEY);
        String logPrefix = StrFormatter.format("【职位体系】-动态调整-人员【{}（{}）】",
                personName,
                personNumber);
        //最近一次档案
        DynamicObject latsPersonPosFile = latsPersonPosFileMap.get(personId);
        //上一次职级
        DynamicObject jobLevelHr = latsPersonPosFile.getDynamicObject(PositionStructureConstant.NCKD_JOBLEVELHR);
        //选择的调整时间
        Date adjustDate = data.getDate(PositionStructureConstant.NCKD_ADJUSTDATE);
        LocalDateTime adjustDateEnd = DateUtil.endOfDay(DateUtil.toLocalDateTime(adjustDate));
        //查询员工在调整日期内的最新信息（职位、部门、序列、学历、职称、技能）
        PositionAppointmentBO positionAppointment = PositionFileHelper.positionAppointmentQuery(personId, DateUtil.toDate(adjustDateEnd));
        if(positionAppointment.getEmpPosOrgRel() == null){
            throw new ValidationException(StrFormatter.format("当前无法为【{}】进行调整，因为根据时间【{}】未获取到人员任职和聘任信息！", personName,DateUtil.format(adjustDateEnd,DateUtil.NORM_DATE_PATTERN)));
        }
        //最新档案总积分
        BigDecimal allSumScore = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_ALLSUMSCORE);
        //计算本次职级
        JobLevelCalculatorService.JobLevelResult jobLevelResult = JobLevelCalculatorService.calculateJobLevel(person, adjustDate, positionAppointment);
        long jobLevelId = jobLevelResult.jobLevel.getLong(FormConstant.ID_KEY);

        Long frontendJobLevelId = null;
        if(data.containsProperty(PositionStructureConstant.NCKD_JOBLEVEL)){
            //前端传入的职级
            DynamicObject frontendJobLevel = data.getDynamicObject(PositionStructureConstant.NCKD_JOBLEVEL);
            if(frontendJobLevel != null){
                frontendJobLevelId = frontendJobLevel.getLong(FormConstant.ID_KEY);
            }
        }
        String remark = null;
        if(data.containsProperty(PositionStructureConstant.NCKD_REMARK)){
            //前端传入的职级
            remark = data.getString(PositionStructureConstant.NCKD_REMARK);
        }

        createPersonPosFile(person, positionAppointment, adjustDate, jobLevelResult, latsPersonPosFile, allSumScore, personId, frontendJobLevelId, jobLevelId, remark, personIds, newPersonPosFiles,lastYearPerformanceResultMap);
        setJobLevelResult(person,jobLevelResult.jobLevel);
    }

    private static void createPersonPosFile(DynamicObject person, PositionAppointmentBO positionAppointment, Date adjustDate,
                                            JobLevelCalculatorService.JobLevelResult jobLevelResult, DynamicObject latsPersonPosFile,
                                            BigDecimal allSumScore, long personId, Long frontendJobLevelId,
                                            long jobLevelId, String remark, List<Long> personIds,
                                            List<DynamicObject> newPersonPosFiles,Map<Long,DynamicObject> lastYearPerformanceResultMap) {

        DynamicObject currentPersonPosFile = BusinessDataServiceHelper.loadSingle(latsPersonPosFile.getLong(FormConstant.ID_KEY), PositionStructureConstant.PERSONPOSFILE_ENTITYID);
        //创建新对象：克隆整个数据包
        DynamicObject newPersonPosFile = (DynamicObject) new CloneUtils(false, true).clone(currentPersonPosFile);
        // 构建职位档案
        /*DynamicObject newPersonPosFile = BusinessDataServiceHelper.newDynamicObject(
                PositionStructureConstant.PERSONPOSFILE_ENTITYID);*/

        DynamicObject empPosOrgRel = positionAppointment.getEmpPosOrgRel();
        newPersonPosFile.set(PositionStructureConstant.NCKD_PERSON, person);

        /*//管理组织
        newPersonPosFile.set(PositionStructureConstant.ORG_KEY, UserServiceHelper.getUserMainOrgId(UserServiceHelper.getCurrentUserId()));
        DynamicObject company = BusinessDataServiceHelper.newDynamicObject(FormConstant.ADMINORGHR_ENTITYID);
        company.set(FormConstant.ID_KEY, empPosOrgRel.getLong(String.join(".",FormConstant.COMPANY_KEY,FormConstant.ID_KEY)));
        //创建组织
        newPersonPosFile.set(PositionStructureConstant.CREATEORG_KEY, company);
        //原创建组织
        newPersonPosFile.set(PositionStructureConstant.SRCCREATEORG_KEY, company);
        //使用组织
        DynamicObject dep = BusinessDataServiceHelper.newDynamicObject(FormConstant.ADMINORGHR_ENTITYID);
        dep.set(FormConstant.ID_KEY, empPosOrgRel.getLong(String.join(".",FormConstant.ADMINORG,FormConstant.ID_KEY)));
        newPersonPosFile.set(PositionStructureConstant.USEORG_KEY, dep);*/

        DynamicObject dep = BusinessDataServiceHelper.newDynamicObject(FormConstant.ADMINORG_ENTITYID);
        dep.set(FormConstant.ID_KEY, empPosOrgRel.getLong(String.join(".",FormConstant.ADMINORG,FormConstant.ID_KEY)));
        newPersonPosFile.set(PositionStructureConstant.NCKD_DEP, dep);



        newPersonPosFile.set(PositionStructureConstant.NCKD_TYPESTATE, "4");
        newPersonPosFile.set(PositionStructureConstant.NCKD_EXECUTEYEAR, DateUtil.getYear(adjustDate));
        Long positionId = empPosOrgRel.getLong(String.join(".",FormConstant.POSITION_KEY,FormConstant.ID_KEY));
        DynamicObject position = BusinessDataServiceHelper.newDynamicObject(FormConstant.HBPM_POSITIONHR);
        position.set(FormConstant.ID_KEY, positionId);
        Long jobSeqId = empPosOrgRel.getLong(String.join(".", FormConstant.HBPM_POSITIONHR, FormConstant.NCKD_JOBSEQ, FormConstant.ID_KEY));
        DynamicObject jobSeq = BusinessDataServiceHelper.newDynamicObject(FormConstant.HBJM_JOBSEQHR);
        jobSeq.set(FormConstant.ID_KEY, jobSeqId);
        newPersonPosFile.set(PositionStructureConstant.NCKD_JOBSEQHR, jobSeq);
        newPersonPosFile.set(PositionStructureConstant.NCKD_POSITIONHR, position);
        newPersonPosFile.set(PositionStructureConstant.NCKD_RANKNAME, jobLevelResult.jobScoreInfo.rankName);
        DynamicObject proTitleLevel = BusinessDataServiceHelper.newDynamicObject(PositionStructureConstant.HBSS_PROTITLELEVEL);
        proTitleLevel.set(FormConstant.ID_KEY, jobLevelResult.jobScoreInfo.perProTitleId);
        newPersonPosFile.set(PositionStructureConstant.NCKD_PROTITLELEVEL, proTitleLevel);
        newPersonPosFile.set(PositionStructureConstant.NCKD_JOBSTATUSNAME, jobLevelResult.jobScoreInfo.jobStatusName);
        DynamicObject ocpQualLevel = BusinessDataServiceHelper.newDynamicObject(PositionStructureConstant.HBSS_OCPQUALLEVEL);
        ocpQualLevel.set(FormConstant.ID_KEY, jobLevelResult.jobScoreInfo.quaLevelId);
        newPersonPosFile.set(PositionStructureConstant.NCKD_OCPQUALLEVEL, ocpQualLevel);
        DynamicObject diploma = BusinessDataServiceHelper.newDynamicObject(PositionStructureConstant.HBSS_DIPLOMA);
        diploma.set(FormConstant.ID_KEY, jobLevelResult.jobScoreInfo.diplomaId);
        newPersonPosFile.set(PositionStructureConstant.NCKD_DIPLOMA, diploma);
        newPersonPosFile.set(PositionStructureConstant.NCKD_JOBLEVELHR, jobLevelResult.jobLevel);
        newPersonPosFile.set(PositionStructureConstant.NCKD_LASTPERSONPOSFILE, latsPersonPosFile);
        newPersonPosFile.set(PositionStructureConstant.NCKD_DIPLOMASCORE, jobLevelResult.jobScoreInfo.diplomaScore);
        newPersonPosFile.set(PositionStructureConstant.NCKD_WHYDIPLOMASCORE, jobLevelResult.adjustMsg);
        newPersonPosFile.set(PositionStructureConstant.NCKD_RANKSCORE, jobLevelResult.jobScoreInfo.perProTitleScore);
        newPersonPosFile.set(PositionStructureConstant.NCKD_JOBSTATUSSCORE, jobLevelResult.jobScoreInfo.quaLevelScore);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ALLSUMSCORE, jobLevelResult.jobScoreInfo.allSumScore);
        //积分池（生涯积分）使用最后一次职位档案中的，因为动态调整不涉及生涯积分变动
        BigDecimal sumScore = latsPersonPosFile.containsProperty(PositionStructureConstant.NCKD_SUMSCORE) ? latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_SUMSCORE) : null;
        newPersonPosFile.set(PositionStructureConstant.NCKD_SUMSCORE,sumScore);
        newPersonPosFile.set(PositionStructureConstant.NCKD_BEGINDATE, adjustDate);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ADJUSTINT, null);
        newPersonPosFile.set(PositionStructureConstant.NCKD_FIRSTRANK, null);


        newPersonPosFile.set(PositionStructureConstant.NCKD_TOPRANK,
                jobLevelResult.rankingResultInfo != null ? jobLevelResult.rankingResultInfo.topRank : null);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ALLOWANCERANK,
                jobLevelResult.rankingResultInfo != null ? jobLevelResult.rankingResultInfo.allowanceRank : null);
        newPersonPosFile.set(PositionStructureConstant.NCKD_TOPRANKPERCENT,
                jobLevelResult.rankingResultInfo != null ? jobLevelResult.rankingResultInfo.topRankPercent : null);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ALLOWANCERANKMARK,
                jobLevelResult.rankingResultInfo != null ? jobLevelResult.rankingResultInfo.allowanceRankMark : null);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ALLOWANCERANKSEL,
                jobLevelResult.rankingResultInfo != null ? jobLevelResult.rankingResultInfo.allowanceRankSel : null);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ALLOWANCERANKPCT,
                jobLevelResult.rankingResultInfo != null ? jobLevelResult.rankingResultInfo.allowanceRankPercent : null);
        //上年度考核结果
        DynamicObject performanceResult = lastYearPerformanceResultMap.get(personId);
        if(performanceResult != null){
            newPersonPosFile.set(PositionStructureConstant.NCKD_APPRAISALRESULT, performanceResult);
            newPersonPosFile.set(PositionStructureConstant.NCKD_RESULTSCORE, performanceResult.getBigDecimal(FormConstant.NCKD_SCORE));
        }
        if(frontendJobLevelId != null && Objects.equals(frontendJobLevelId, jobLevelId)){
            newPersonPosFile.set(PositionStructureConstant.NCKD_ADJUSTTYPE, jobLevelResult.adjustType);
        }else{
            //判断【职称等级】和【技能等级】都为空时设为"7"，表示“无聘任”。
            if((jobLevelResult.jobScoreInfo.perProTitleId == null || jobLevelResult.jobScoreInfo.perProTitleId == 0)
                    && (jobLevelResult.jobScoreInfo.quaLevelId == null || jobLevelResult.jobScoreInfo.quaLevelId == 0)){
                newPersonPosFile.set(PositionStructureConstant.NCKD_ADJUSTTYPE, "7");
            }else{
                newPersonPosFile.set(PositionStructureConstant.NCKD_ADJUSTTYPE, jobLevelResult.adjustType);
            }
        }

        newPersonPosFile.set(PositionStructureConstant.NCKD_DISABLE, EnableEnum.NO.getCode());
        // 这里不能直接定义为最新的，需要点击生效才是最新的
        // newPersonPosFile.set(PositionStructureConstant.NCKD_ISCURRENTNEWEST, EnableEnum.YES.getCode());
        newPersonPosFile.set(PositionStructureConstant.STATUS, StatusEnum.C.toString());
        newPersonPosFile.set(PositionStructureConstant.ENABLE, EnableEnum.YES.getCode());
        // 备注
        newPersonPosFile.set(PositionStructureConstant.KEY_NCKD_CAUSEREMARK, remark);
        newPersonPosFile.set(FormConstant.CREATE_TIME_KEY, null);
        newPersonPosFile.set(FormConstant.CREATOR_KEY, RequestContext.get().getCurrUserId());
        newPersonPosFile.set(FormConstant.MODIFY_TIME_KEY, null);
        newPersonPosFile.set(FormConstant.MODIFIER_KEY, null);

        // 聘任状态
        /*String employmentStatus = latsPersonPosFile.getString(PositionStructureConstant.NCKD_EMPLOYMENTSTATUS);
        newPersonPosFile.set(PositionStructureConstant.NCKD_EMPLOYMENTSTATUS, employmentStatus);
        // 连续聘任年限
        int employmentYears = latsPersonPosFile.getInt(PositionStructureConstant.NCKD_EMPLOYMENTYEARS);
        newPersonPosFile.set(PositionStructureConstant.NCKD_EMPLOYMENTYEARS, employmentYears);
        // 优秀生分
        BigDecimal orginsScore = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_ORGINSSCORE);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ORGINSSCORE, orginsScore);
        // 上年度贡献综合评价分
        BigDecimal lyrContribScore = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_LYRCONTRIBSCORE);
        newPersonPosFile.set(PositionStructureConstant.NCKD_LYRCONTRIBSCORE, lyrContribScore);
        // 任命结束日期
        Date endDate = latsPersonPosFile.getDate(PositionStructureConstant.NCKD_ENDDATE);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ENDDATE, endDate);
        // 任命状态
        String appointStatus = latsPersonPosFile.getString(PositionStructureConstant.NCKD_APPOINTSTATUS);
        newPersonPosFile.set(PositionStructureConstant.NCKD_APPOINTSTATUS, appointStatus);
        // 年度调整状态
        String adjusStatus = latsPersonPosFile.getString(PositionStructureConstant.NCKD_ADJUSSTATUS);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ADJUSSTATUS, adjusStatus);
        // 年度科研与创新分
        BigDecimal yearScoreSumA = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMA);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMA, yearScoreSumA);
        // 年度专利申报分
        BigDecimal yearScoreSumB = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMB);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMB, yearScoreSumB);
        // 年度论文发表分
        BigDecimal yearScoreSumC = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMC);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMC, yearScoreSumC);
        // 年度技能竞赛分
        BigDecimal yearScoreSumD = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMD);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMD, yearScoreSumD);
        // 年度培训教材分
        BigDecimal yearScoreSumE = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUME);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUME, yearScoreSumE);
        // 年度技术标准分
        BigDecimal yearScoreSumF = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMF);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMF, yearScoreSumF);
        // 年度管理规范分
        BigDecimal yearScoreSumG = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMG);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMG, yearScoreSumG);
        // 年度师带徒分
        BigDecimal yearScoreSumH = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMH);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMH, yearScoreSumH);
        // 年度培训授课分
        BigDecimal yearScoreSumI = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_YEARSCORESUMI);
        newPersonPosFile.set(PositionStructureConstant.NCKD_YEARSCORESUMI, yearScoreSumI);
        // 贡献单据分数之和
        BigDecimal allYearScoreSum = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_ALLYEARSCORESUM);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ALLYEARSCORESUM, allYearScoreSum);
        // 年度新增的贡献积分
        BigDecimal addYContribScore = latsPersonPosFile.getBigDecimal(PositionStructureConstant.NCKD_ADDYCONTRIBSCORE);
        newPersonPosFile.set(PositionStructureConstant.NCKD_ADDYCONTRIBSCORE, addYContribScore);*/


        personIds.add(personId);
        newPersonPosFiles.add(newPersonPosFile);
    }

    /**
     * 设置操作结果中的职级信息
     */
    protected void setJobLevelResult(DynamicObject person, DynamicObject jobLeve) {
        String jobLeveStr = StrFormatter.format("{}：{}（{}级）",
                person.getString(FormConstant.NAME_KEY),
                jobLeve.getString(FormConstant.NAME_KEY),
                jobLeve.getString(PositionStructureConstant.NCKD_ALIAS));

        Map<String, String> customData = this.getOperationResult().getCustomData();
        if(customData == null) {
            this.getOperationResult().setCustomData(new HashMap<>());
            customData = this.getOperationResult().getCustomData();
        }

        String oldJobLeveStr = customData.get(PositionStructureConstant.NCKD_JOBLEVELHR);
        if (oldJobLeveStr == null || oldJobLeveStr.isEmpty()) {
            customData.put(PositionStructureConstant.NCKD_JOBLEVELHR, jobLeveStr);
        } else {
            customData.put(PositionStructureConstant.NCKD_JOBLEVELHR, oldJobLeveStr + StrFormatter.LINE_SEPARATOR + jobLeveStr);
        }
    }
}