package nckd.jimin.jyyy.hr.tsrsc.plugin.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.*;
import kd.bos.exception.KDBizException;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.importentry.resolving.ImportEntryData;
import kd.bos.list.ListShowParameter;
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.QueryServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.hr.hbp.business.openservicehelper.hrpi.HRPIPersonServiceHelper;
import kd.hr.hbp.common.model.org.staff.StaffResponse;
import nckd.jimin.jyyy.hr.hrmp.hbpm.opplugin.web.position.PositionUtils;
import nckd.jimin.jyyy.hr.tsrsc.plugin.util.RecUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

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

/**
 * Module           :人才供应云-招聘直通车-首页-临时招聘申请
 * Description      :临时招聘申请单据插件
 * @author Tyx
 * @date  2025/5/8
 * 标识 nckd_casrecrapply
 */



public class CasRecrApplyFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {

    private static Log logger = LogFactory.getLog(CasRecrApplyFormPlugin.class);

    // 公司类型
    private final List<String> COMPANY_LIST = Arrays.asList(new String[]{"1020_S","1050_S","1060_S","1070_S"});

    private final List<String> COMPANY_LIST2 = Arrays.asList(new String[]{"Orgform01","Orgform01-100","Orgform02","Orgform03"});

    // 定义日期格式
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final String SUBMIT = "submit";

