//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nckd.jimin.jyyy.hr.swc.hcdm.formplugin.web;

import com.google.common.collect.Lists;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.validate.ValidateResult;
import kd.bos.ext.hr.metadata.edit.MulPersonEdit;
import kd.bos.ext.hr.metadata.edit.MulQueryEdit;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.EntryGridBindDataEvent;
import kd.bos.form.control.events.EntryGridBindDataListener;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.*;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.DateEdit;
import kd.bos.form.field.MulBasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.field.events.DateClickListener;
import kd.bos.form.field.events.ResetDateFilterEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.SessionManager;
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.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.workflow.WorkflowServiceHelper;
import kd.hr.hbp.bussiness.cert.HRCertCommonHelper;
import kd.hr.hbp.bussiness.cert.HRCertNoticeTypeEnum;
import kd.hr.hbp.common.util.*;
import kd.hr.hbp.formplugin.web.HRDataBaseEdit;
import kd.hrmp.hrpi.business.infrastructure.utils.QFilterUtil;
import kd.tdc.tdcs.bussiness.formservice.FormCommonService;
import kd.tdc.tdcs.bussiness.license.TDCSCertCommonHelper;
import kd.tdc.tjga.business.application.quickchange.BatchChangeGradeLevelApplication;
import kd.tdc.tjga.business.formservice.BatchChangeGradeLevelFormService;
import kd.tdc.tjga.common.util.CommUtils;
import kd.tdc.tjga.common.util.ControlDataSyn;
import kd.tdc.tjga.common.util.TjgaObjectUtils;
import nckd.jimin.jyyy.hr.hrmp.hbpm.task.SyncUtil;
import org.apache.commons.lang3.StringUtils;

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

public class AdjustJobBillEdit extends HRDataBaseEdit implements BeforeF7SelectListener, DateClickListener, EntryGridBindDataListener {
    private static final Log logger = LogFactory.getLog(AdjustJobBillEdit.class);

    public AdjustJobBillEdit() {
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        MulPersonEdit ermanfileF7 = (MulPersonEdit)this.getControl("ermanfiles");
        ermanfileF7.addBeforeF7SelectListener(this);
        MulBasedataEdit muladjFileF7 = (MulBasedataEdit) this.getControl("nckd_muladjrecord");
        muladjFileF7.addBeforeF7SelectListener(this);
        BasedataEdit hrbu = (BasedataEdit)this.getControl("hrbu");
        hrbu.addBeforeF7SelectListener(this);
        BasedataEdit jobGrade = (BasedataEdit)this.getControl("jobgrade");
        jobGrade.addBeforeF7SelectListener(this);
        BasedataEdit jobLevel = (BasedataEdit)this.getControl("joblevel");
        jobLevel.addBeforeF7SelectListener(this);
        BasedataEdit standardItem = (BasedataEdit)this.getControl("nckd_standarditem");
        standardItem.addBeforeF7SelectListener(this);
        this.addItemClickListeners(new String[]{"advcontoolbarap","nckd_advcontoolbarap"});
        DateEdit dateEdit = (DateEdit)this.getControl("changeeffdate");
        dateEdit.addDateClickListener(this);
        EntryGrid changeEntry = (EntryGrid)this.getControl("changeentry");
        changeEntry.addDataBindListener(this);
    }

    @Override
    public void afterCreateNewData(EventObject e) {

    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        BillShowParameter formShowParameter = (BillShowParameter)this.getView().getFormShowParameter();
        String billStatus = this.getModel().getDataEntity().getString("billstatus");
        if (!"A".equals(billStatus)) {
            String billNo = this.getModel().getDataEntity().getString("billno");
            String capation = ResManager.loadKDString("批量职等调整单", "BatchChangeGradeLevelEdit_3", "tdc-tjga-formplugin", new Object[0]);
            formShowParameter.setCaption(CommUtils.appendStr(new String[]{capation, "-", billNo}));
        }

    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }


    public void setEntryEnable() {
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("changeentry");
        for(int i = 0; i < entryEntity.size(); ++i) {
            DynamicObject entryRowObj = (DynamicObject)entryEntity.get(i);
            //this.setRowEnable(entryRowObj, i);
        }

    }

    public void setRowEnable(DynamicObject entryRowObj, Integer row) {
        Set<String> falseEnableSet = this.getFalseEnableColumnName(entryRowObj);
        this.getView().setEnable(Boolean.FALSE, row, (String[])falseEnableSet.toArray(new String[0]));
        String[] trueEnableArr = (String[])this.getTrueEnableColumnName(entryRowObj, falseEnableSet).toArray(new String[0]);
        this.getView().setEnable(Boolean.TRUE, row, trueEnableArr);
    }

    public Set<String> getFalseEnableColumnName(DynamicObject entryRowObj) {
        Set<String> falseFieldNameSet = new HashSet(6);
        if (HRObjectUtils.isEmpty(entryRowObj.get("hrbu"))) {
            falseFieldNameSet.addAll(Lists.newArrayList(new String[]{"job", "jobgradescm", "joblevelscm", "jobgrade", "joblevel"}));
            return falseFieldNameSet;
        } else if (HRObjectUtils.isEmpty(entryRowObj.get("job"))) {
            falseFieldNameSet.addAll(Lists.newArrayList(new String[]{"jobgradescm", "joblevelscm", "jobgrade", "joblevel"}));
            return falseFieldNameSet;
        } else {
            if (!HRObjectUtils.isEmpty(entryRowObj.get("job"))) {
                DynamicObject jobObj = entryRowObj.getDynamicObject("job");
                BatchChangeGradeLevelFormService formService = new BatchChangeGradeLevelFormService();
                long jobGradeScmId = formService.getJobGradeOrLevelScm(jobObj, "jobgradescm");
                long gradeScmId = entryRowObj.getLong("jobgradescm.id");
                if (gradeScmId != 0L && jobGradeScmId == gradeScmId) {
                    falseFieldNameSet.addAll(Lists.newArrayList(new String[]{"jobgradescm"}));
                }

                long jobLevleScmId = formService.getJobGradeOrLevelScm(jobObj, "joblevelscm");
                long levelScmId = entryRowObj.getLong("joblevelscm.id");
                if (levelScmId != 0L && jobLevleScmId == levelScmId) {
                    falseFieldNameSet.addAll(Lists.newArrayList(new String[]{"joblevelscm"}));
                }
            }

            if (HRObjectUtils.isEmpty(entryRowObj.get("jobgradescm"))) {
                falseFieldNameSet.add("jobgrade");
            }

            if (HRObjectUtils.isEmpty(entryRowObj.get("joblevelscm"))) {
                falseFieldNameSet.add("joblevel");
            }

            return falseFieldNameSet;
        }
    }

    public Set<String> getTrueEnableColumnName(DynamicObject entryRowObj, Set<String> falseEnableSet) {
        Set<String> trueFieldNameList = new HashSet(6);
        trueFieldNameList.add("hrbu");
        if (!HRObjectUtils.isEmpty(entryRowObj.get("hrbu"))) {
            trueFieldNameList.add("job");
        }

        if (!falseEnableSet.contains("jobgradescm")) {
            trueFieldNameList.add("jobgradescm");
        }

        if (!falseEnableSet.contains("joblevelscm")) {
            trueFieldNameList.add("joblevelscm");
        }

        if (!falseEnableSet.contains("jobgrade")) {
            trueFieldNameList.add("jobgrade");
        }

        if (!falseEnableSet.contains("joblevel")) {
            trueFieldNameList.add("joblevel");
        }

        return trueFieldNameList;
    }

    public void setViewFlowChartVisible(String billStatus) {
        Boolean isExistsWorkFlow = this.getModel().getDataEntity().getBoolean("isexistsworkflow");
        Boolean isShowViewFlowChartBtn = CommUtils.anyMatchStr(billStatus, new String[]{"F", "B", "D", "C", "E"}) && isExistsWorkFlow;
        this.getView().setVisible(isShowViewFlowChartBtn, new String[]{"bar_viewflowchart"});
    }