    private static String OPPARAM_AFTERCONFIRM = "afterconfirm";



    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
//        DispatchServiceHelper.invokeService("kd.hrmp.haos.servicehelper","haos","IHAOSStaffService","queryUseStaffInfo",objects);
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        Object billstatus = this.getModel().getValue("billstatus");
        // 暂存状态才发生变化
        if(ObjectUtils.equals(billstatus,"A")){
            DynamicObject org = (DynamicObject) this.getModel().getValue("org");
            updateStaffCount();
            // 实际人数
            this.getModel().setValue("nckd_relnum", RecUtils.getStaffCount(org.getPkValue()));
        }
    }

    private void updateStaffCount(){

        DynamicObject org = (DynamicObject) this.getModel().getValue("org");
        //  组织id
        Long pkValue = (Long) org.getPkValue();
        List<Long> longs = new ArrayList<Long>();
        longs.add(pkValue);
        QFilter qFilter = new QFilter("boid", QCP.equals, pkValue);
        // 获取组织历史查询
        DynamicObjectCollection query = QueryServiceHelper.query("haos_adminorgdetail", "id,boid,hisversion", new QFilter[]{qFilter}, "hisversion desc");
        if(ObjectUtils.isNotEmpty(query)){
            long boid = query.get(0).getLong("id");
            // 获取填写的年度 nckd_year
            Object nckdYear =  this.getModel().getValue("nckd_year");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

            if(ObjectUtils.isEmpty(nckdYear)){
                nckdYear = new Date();
            }else{
                nckdYear = (Date) nckdYear;
            }
            String dateStr = sdf.format(nckdYear);
//            QFilter qFilter2 = new QFilter("staff.year", QCP.like, dateStr + "%");
            QFilter qFilter1 = new QFilter("dutyorg.id", QCP.equals, boid);

            DynamicObject[] haosDutyorgdetail = BusinessDataServiceHelper.load( "haos_dutyorgdetail","id,dutyorg,staff,staffcount",new QFilter[]{qFilter1},"staff.year desc");
            if(ObjectUtils.isNotEmpty(haosDutyorgdetail)){
                DynamicObject dynamicObject = haosDutyorgdetail[0];
                int staffcount = dynamicObject.getInt("staffcount");
                this.getModel().setValue("nckd_sftaffcount",staffcount);
                this.getModel().setValue("nckd_sftaff",dynamicObject.getLong("staff.id"));
//                for (DynamicObject dynamicObject : haosDutyorgdetail) {
//                    String format = sdf.format(dynamicObject.getDate("staff.year"));
//                    if(dateStr.equals(format)){
//                        int staffcount = dynamicObject.getInt("staffcount");
//                        this.getModel().setValue("nckd_sftaffcount",staffcount);
//                        return;
//                    }
//                }
            }
            this.getModel().setValue("nckd_sftaffcount",null);

//            int staffcount = ObjectUtils.isNotEmpty(haosDutyorgdetail) ? haosDutyorgdetail.getInt("staffcount"):null;
//            this.getModel().setValue("nckd_sftaffcount",staffcount);

        }

    }

    private List<String> getPostNumber(){
        DynamicObjectCollection entryentity = this.getModel().getDataEntity(true).getDynamicObjectCollection("entryentity");
        List<String> postNumber = new ArrayList<>();
        for (DynamicObject dynamicObject : entryentity) {
            if(ObjectUtils.isNotEmpty(dynamicObject.get("nckd_recruitpost"))){
                postNumber.add(dynamicObject.getString("nckd_recruitpost.number"));
            }
        }
        return postNumber;
    }

    @Override
    public void beforeImportEntry(BeforeImportEntryEventArgs e) {
        // 临时招聘 导入数据
//        super.beforeImportEntry(e);
        logger.info("临时招聘导入数据--------");
        QFilter qFilter = new QFilter("status", QCP.equals, "C")
                .and("enable", QCP.equals, "1")
                .and("iscurrentversion", QCP.equals, "1");
        Map<String, List<Object>> entryDataMap = e.getEntryDataMap();
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> postNumber = getPostNumber();
        DynamicObject nckdRecruitcompany = (DynamicObject)this.getModel().getValue("org");

        List<Long> longs = new ArrayList<Long>();
        Long pkValue = (Long) nckdRecruitcompany.getPkValue();
        longs.add(pkValue);
        List<Long> allSubordinateOrgIds = OrgUnitServiceHelper.getAllSubordinateOrgs("01", longs, true);
        Integer index = 0;
        try {
            String jsonString = objectMapper.writeValueAsString(entryDataMap);
            logger.info("jsonString:{}",jsonString);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonString);
            JSONArray entryentity = jsonObject.getJSONArray("entryentity");
            JSONObject jsonObject1 = entryentity.getJSONObject(0);
            index =jsonObject1.getInteger("rowIndex");
        } catch (JsonProcessingException ex) {
            throw new RuntimeException(ex);
        }


        Map<String, List<ImportEntryData>> source = (Map)e.getSource();
        Set<Map.Entry<String, List<ImportEntryData>>> entries = source.entrySet();
        Iterator var4 = entries.iterator();
        while (var4.hasNext()){
            Map.Entry<String, List<ImportEntryData>> entry = (Map.Entry)var4.next();
            String key = entry.getKey();
            logger.info("entryentity,key:{}",key);
            if("entryentity".equals(key)){
                List<ImportEntryData> entryValue = (List) entry.getValue();
                List<ImportEntryData> entryValue2 = entryValue;
                logger.info("获取到导入数据");
                logger.info("获取到导入数据.size:{}",entryValue2.size());
                if(entryValue2.size() > 0){
                    StringBuilder errorBuilder = new StringBuilder();
                    logger.info("分录数据不为空");
                    List<Object> listQuerOrg = new ArrayList<>();
                    List<Object> listQuerPost = new ArrayList<>();
                    String orgQuery = null;
                    String postQuery = null;
                    logger.info("开始构建查询条件");
                    for (int i = 0; i < entryValue2.size(); i++) {
                        // 部门
                        JSONObject nckdRecruitorg = entryValue2.get(i).getData().getJSONObject("nckd_recruitorg");
                        // 岗位
                        JSONObject nckdRecruitpost = entryValue2.get(i).getData().getJSONObject("nckd_recruitpost");

                        if(i == 0){
                            orgQuery = nckdRecruitorg.getString("importprop");
                            postQuery = nckdRecruitpost.getString("importprop");
                        }
                        listQuerOrg.add(nckdRecruitorg.get(orgQuery));
                        listQuerPost.add(nckdRecruitpost.get(postQuery));
                    }
                    logger.info("查询条件listQuerOrg:{},listQuerPost:{}",listQuerOrg,listQuerPost);
                    QFilter qFilterorg = new QFilter(orgQuery, QCP.in, listQuerOrg);
                    QFilter qFilterpost = new QFilter(postQuery, QCP.in, listQuerPost);
                    QFilter qFilterbelongcompany = new QFilter("belongcompany", QCP.in,allSubordinateOrgIds);
                    DynamicObject[] haosAdminorgf7s = BusinessDataServiceHelper.load("haos_adminorgf7", "id,name,number,status,enable,iscurrentversion", new QFilter[]{qFilter, qFilterorg,qFilterbelongcompany});
//                    logger.info("查询结果haosAdminorgf7s:{}",haosAdminorgf7s);
                    String finalOrgQuery = orgQuery;
                    Map<String, DynamicObject> map1 =
                            Arrays.stream(haosAdminorgf7s)
                                    .collect(Collectors.toMap(
                                            detail -> detail.get(finalOrgQuery).toString(),
                                            detail -> detail,
                                            (existing, replacement) -> existing // 保留前面的值
                                    ));

                    DynamicObject[] hbpmPositionhrs = BusinessDataServiceHelper.load("hbpm_positionhr", "id,name,number,status,enable,iscurrentversion", new QFilter[]{qFilter, qFilterpost});
//                    logger.info("查询结果hbpmPositionhrs:{}",hbpmPositionhrs);
                    String finalOrgQuery2 = postQuery;
                    Map<String, Object> map2 =
                            Arrays.stream(hbpmPositionhrs)
                                    .collect(Collectors.toMap(
                                            detail -> detail.get(finalOrgQuery2).toString(),
                                            detail -> detail.get("id"),
                                            (existing, replacement) -> existing // 保留前面的值
                                    ));

                    String finalPostQuery = postQuery;

                    for (int i = 0; i < entryValue.size(); i++) {
                        ImportEntryData importEntryData = entryValue.get(i);
                        int i1 = index + i;
                        logger.info("修改前importEntryData:{},jsondata:{}",importEntryData.getEntryName(),importEntryData.getData().toString());
                        // 部门
                        JSONObject nckdRecruitorg = importEntryData.getData().getJSONObject("nckd_recruitorg");
                        String imoportprop = nckdRecruitorg.getString("importprop");
                        Object o = nckdRecruitorg.get(imoportprop);
                        if(ObjectUtils.isNotEmpty(o)){
                            DynamicObject o1 = map1.get(o);
                            JSONObject jsonObject = new JSONObject();
                            if(ObjectUtils.isEmpty(o1)){
                                errorBuilder.append("第"+i1+"行"+"部门"+o+"在组织"+nckdRecruitcompany.getString("name")+"下未找到!" + "\n");
                            }else{
                                jsonObject.put("importprop","id");
                                jsonObject.put("id",o1.getPkValue());
                                importEntryData.getData().remove("nckd_recruitorg");
                                importEntryData.getData().put("nckd_recruitorg",jsonObject);
                                // 岗位
                                JSONObject nckdRecruitpost = importEntryData.getData().getJSONObject("nckd_recruitpost");
                                String imoportprop2 = nckdRecruitpost.getString("importprop");
                                Object o2 = nckdRecruitpost.get(imoportprop2);
                                if(ObjectUtils.isNotEmpty(o)){
                                    List<Long> longs2 = new ArrayList<Long>();
                                    longs2.add((Long) o1.getPkValue());
                                    List<Long> allSubordinateOrgIds2 = OrgUnitServiceHelper.getAllSubordinateOrgs("01", longs2, true);
                                    QFilter qFilter1 = new QFilter("adminorg.id", QCP.in, allSubordinateOrgIds2);
                                    QFilter qFilter2 = new QFilter(finalPostQuery, QCP.equals, o2);
                                    DynamicObject hbpmPositionhr = BusinessDataServiceHelper.loadSingle("hbpm_positionhr", "id,name,number,status,enable,iscurrentversion", new QFilter[]{qFilter, qFilterpost, qFilter1,qFilter2});
                                    if(ObjectUtils.isEmpty(hbpmPositionhr)){
                                        ((List)source.get("entryentity")).clear();
                                        errorBuilder.append("第"+i1+"行："+o2 +"岗位不存在！" + "\n");
                                    }else{
                                        if(postNumber.contains(hbpmPositionhr.getString("number"))){
                                            errorBuilder.append("第"+i1+"行："+o2 +"岗位重复！"+"\n");
                                        }else{
                                            postNumber.add(hbpmPositionhr.getString("number"));
                                            JSONObject jsonObject2 = new JSONObject();
                                            jsonObject2.put("importprop","id");
                                            jsonObject2.put("id",hbpmPositionhr.getPkValue());
                                            importEntryData.getData().remove("nckd_recruitpost");
                                            importEntryData.getData().put("nckd_recruitpost",jsonObject2);
                                        }
                                    }
                                }
                            }

                        }
                    }
                    if(ObjectUtils.isNotEmpty(errorBuilder)){
                        ((List)source.get("entryentity")).clear();
                        throw new KDBizException(errorBuilder.toString());
                    }
                }


            }

        }

    }

    @Override
    public void afterImportData(ImportDataEventArgs e) {
        super.afterImportData(e);
    }

    @Override
    public void loadData(LoadDataEventArgs e) {
        super.loadData(e);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String key = e.getProperty().getName();
        ChangeData[] changeData = e.getChangeSet();
        Object newValue = changeData[0].getNewValue();
        Object oldValue = changeData[0].getOldValue();
        int iRow = changeData[0].getRowIndex();
        switch (key) {
            case "nckd_year":
                updateStaffCount();
                break;
            case "nckd_recruitcompany":
                // 公司为空清除部门岗位
                if(!isNotEmpty(newValue)){
                    this.getModel().setValue("nckd_recruitorg", null,iRow);
                    this.getModel().setValue("nckd_recruitpost", null,iRow);
                }
                break;
            case "nckd_recruitorg":
                // 部门，判断是否存企业，如果不存在企业则将部门的所属公司带入到企业中
                // 修改部门，岗位置为null
                this.getModel().setValue("nckd_recruitpost", null,iRow);
                this.getModel().setValue("nckd_compilation", null,iRow);
                this.getModel().setValue("nckd_currentnum", null,iRow);
                this.getModel().setValue("nckd_majortype", null,iRow);
                this.getModel().setValue("nckd_education", null,iRow);
                this.getModel().setValue("nckd_payrangemin", null,iRow);
                this.getModel().setValue("nckd_payrange", null,iRow);
                this.getModel().setValue("nckd_employcategory", null,iRow);
                this.getModel().setValue("nckd_recruittype", null,iRow);
                this.getModel().setValue("nckd_employmentreasons", null,iRow);
                this.getModel().setValue("nckd_approvednum", null,iRow);
                this.getModel().setValue("nckd_recruitnum", 0,iRow);
                break;
            case "nckd_recruitpost":
                // 岗位，判断是否存企业，如果不存在企业则将部门的所属公司带入到企业中
                if(isNotEmpty(newValue)){
                    DynamicObject newValue1 = (DynamicObject) newValue;
                    // 校验是否有相同岗位
                    if(!checkPosition(newValue1,iRow)){
                        this.getView().showErrorNotification("已录入相同岗位！"+newValue1.getString("name")+newValue1.getString("number"));
                        this.getModel().setValue("nckd_recruitpost", null,iRow);
                        return;
                    }
                    // 获取行政组织，和行政组织的所属公司
                    // 行政组织
                    DynamicObject nckdRecruitcompany = (DynamicObject)this.getModel().getValue("nckd_recruitorg", iRow);
                    if(ObjectUtils.isEmpty(nckdRecruitcompany)){
                        DynamicObject adminorg = newValue1.getDynamicObject("adminorg");
                        DynamicObjectCollection entryentity = this.getModel().getDataEntity().getDynamicObjectCollection("entryentity");
                        for (DynamicObject object : entryentity) {
                            if(newValue1.getString("number").equals(object.getString("nckd_recruitpost.number"))){
                                object.set("nckd_recruitorg",adminorg);
                                break;
                            }
                        }
                    }
                    this.getModel().setValue("nckd_compilation",getFieldValue(newValue1),iRow);
                    long id = newValue1.getLong("id");
                    List<Long> longs = new ArrayList<Long>();
                    longs.add(id);
                    Map<Long, Set<Long>> allUsersOfPosition = HRPIPersonServiceHelper.getAllUsersOfPosition("1010_S", longs);
                    int num = 0;
                    if(ObjectUtils.isNotEmpty(allUsersOfPosition)){
                        Set<Long> longSet = allUsersOfPosition.get(id);
                        List<String> zaizhiStatus = Arrays.asList(new String[]{"1020_S","1010_S","1190_S","1050_S","1140_S","1060_S","1120_S","1210_S"});
                        QFilter qFilter = new QFilter("person.id", QCP.in, longSet)
                                .and("iscurrentversion",QCP.equals,"1")
                                .and("businessstatus",QCP.equals,"1")
                                .and("labrelstatusprd.number",QCP.in,zaizhiStatus);

                        DynamicObject[] hrpiEmpentrels = BusinessDataServiceHelper.load("hrpi_empentrel", "id,person", qFilter.toArray());
                        num = hrpiEmpentrels.length;
                    }
                    this.getModel().setValue("nckd_currentnum",num,iRow);
                }else{
                    this.getModel().setValue("nckd_compilation",null,iRow);
                    this.getModel().setValue("nckd_currentnum",null,iRow);
                }
                this.getModel().setValue("nckd_recruitnum",0,iRow);
                this.getView().updateView("entryentity");
                break;
            case "nckd_recruitnum":
                // 人数字段统计
                setSumRecruitnum(newValue,iRow);
                checkRecruitnum(newValue,iRow);
                break;
            case "nckd_payrangemin":
                changePayrangemin(newValue,oldValue,iRow);
                break;
            case "nckd_payrange":
                changepayrange(newValue,oldValue,iRow);
                break;
            default:
                break;
        }

    }

    // 校验岗位人数是否超编制
    private void checkRecruitnum(Object recruitnum,int row) {
        if(recruitnum instanceof Integer){
            // 获取编制人数
            Object nckdCompilation = this.getModel().getValue("nckd_compilation",row);
            if(ObjectUtils.isNotEmpty(nckdCompilation)){
                Integer integer =  (Integer)nckdCompilation;
                Integer nckdCurrentnum = (Integer)this.getModel().getValue("nckd_currentnum", row);
                Integer recruitnum1 =  (Integer)recruitnum;
                if (integer < (nckdCurrentnum + recruitnum1)){
                    this.getView().showErrorNotification("最高薪资不能低于最低薪资！");
                }
            }
        }
    }

    // 校验分录的最高薪资和最低薪资大小关系
    private String vaildatorPayrange(){
        DynamicObjectCollection entryentity = this.getModel().getDataEntity(true).getDynamicObjectCollection("entryentity");
        StringBuilder errorBuilder = new StringBuilder();
        for (DynamicObject object : entryentity) {
            int nckdPayrange = object.getInt("nckd_payrange");
            int nckdPayrangemin = object.getInt("nckd_payrangemin");
            if(nckdPayrange < nckdPayrangemin){
                errorBuilder.append(object.get("seq"));
            }
        }
        if(ObjectUtils.isNotEmpty(errorBuilder)){
            errorBuilder.append("行,最高薪资不能低于最低薪资！");
        }
        return errorBuilder.toString();

    }

    private void changePayrangemin(Object newValue,Object oldValue,int row){
        if(newValue instanceof Integer){
            // 最大值
            Integer nckdPayrange = (Integer)this.getModel().getValue("nckd_payrange",row);
            if(nckdPayrange > 0) {
                int comparisonResult = nckdPayrange.compareTo((Integer) newValue);
                if (comparisonResult < 0) {
                    this.getView().showErrorNotification("最高薪资不能低于最低薪资！");
                    this.getModel().setValue("nckd_payrangemin", oldValue, row);
                }
            }
        }
    }
    private void changepayrange(Object newValue,Object oldValue,int row){
        if(newValue instanceof Integer){
            // 最大值
            Integer nckdPayrange = (Integer)this.getModel().getValue("nckd_payrangemin",row);
            int comparisonResult = ((Integer) newValue).compareTo( (Integer) nckdPayrange);
            if(comparisonResult < 0){
                this.getView().showErrorNotification("最高薪资不能低于最低薪资！");
                this.getModel().setValue("nckd_payrange",oldValue,row);
            }
        }
    }

    private boolean checkPosition(DynamicObject  newValue,int row) {
        DynamicObjectCollection entryentity = this.getModel().getDataEntity(true).getDynamicObjectCollection("entryentity");
        for (int i = 0; i < entryentity.size(); i++) {
            if(row == i){
                break;
            }
            if(ObjectUtils.isNotEmpty(entryentity.get(i).get("nckd_recruitpost"))){
                if(entryentity.get(i).get("nckd_recruitpost.number").equals(newValue.get("number"))){
                    return false;
                }
            }
        }

        return true;
    }

    // 公司，部门，岗位选择过滤
    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String fieldKey = e.getProperty().getName();
        switch (fieldKey){
            case "nckd_recruitcompany":
                // 企业名称
                ListShowParameter showParameter = (ListShowParameter)e.getFormShowParameter();
                //是否展示审核的改为false
                QFilter qFilter = new QFilter("adminorgtype.number", "in", COMPANY_LIST);
                showParameter.getListFilterParameter().setFilter(qFilter);
                break;
            case "nckd_recruitorg":
                // 组织名称
                ListShowParameter showParameter2 = (ListShowParameter)e.getFormShowParameter();
                // 展示部门，如果选择了企业，展示企业下的部门，添加企业筛选条件
                DynamicObject nckdRecruitcompany = (DynamicObject)this.getModel().getValue("org");

                List<Long> longs = new ArrayList<Long>();
                Long pkValue = (Long) nckdRecruitcompany.getPkValue();
                longs.add(pkValue);
                List<Long> allSubordinateOrgIds = OrgUnitServiceHelper.getAllSubordinateOrgs("01", longs, true);
                // 使用流处理过滤掉指定的值
//                List<Long> filteredOrgIds = allSubordinateOrgIds.stream()
//                        .filter(orgId -> !orgId.equals(pkValue)) // 过滤掉值
//                        .collect(Collectors.toList());

                // 获取组织编码
//                QFilter belongcompanyFilter = new QFilter("belongcompany", "in", allSubordinateOrgIds);
                QFilter qFilter2 = new QFilter("belongcompany", QCP.in,allSubordinateOrgIds);
                showParameter2.getListFilterParameter().setFilter(qFilter2);

                break;
            case "nckd_recruitpost":
                // 岗位名称
                ListShowParameter showParameter3 = (ListShowParameter)e.getFormShowParameter();
                // 展示部门，如果选择了企业，展示企业下的部门
                EntryGrid treeEntryEntity2 = this.getControl("entryentity");
                int[] rows2 = treeEntryEntity2.getSelectRows();
                DynamicObject nckdRecruitcompany2 = (DynamicObject)this.getModel().getValue("org");
                DynamicObject nckdRecruitorg = (DynamicObject)this.getModel().getValue("nckd_recruitorg", rows2[0]);
                List<Long> longs2 = new ArrayList<Long>();
                longs2.add((Long)nckdRecruitcompany2.getPkValue());
                List<Long> allSubordinateOrgIds2 = OrgUnitServiceHelper.getAllSubordinateOrgs("01", longs2, true);
                QFilter qFilter1 = new QFilter("adminorg.id", QCP.in, allSubordinateOrgIds2);
                if(ObjectUtils.isNotEmpty(nckdRecruitorg)){
                    qFilter1.and("adminorg.id", QCP.equals, nckdRecruitorg.getPkValue());
                }
                showParameter3.getListFilterParameter().setFilter(qFilter1);
                break;
            case "org":
                ListShowParameter showParameter4 = (ListShowParameter)e.getFormShowParameter();
                // 去除部门
                QFilter qFilter4 = new QFilter("orgpattern.number", "in", COMPANY_LIST2);
                showParameter4.getListFilterParameter().setFilter(qFilter4);
                break;
            default:
                break;
        }
    }


    // 获取岗位对应编制人数
    public Object getFieldValue(DynamicObject nckd_recruitpost) {
        Object num = null;
        if(ObjectUtils.isNotEmpty(nckd_recruitpost)){
            //Tyx 2025-09-19 改成直接按照岗位获取编制数
            List<Long> ids = new ArrayList<Long>();
            ids.add(nckd_recruitpost.getLong("id"));
            StaffResponse staffResponse = PositionUtils.getStaffByPosition(ids);
            if(staffResponse.isSuccess()) {
                Map data = (Map) staffResponse.getData();
                if(data.keySet().contains(ids.get(0).toString())) {
                    Map staffMap = (Map) data.get(ids.get(0).toString());
                    num = staffMap.get("staffNum");
                }
            }
//            DynamicObject haosStaff = null;
//            if(ObjectUtils.isNotEmpty(nckdSftaff)){
//                haosStaff = BusinessDataServiceHelper.loadSingle(nckdSftaff,"haos_staff");
//            }else{
//                QFilter qFilter = new QFilter("enable", QCP.equals, "1");
//                DynamicObject[] haosStaffs = BusinessDataServiceHelper.load("haos_staff", "id,name,number", new QFilter[]{qFilter},"year desc");
//                if (haosStaffs != null && haosStaffs.length > 0) {
//                    haosStaff = haosStaffs[0];
//                } else {
//                    return null;
//                }
//                this.getModel().setValue("nckd_sftaff",haosStaff.getPkValue());
//            }
//
//            Object pkValue = nckd_recruitpost.get("id");
//            QFilter qFilter3 = new QFilter("staff.id", QCP.equals, haosStaff.getPkValue())
//                    .and("enable", QCP.not_equals, "0")
//                    .and("datastatus",QCP.not_equals,"-2")
//                    .and("datastatus",QCP.not_equals,"2")
//                    .and("datastatus",QCP.not_equals,"-1")
//                    .and("dutyworkrole.boid",QCP.equals,pkValue);
//            DynamicObject[] haosDutyorgdetails = BusinessDataServiceHelper.load("haos_muldimendetail", "id,staff,dutyworkrole,dutyworkrole.boid,yearstaff", new QFilter[]{qFilter3});
//            if(haosDutyorgdetails.length > 0) {
//                num = haosDutyorgdetails[0].get("yearstaff");
//            }
        }
        return num;
    }


    @Override
    public void registerListener(EventObject e) {
        BasedataEdit fieldEdit = (BasedataEdit) this.getView().getControl("nckd_recruitcompany");
        BasedataEdit fieldEdit2 = (BasedataEdit) this.getView().getControl("nckd_recruitorg");
        BasedataEdit fieldEdit3 = (BasedataEdit) this.getView().getControl("nckd_recruitpost");
        BasedataEdit fieldEdit4 = this.getView().getControl("org");
        fieldEdit.addBeforeF7SelectListener(this);
        fieldEdit.addBeforeF7SelectListener(this);
        fieldEdit2.addBeforeF7SelectListener(this);
        fieldEdit3.addBeforeF7SelectListener(this);
        fieldEdit4.addBeforeF7SelectListener(this);
    }


    public static boolean isNotEmpty(Object  key) {
        // 基础资料判空
        if(ObjectUtils.isEmpty(key) || ObjectUtils.isEmpty(((DynamicObject)key).getDataStorage())){
            return false;
        }
        return true;
    }


    public void setSumRecruitnum(Object newValue,int row){
        // 计算招聘人数,获取出所有分录，然后统计所有分录的招聘人数累加
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("entryentity");
        int num = 0;
        for (int i = 0; i < entryEntity.size(); i++) {
            if(row == i){
                num = num + (Integer) newValue;
            }else{
                num = num + (Integer) entryEntity.get(i).get("nckd_recruitnum");
            }
        }
        this.getModel().setValue("nckd_applynum", num);
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate opreate = (FormOperate) args.getSource();
        switch (opreate.getOperateKey()) {
            case "submit":
                String errorMessage = vaildatorPayrange();
                if(StringUtils.isNotEmpty(errorMessage)){
                    this.getView().showErrorNotification(errorMessage);
                    args.setCancel(true);
                    return;
                }
                // 在此添加处理逻辑
                Object nckdSftaffcount1 = this.getModel().getValue("nckd_sftaffcount");
                if(ObjectUtils.isNotEmpty(nckdSftaffcount1)){
                    int nckdSftaffcount = (int) this.getModel().getValue("nckd_sftaffcount");
                    // 实际人数
                    int nckdRelnum = (int) this.getModel().getValue("nckd_relnum");
                    // 申请人数
                    int nckdApplynum = (int) this.getModel().getValue("nckd_applynum");
                    if(nckdApplynum > 0){
                        if(nckdSftaffcount < nckdRelnum + nckdApplynum){
                            // 判断是否处理过
                            String isDealed = this.getView().getPageCache().get("isDealed");
                            if (!"true".equals(isDealed)) {
                                // 取消原来的操作
                                args.setCancel(true);
                                // 在用户点击确认框上的按钮后，系统会调用confirmCallBack方法
                                ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("isExceed", this);
                                // 设置页面确认框，参数为：标题，选项框类型，回调监听
                                this.getView().showConfirm("请注意，申请人数超编，是否继续提报？", MessageBoxOptions.YesNo, confirmCallBackListener);
                                // 只执行一次
                                this.getView().getPageCache().put("isDealed", "true");
                            }
                        }
                    }

                }

                break;
            case "save":
                String errorMessage2 = vaildatorPayrange();
                if(StringUtils.isNotEmpty(errorMessage2)){
                    this.getView().showErrorNotification(errorMessage2);
                    args.setCancel(true);
                    return;
                }
            default:
                break;
        }
    }





    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        this.getView().getPageCache().remove("isDealed");
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        //判断回调参数id
        if ("isExceed".equals(messageBoxClosedEvent.getCallBackId())) {
            if (MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
                this.getView().invokeOperation("submit");
            } else if (MessageBoxResult.No.equals(messageBoxClosedEvent.getResult())) {
                // 点击否也清除
                this.getView().getPageCache().remove("isDealed");
            }
        }
    }



}