    @Override
    public void propertyChanged(PropertyChangedArgs args) {
        String name = args.getProperty().getName();
        int rowNum;
        if ("job".equals(name)) {
            rowNum = this.getModel().getEntryCurrentRowIndex("changeentry");
            ChangeData[] changeDataArr = args.getChangeSet();
            Object newValue = changeDataArr[0].getNewValue();
            if (HRObjectUtils.isEmpty(newValue)) {
                this.getModel().setValue("seqfamclass", "", rowNum);
            } else {
                String afterSeqFailyClass = (new BatchChangeGradeLevelFormService()).getAfterSeqFailyClass((DynamicObject)newValue);
                this.getModel().setValue("seqfamclass", afterSeqFailyClass, rowNum);
            }

            BatchChangeGradeLevelFormService formService = new BatchChangeGradeLevelFormService();
            Long jobGradeScmId = formService.getJobGradeOrLevelScm((DynamicObject)newValue, "jobgradescm");
            Boolean gradeScmEnable = jobGradeScmId == 0L ? Boolean.TRUE : Boolean.FALSE;
            this.getView().setEnable(gradeScmEnable, rowNum, new String[]{"jobgradescm"});
            this.getModel().setValue("jobgradescm", jobGradeScmId, rowNum);
            Long jobLevelScmId = formService.getJobGradeOrLevelScm((DynamicObject)newValue, "joblevelscm");
            Boolean levelScmEnable = jobLevelScmId == 0L ? Boolean.TRUE : Boolean.FALSE;
            this.getView().setEnable(levelScmEnable, rowNum, new String[]{"joblevelscm"});
            this.getModel().setValue("joblevelscm", jobLevelScmId, rowNum);
        }

        if (CommUtils.anyMatchStr(name, new String[]{"hrbu", "job", "jobgradescm", "joblevelscm"})) {
            rowNum = this.getModel().getEntryCurrentRowIndex("changeentry");
            DynamicObject dynamicObject = (DynamicObject)this.getModel().getEntryEntity("changeentry").get(rowNum);
            this.setRowEnable(dynamicObject, rowNum);
        }

    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate source = (FormOperate)args.getSource();
        String operateKey = source.getOperateKey();
        String cache = this.getView().getPageCache().get("notNeedCheck");
        if (CommUtils.anyMatchStr(operateKey, new String[]{"submit", "submiteffect"}) && HRStringUtils.isEmpty(cache)) {
            if (HRCollUtil.isEmpty(this.opCheck())) {
                args.setCancel(true);
                return;
            }

            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection entryObj = dataEntity.getDynamicObjectCollection("changeentry");
            if (HRCollUtil.isNotEmpty(entryObj)) {
                OperateOption operateOption = OperateOption.create();
                operateOption.setVariableValue("isopcancel", "1");
                OperationResult result = OperationServiceHelper.executeOperate("savecheck", "nckd_jobadjustbill", new DynamicObject[]{dataEntity}, operateOption);
                if (!result.isSuccess()) {
                    List<ValidateResult> validateErrors = result.getValidateResult().getValidateErrors();
                    if (HRCollUtil.isNotEmpty(validateErrors)) {
                        ValidateResult validateResult = (ValidateResult)validateErrors.get(0);
                        List<OperateErrorInfo> allErrorInfo = validateResult.getAllErrorInfo();
                        if (HRCollUtil.isNotEmpty(allErrorInfo)) {
                            this.getView().showErrorNotification(((OperateErrorInfo)allErrorInfo.get(0)).getMessage());
                        }

                        args.setCancel(true);
                        return;
                    }
                }
            }

            BatchChangeGradeLevelFormService fromService = new BatchChangeGradeLevelFormService();
            String jobGradeNameStr = fromService.afterEmptyBeforeHaveValue(entryObj, "bjobgrade", "jobgrade");
            String jobLevelNameStr = fromService.afterEmptyBeforeHaveValue(entryObj, "bjoblevel", "joblevel");
            if (HRStringUtils.isNotEmpty(jobGradeNameStr) || HRStringUtils.isNotEmpty(jobLevelNameStr)) {
                String msg = ResManager.loadKDString("请确认以下信息，确定继续吗？", "BatchChangeGradeLevelEdit_6", "tdc-tjga-formplugin", new Object[0]);
                String detailStr = "";
                if (HRStringUtils.isNotEmpty(jobGradeNameStr)) {
                    detailStr = ResManager.loadKDString("员工“{0}”调整前职等不为空，调整后职等为空。", "BatchChangeGradeLevelEdit_7", "tdc-tjga-formplugin", new Object[]{jobGradeNameStr});
                }

                if (HRStringUtils.isNotEmpty(jobLevelNameStr)) {
                    String levelStr = ResManager.loadKDString("员工“{0}”调整前职级不为空，调整后职级为空。", "BatchChangeGradeLevelEdit_8", "tdc-tjga-formplugin", new Object[]{jobLevelNameStr});
                    detailStr = StringUtils.isEmpty(detailStr) ? levelStr : CommUtils.appendStr(new String[]{detailStr, "\n", levelStr});
                }

                this.getView().showConfirm(msg, detailStr, MessageBoxOptions.OKCancel, ConfirmTypes.Default, new ConfirmCallBackListener(operateKey));
                args.setCancel(true);
                return;
            }
        } else if (CommUtils.anyMatchStr(operateKey, new String[]{"save", "submit", "submiteffect"}) && "notNeedCheck".equals(cache)) {
            this.getView().getPageCache().put("notNeedCheck", (String)null);
        }

        if ("submit".equals(operateKey) && (!WorkflowServiceHelper.existProcDefByEntityNumber("nckd_jobadjustbill") || CollectionUtils.isEmpty(WorkflowServiceHelper.getEnabledProcesses(this.getModel().getDataEntity(), "submit")))) {
            this.getView().showErrorNotification(ResManager.loadKDString("未匹配到工作流，请先完成相关流程配置。", "BatchChangeGradeLevelEdit_9", "tdc-tjga-formplugin", new Object[0]));
            args.setCancel(true);
        } else {
            if (CommUtils.anyMatchStr(operateKey, new String[]{"save", "submit", "submiteffect"})) {
                int size = this.getModel().getEntryEntity("changeentry").size();
                this.getModel().setValue("totalnum", size);
            }

            if ("import_entrydata_hr".equals(operateKey)) {
                SessionManager.getCurrent().put("tjga_batchjob_pageid", this.getView().getPageId());
            }

        }
    }

    private boolean permVerification(BeforeDoOperationEventArgs args) {
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("changeentry");
        List<Long> personIdList = (List)entryEntity.stream().map((row) -> {
            return row.getLong("person.id");
        }).collect(Collectors.toList());
        if (HRCollUtil.isEmpty(personIdList)) {
            args.setCancel(true);
            return true;
        } else {
            Map<String, Object> certRstMap = TDCSCertCommonHelper.verifyCertByPersonId("326PLYR3VT8A", "tjga_batchjob", personIdList);
            String state = (String)certRstMap.get("STATE");
            if ("FORBID".equals(state)) {
                Map<String, Object> data = (Map)certRstMap.get("DATA");
                String message = (String)data.get("FD_HTML_MESSAGE");
                this.getView().showForm(HRCertCommonHelper.getFormShowParameter(HRCertNoticeTypeEnum.FORBIDDEN.getName(), (String)null, message));
                args.setCancelMessage(message);
                args.setCancel(true);
                return true;
            } else if ("FAIL".equals(state)) {
                String message = (String)certRstMap.get("FAIL_HTML_MESSAGE");
                this.getView().showForm(HRCertCommonHelper.getFormShowParameter(HRCertNoticeTypeEnum.ENCODE.getName(), (String)null, message));
                args.setCancelMessage(message);
                args.setCancel(true);
                return true;
            } else {
                return false;
            }
        }
    }

    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        String operateKey = afterDoOperationEventArgs.getOperateKey();
        if ("deleteentry".equals(operateKey)) {
            (new ControlDataSyn()).entryToMulBaseEdit(this, "ermanfiles", "changeentry", "employee");
        }

        if ("terminate_bill".equals(operateKey) && afterDoOperationEventArgs.getOperationResult().isSuccess()) {
            List<DynamicObject> processingBills = this.opCheck();
            if (HRCollUtil.isEmpty(processingBills)) {
                return;
            }

            (new BatchChangeGradeLevelFormService()).showTerminatePage(this, "terminate_bill_callback");
        }

        if ("submit".equals(operateKey)) {
            String billStatus = this.getModel().getDataEntity().getString("billstatus");
            this.setViewFlowChartVisible(billStatus);
        }

        if (CommUtils.anyMatchStr(operateKey, new String[]{"unsubmit", "save", "submit", "submiteffect"})) {
            this.getView().updateView();
        }

    }

    public void beforeItemClick(BeforeItemClickEvent evt) {
        String key = evt.getItemKey();
        int[] selectRows;
        String confirmStr;
        if (HRStringUtils.equals(key, "delemp")) {
            selectRows = ((EntryGrid)this.getControl("changeentry")).getSelectRows();
            if (selectRows.length != 0) {
                confirmStr = ResManager.loadKDString("确定要删除选中的数据吗？", "BatchChangeGradeLevelEdit_1", "tdc-tjga-formplugin", new Object[0]);
                this.getView().showConfirm(confirmStr, MessageBoxOptions.OKCancel, new ConfirmCallBackListener("delemp"));
                evt.setCancel(true);
            }
        }

        if ("batchwrite".equals(key)) {
            selectRows = ((EntryGrid)this.getControl("changeentry")).getSelectRows();
            if (selectRows.length == 0) {
                confirmStr = ResManager.loadKDString("请选择要执行的数据。", "BatchChangeGradeLevelEdit_2", "tdc-tjga-formplugin", new Object[0]);
                this.getView().showTipNotification(confirmStr);
                evt.setCancel(true);
            }
        }

    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        String callBackId = messageBoxClosedEvent.getCallBackId();
        if ("delemp".equals(callBackId) && MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
            this.getView().invokeOperation("deleteentry");
            this.setEntryEnable();
        }

        if (CommUtils.anyMatchStr(callBackId, new String[]{"save", "submit", "submiteffect"}) && MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
            this.getView().getPageCache().put("notNeedCheck", "notNeedCheck");
            this.getView().invokeOperation(callBackId);
        }

    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String key = evt.getItemKey();
        if (HRStringUtils.equals(key, "addemp")) {
            (new ControlDataSyn()).entryToMulBaseEdit(this, "ermanfiles", "changeentry", "employee");
            BasedataEdit talentfile = (BasedataEdit)this.getControl("ermanfiles");
            talentfile.click();
        }
        if(HRStringUtils.equals(key, "nckd_addsalemp")) {
            (new ControlDataSyn()).entryToMulBaseEdit(this, "nckd_muladjrecord", "nckd_entryentity", "nckd_adjrecord");
            BasedataEdit muladjFile = (BasedataEdit)this.getControl("nckd_muladjrecord");
            muladjFile.click();
        }
    }

    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        String name = beforeF7SelectEvent.getProperty().getName();
        ListShowParameter formShowParameter = (ListShowParameter)beforeF7SelectEvent.getFormShowParameter();
        if ("ermanfiles".equals(name)) {
            List<QFilter> customQFilters = beforeF7SelectEvent.getCustomQFilters();
//            QFilter orgPermissionQFilter = PermissionApplicationService.bosOrgQFilter("tjga", "tjga_batchjob", "47150e89000000ac", "org");
//            customQFilters.add(orgPermissionQFilter);
//            customQFilters.add(new QFilter("iscurrentversion", "=", "1"));
//            customQFilters.add(new QFilter("datastatus", "=", "1"));
//            customQFilters.add(new QFilter("isprimary", "=", "1"));
//            logger.info("BatchChangeGradeLevelEdit#beforeF7Select TALENT_FILE filter:{}", customQFilters.toString());
            formShowParameter.setCloseCallBack(new CloseCallBack(this, "ermanfiles"));
        }

        //多选定调薪信息之前，过滤当前版本
        if("nckd_muladjrecord".equals(name)) {
            List<QFilter> customQFilters = beforeF7SelectEvent.getCustomQFilters();
            customQFilters.add(new QFilter("iscurrentversion", "=", "1"));
            formShowParameter.setCloseCallBack(new CloseCallBack(this, "muladjrecord"));
        }

        //过滤，只能选择定调薪信息里面的定调薪项目
        if("nckd_standarditem".equals(name)) {
            int currRow = this.getModel().getEntryCurrentRowIndex("nckd_entryentity");
            DynamicObject entryRowEntity = this.getModel().getEntryRowEntity("nckd_entryentity", currRow);
            DynamicObject fileObj = entryRowEntity.getDynamicObject("nckd_adjrecord");
            QFilter filter = QFilterUtil.getCurrentQf();
            filter.and("salaryadjfile.id", QCP.equals, fileObj.getPkValue());
            DynamicObjectCollection records = QueryServiceHelper.query("hcdm_salaryadjrecord", "standarditem.id", new QFilter[]{filter});
            List<Long> itemIds = records.stream().map((dyx -> dyx.getLong("standarditem.id"))).collect(Collectors.toList());
            List<QFilter> customQFilters = beforeF7SelectEvent.getCustomQFilters();
            customQFilters.add(new QFilter("id", QCP.in, itemIds));
        }

        if ("hrbu".equals(name)) {
            formShowParameter.setMultiSelect(false);
        }

        if ("jobgrade".equals(name) || "joblevel".equals(name)) {
            int currRow = this.getModel().getEntryCurrentRowIndex("changeentry");
            DynamicObject entryRowEntity = this.getModel().getEntryRowEntity("changeentry", currRow);
            DynamicObject jobObj = entryRowEntity.getDynamicObject("job");
            BatchChangeGradeLevelFormService formService = new BatchChangeGradeLevelFormService();
            String scmName = "jobgrade".equals(name) ? "jobgradescm" : "joblevelscm";
            DynamicObject scmObj = entryRowEntity.getDynamicObject(scmName);
            String lowJobIdKey = "jobgrade".equals(name) ? "lowjobgrade.id" : "lowjoblevel.id";
            String highJobIdKey = "jobgrade".equals(name) ? "highjobgrade.id" : "highjoblevel.id";
            String sortKey = "jobgrade".equals(name) ? "jobgrade_seq" : "joblevel_seq";
            String sortStr = "jobgrade".equals(name) ? "jobgradeseq asc" : "joblevelseq asc";
            List<Long> ids = formService.getGradeOrLevelRangeIds(jobObj, lowJobIdKey, highJobIdKey, sortKey, scmObj);
            beforeF7SelectEvent.getCustomQFilters().add(new QFilter("id", "in", ids));
            formShowParameter.getListFilterParameter().setOrderBy(sortStr);
        }

    }

    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        String actionId = closedCallBackEvent.getActionId();
        long entryGradeId;

        if("muladjrecord".equals(actionId)) {
            List<Object> primaryIds = getCallBackSelectIds(closedCallBackEvent);
            if (HRCollUtil.isEmpty(primaryIds)) {
                return;
            }

            if (primaryIds.size() >= 100000) {
                this.getView().showErrorNotification(ResManager.loadKDString("最多只能添加100000条数据。", "BatchChangeGradeLevelEdit_11", "tdc-tjga-formplugin", new Object[0]));
                return;
            }
            BatchChangeGradeLevelFormService formService = new BatchChangeGradeLevelFormService();
            List<Long> primaryIdList = (List)primaryIds.stream().map((p) -> {
                return (Long)p;
            }).collect(Collectors.toList());
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("nckd_entryentity");
            Set<Long> existsFileId = (Set)entryEntity.stream().map((d) -> {
                return d.getLong("nckd_adjrecord.id");
            }).collect(Collectors.toSet());
            Set<Long> checkProcessingId = (Set)primaryIdList.stream().filter((id) -> {
                return !existsFileId.contains(id);
            }).collect(Collectors.toSet());
            Set<Long> processingFileIds = (Set)formService.showProcessingEmp(this, checkProcessingId);
            Set<Long> notProcessingIds = (Set)primaryIdList.stream().filter((id) -> {
                return !processingFileIds.contains(id);
            }).collect(Collectors.toSet());
            this.getModel().setValue("nckd_muladjrecord", notProcessingIds.toArray());
            Set<Long> newIdSet = (new ControlDataSyn()).mulBaseEditToEntry(this, "nckd_muladjrecord", new String[]{"id"}, "nckd_entryentity", new String[]{"nckd_adjrecord"});
            DynamicObjectCollection changeCollection = this.getModel().getDataEntity(true).getDynamicObjectCollection("nckd_entryentity");
            Set<Long> empIdSet = (Set)changeCollection.stream().filter((d) -> {
                return newIdSet.contains(d.getLong("nckd_adjrecord.id"));
            }).map((d) -> {
                return d.getLong("nckd_adjrecord.id");
            }).collect(Collectors.toSet());
            IDataModel model = this.getModel();
            model.beginInit();
            for(int rowNum = 0; rowNum < changeCollection.size(); ++rowNum) {
                DynamicObject changeRowObj = (DynamicObject)changeCollection.get(rowNum);
                DynamicObject record = changeRowObj.getDynamicObject("nckd_adjrecord");
                Long adjFileId = record.getLong("salaryadjfile.id");
                DynamicObject adjFile = BusinessDataServiceHelper.loadSingle(adjFileId, "hcdm_adjfileinfo");
                DynamicObject relPerson = BusinessDataServiceHelper.loadSingle(record.getLong("relpersonid"), "hcdm_decadjrelperson");
                model.setValue("nckd_adjfile", adjFile, rowNum);
                model.setValue("nckd_salname", adjFile.getString("person.name"), rowNum);
                model.setValue("nckd_salnumber", adjFile.getString("person.number"), rowNum);
                model.setValue("nckd_saladminorg", adjFile.getDynamicObject("adminorg"), rowNum);
                model.setValue("nckd_salposition", adjFile.getDynamicObject("position"), rowNum);
                model.setValue("nckd_standarditem", record.getDynamicObject("standarditem"), rowNum);
                model.setValue("nckd_oldamount", record.getBigDecimal("amount"), rowNum);

                model.setValue("nckd_saljoblevel", relPerson.getDynamicObject("joblevel"), rowNum);
                model.setValue("nckd_saljobgrade", relPerson.getDynamicObject("jobgrade"), rowNum);

            }
            model.endInit();
            this.getView().updateView("nckd_entryentity");
        }


        if ("ermanfiles".equals(actionId)) {
            List<Object> primaryIds = getCallBackSelectIds(closedCallBackEvent);
            if (HRCollUtil.isEmpty(primaryIds)) {
                return;
            }

            if (primaryIds.size() >= 100000) {
                this.getView().showErrorNotification(ResManager.loadKDString("最多只能添加100000条数据。", "BatchChangeGradeLevelEdit_11", "tdc-tjga-formplugin", new Object[0]));
                return;
            }

            BatchChangeGradeLevelFormService formService = new BatchChangeGradeLevelFormService();
            List<Long> primaryIdList = (List)primaryIds.stream().map((p) -> {
                return (Long)p;
            }).collect(Collectors.toList());
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("changeentry");
            Set<Long> existsTalentId = (Set)entryEntity.stream().map((d) -> {
                return d.getLong("employee.id");
            }).collect(Collectors.toSet());
            Set<Long> checkProcessingId = (Set)primaryIdList.stream().filter((id) -> {
                return !existsTalentId.contains(id);
            }).collect(Collectors.toSet());
            Set<Long> processingTalentIds = (Set)formService.showProcessingEmp(this, checkProcessingId);
            Set<Long> notProcessingIds = (Set)primaryIdList.stream().filter((id) -> {
                return !processingTalentIds.contains(id);
            }).collect(Collectors.toSet());
            this.getModel().setValue("ermanfiles", notProcessingIds.toArray());
            Set<Long> newIdSet = (new ControlDataSyn()).mulBaseEditToEntry(this, "ermanfiles", new String[]{"id","person.id"}, "changeentry", new String[]{"employee","person"});

            DynamicObjectCollection changeCollection = this.getModel().getDataEntity(true).getDynamicObjectCollection("changeentry");
            Set<Long> empIdSet = (Set)changeCollection.stream().filter((d) -> {
                return newIdSet.contains(d.getLong("employee.id"));
            }).map((d) -> {
                return d.getLong("employee.id");
            }).collect(Collectors.toSet());
            Map<Long, DynamicObject> empJobMap = (new BatchChangeGradeLevelApplication()).queryEmpJobInfo(empIdSet);
            Map<String, Object> permissionHrBuMap = formService.currentUserPermissionHrBu();
            IDataModel model = this.getModel();
            model.beginInit();

            for(int rowNum = 0; rowNum < changeCollection.size(); ++rowNum) {
                DynamicObject changeRowObj = (DynamicObject)changeCollection.get(rowNum);
                if (newIdSet.contains(changeRowObj.getLong("employee.id"))) {
                    model.setValue("name", changeRowObj.getString("person.name"), rowNum);
                    model.setValue("number", changeRowObj.getString("person.number"), rowNum);
                    Long employeeId = changeRowObj.getLong("employee.id");
                    DynamicObject dyn = SyncUtil.getAdminOrgAndPositionByEmployeeId(employeeId);
                    if(!ObjectUtils.isEmpty(dyn)) {
                        model.setValue("adminorg", dyn.getLong("adminorg.id"), rowNum);
                        model.setValue("position", dyn.getLong("position.id"), rowNum);
                    }
                    DynamicObject empJobObj = (DynamicObject)empJobMap.get(employeeId);
                    if (!HRObjectUtils.isEmpty(empJobObj)) {
                        entryGradeId = empJobObj.getLong("hrbu.id");
                        model.setValue("bhrbu", entryGradeId, rowNum);
                        model.setValue("bjob", empJobObj.getLong("job.id"), rowNum);
                        model.setValue("bjobgradescm", empJobObj.getLong("jobgradescm.id"), rowNum);
                        model.setValue("bjobgrade", empJobObj.getLong("jobgrade.id"), rowNum);
                        model.setValue("bjoblevelscm", empJobObj.getLong("joblevelscm.id"), rowNum);
                        model.setValue("bjoblevel", empJobObj.getLong("joblevel.id"), rowNum);
                        model.setValue("bjobscm", empJobObj.getLong("jobscm.id"), rowNum);
                        Date startDate = empJobObj.getDate("startdate");
                        model.setValue("startdate", startDate, rowNum);
                        String bjobSeqName = HRStringUtils.isEmpty(empJobObj.getString("jobseq.name")) ? "-" : empJobObj.getString("jobseq.name");
                        String bjobFailyName = HRStringUtils.isEmpty(empJobObj.getString("jobfamily.name")) ? "-" : empJobObj.getString("jobfamily.name");
                        String bjobClassName = HRStringUtils.isEmpty(empJobObj.getString("jobclass.name")) ? "-" : empJobObj.getString("jobclass.name");
                        String seqFamilyClass = CommUtils.appendStr(new String[]{bjobSeqName, "/", bjobFailyName, "/", bjobClassName});
                        model.setValue("bseqfamclass", seqFamilyClass, rowNum);
                        Boolean superUser = (Boolean)permissionHrBuMap.get("superUser");
                        Set<Long> ids = (Set)permissionHrBuMap.get("PermissionHrBuIds");
                        if (superUser || ids.contains(entryGradeId)) {
                            model.setValue("hrbu", entryGradeId, rowNum);
                            /**
                             * 2025-07-30 Tyx 因业务做调动申请时，只变更岗位/职位，不变更职级职等，人员档案中职级职等不会生成新数据
                             * 这里改成取人员最新任职的职位/职级方案/职等方案
                             */
                            // 人员ID
                            Long personId = changeRowObj.getLong("person.id");
                            // 根据人员ID获取最新任职信息上的职位ID
                            Long jobId = getLatestJobIdByPersonId(personId);
                            model.setValue("job", jobId, rowNum);
                            model.setValue("seqfamclass", seqFamilyClass, rowNum);
                            DynamicObject entryRowEntity = this.getModel().getEntryRowEntity("changeentry", rowNum);
                            Long jobGradeScmId = formService.getJobGradeOrLevelScm(entryRowEntity.getDynamicObject("job"), "jobgradescm");
                            Boolean gradeScmEnable = jobGradeScmId == 0L ? Boolean.TRUE : Boolean.FALSE;
                            this.getView().setEnable(gradeScmEnable, rowNum, new String[]{"jobgradescm"});
                            model.setValue("jobgradescm", jobGradeScmId, rowNum);
                            Long jobLevelScmId = formService.getJobGradeOrLevelScm(entryRowEntity.getDynamicObject("job"), "joblevelscm");
                            Boolean levelScmEnable = jobLevelScmId == 0L ? Boolean.TRUE : Boolean.FALSE;
                            this.getView().setEnable(levelScmEnable, rowNum, new String[]{"joblevelscm"});
                            model.setValue("joblevelscm", jobLevelScmId, rowNum);
                        }

                        model.setValue("billnoentry", this.getModel().getDataEntity().getString("billno"), rowNum);
                    }
                }
            }

            model.endInit();
            this.getView().updateView("changeentry");
            this.setEntryEnable();
        }

        Map returnData;
        if ("batchwrite".equals(actionId)) {
            returnData = (Map)closedCallBackEvent.getReturnData();
            if (returnData != null && returnData.size() > 0) {
                DynamicObjectCollection changeEntry = this.getModel().getEntryEntity("changeentry");
                int[] selectRows = ((EntryGrid)this.getControl("changeentry")).getSelectRows();
                Set<Integer> selectRowSet = (Set)Arrays.stream(selectRows).boxed().collect(Collectors.toSet());
                IDataModel model = this.getModel();
                model.beginInit();

                for(int i = 0; i < changeEntry.size(); ++i) {
                    if (selectRowSet.contains(i)) {
                        if (!HRObjectUtils.isEmpty(returnData.get("changetype"))) {
                            this.getModel().setValue("changetype", returnData.get("changetype"), i);
                        }

                        Date startDate = ((DynamicObject)changeEntry.get(i)).getDate("startdate");
                        Date changeEffDate = (Date)returnData.get("changeeffdate");
                        if ((HRObjectUtils.isEmpty(changeEffDate) || startDate == null || !startDate.before(changeEffDate)) && startDate != null) {
                            if (!HRObjectUtils.isEmpty(changeEffDate)) {
                                this.getModel().setValue("changeeffdate", (Object)null, i);
                            }
                        } else {
                            this.getModel().setValue("changeeffdate", changeEffDate, i);
                        }

                        Object batchHrBUId = returnData.get("hrbu");
                        long entryHuBuId = ((DynamicObject)changeEntry.get(i)).getLong("hrbu.id");
                        if (!TjgaObjectUtils.isEmpty(batchHrBUId) && (Long)batchHrBUId != entryHuBuId) {
                            this.getModel().setValue("hrbu", returnData.get("hrbu"), i);
                            this.getModel().setValue("job", (Object)null, i);
                            this.getModel().setValue("jobgradescm", (Object)null, i);
                            this.getModel().setValue("jobgrade", (Object)null, i);
                            this.getModel().setValue("joblevelscm", (Object)null, i);
                            this.getModel().setValue("joblevel", (Object)null, i);
                        }

                        Object batchJobId = returnData.get("job");
                        long entryJobId = ((DynamicObject)changeEntry.get(i)).getLong("job.id");
                        if (!TjgaObjectUtils.isEmpty(batchJobId) && (Long)batchJobId != entryJobId) {
                            this.getModel().setValue("job", returnData.get("job"), i);
                            this.getModel().setValue("seqfamclass", returnData.get("seqfamclass"), i);
                            this.getModel().setValue("jobgradescm", (Object)null, i);
                            this.getModel().setValue("jobgrade", (Object)null, i);
                            this.getModel().setValue("joblevelscm", (Object)null, i);
                            this.getModel().setValue("joblevel", (Object)null, i);
                        }

                        Object batchGradeScmId = returnData.get("jobgradescm");
                        long entryGradeScmId = ((DynamicObject)changeEntry.get(i)).getLong("jobgradescm.id");
                        if (!TjgaObjectUtils.isEmpty(batchGradeScmId) && (Long)batchGradeScmId != entryGradeScmId) {
                            this.getModel().setValue("jobgradescm", returnData.get("jobgradescm"), i);
                            this.getModel().setValue("jobgrade", (Object)null, i);
                        }

                        Object batchGradeId = returnData.get("jobgrade");
                        entryGradeId = ((DynamicObject)changeEntry.get(i)).getLong("jobgrade.id");
                        if (!TjgaObjectUtils.isEmpty(batchGradeId) && (Long)batchGradeId != entryGradeId) {
                            this.getModel().setValue("jobgrade", returnData.get("jobgrade"), i);
                        }

                        Object batchLevelScmId = returnData.get("joblevelscm");
                        long entryLevelScmId = ((DynamicObject)changeEntry.get(i)).getLong("joblevelscm.id");
                        if (!TjgaObjectUtils.isEmpty(batchLevelScmId) && (Long)batchLevelScmId != entryLevelScmId) {
                            this.getModel().setValue("joblevelscm", returnData.get("joblevelscm"), i);
                            this.getModel().setValue("joblevel", (Object)null, i);
                        }

                        Object batchLevelId = returnData.get("joblevel");
                        long entryLevelId = ((DynamicObject)changeEntry.get(i)).getLong("joblevel.id");
                        if (!TjgaObjectUtils.isEmpty(batchLevelId) && (Long)batchLevelId != entryLevelId) {
                            this.getModel().setValue("joblevel", returnData.get("joblevel"), i);
                        }

                        if (!HRObjectUtils.isEmpty(returnData.get("changereason"))) {
                            this.getModel().setValue("changereason", returnData.get("changereason"), i);
                        }
                    }
                }

                model.endInit();
                this.getView().updateView("changeentry");
                this.setEntryEnable();
            }
        }

        if ("terminate_bill_callback".equals(actionId)) {
            returnData = (Map)closedCallBackEvent.getReturnData();
            if (!HRMapUtils.isEmpty(returnData) && returnData.get("iscofirm") != null && (Boolean)returnData.get("iscofirm")) {
                List<DynamicObject> processingBills = this.opCheck();
                if (HRCollUtil.isEmpty(processingBills)) {
                    return;
                }

                OperateOption operateOption = OperateOption.create();
                operateOption.setVariableValue("terreason", returnData.get("details").toString());
                this.getView().invokeOperation("terminate", operateOption);
                String successStr = ResManager.loadKDString("终止成功。", "BatchChangeGradeLevelList_3", "tdc-tjga-formplugin", new Object[0]);
                this.getView().showSuccessNotification(successStr);
                this.getView().invokeOperation("refresh");
            }
        }

    }

    private List<DynamicObject> opCheck() {
        String billStatus = this.getModel().getDataEntity().getString("billstatus");
        if ("A".equals(billStatus)) {
            return Lists.newArrayList(new DynamicObject[]{new DynamicObject()});
        } else {
            Long id = this.getModel().getDataEntity().getLong("id");
            List<DynamicObject> processingBills = (new BatchChangeGradeLevelFormService()).getProcessingBills(Lists.newArrayList(new Long[]{id}));
            if (HRCollUtil.isEmpty(processingBills)) {
                String listStr = ResManager.loadKDString("操作失败，当前单据状态已变更。", "BatchChangeGradeLevelEdit_10", "tdc-tjga-formplugin", new Object[0]);
                this.getView().showErrorNotification(listStr);
                this.getView().invokeOperation("refresh");
                return new ArrayList();
            } else {
                return processingBills;
            }
        }
    }

    public static List<Object> getCallBackSelectIds(ClosedCallBackEvent closedCallBackEvent) {
        ListSelectedRowCollection returnData = (ListSelectedRowCollection)closedCallBackEvent.getReturnData();
        if (returnData == null) {
            return new ArrayList();
        } else {
            List<Object> primaryIds = (List)returnData.stream().map(ListSelectedRow::getPrimaryKeyValue).collect(Collectors.toList());
            return primaryIds;
        }
    }

    public void beforeClosed(BeforeClosedEvent e) {
        super.beforeClosed(e);
        FormCommonService FORM_COMMON_SERVICE = new FormCommonService();
        FORM_COMMON_SERVICE.setPropertyNotDataChanged(this.getModel(), new String[]{"talentfile", "talentfileentry", "person", "employee", "startdate", "billnoentry"});
    }

    public void resetDateFilter(ResetDateFilterEvent resetDateFilterEvent) {
        int currentRow = this.getModel().getEntryCurrentRowIndex("changeentry");
        DynamicObject entryRowEntity = this.getModel().getEntryRowEntity("changeentry", currentRow);
        Date startDate = entryRowEntity.getDate("startdate");
        DateEdit changeeffdate = (DateEdit)this.getControl("changeeffdate");
        if (startDate != null) {
            changeeffdate.setMinDate(HRDateTimeUtils.addDay(startDate, 1L));
        } else {
            try {
                changeeffdate.setMinDate(HRDateTimeUtils.parseDate("1900-01-01", "yyyy-MM-dd"));
            } catch (ParseException var7) {
                var7.printStackTrace();
            }
        }

    }

    public void entryGridBindData(EntryGridBindDataEvent e) {
        this.setEntryEnable();
    }

    public Long getLatestJobIdByPersonId(Long personId) {
        QFilter filter = QFilterUtil.getCurrentQf();
        filter.and("isprimary", QCP.equals, "1");
        filter.and("person.id", QCP.equals, personId);
        filter.and("startdate", QCP.less_equals, new Date());
        filter.and("enddate", QCP.large_equals, new Date());
        DynamicObject dyn = QueryServiceHelper.queryOne("hrpi_empposorgrel", "job.id", new QFilter[]{filter});
        if(ObjectUtils.isEmpty(dyn)) {
            return 0L;
        }
        else {
            return dyn.getLong("job.id");
        }
    }

}
