package nckd.jxccl.swc.init.business;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.param.CustomParam;
import kd.bos.ext.fi.bei.util.EmptyUtil;
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.operation.SaveServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.swc.helper.SWCHelper;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 员工待定调薪清单
 * 同步入职与调动单数据
 * hom_personhasonbrd  入职单
 * hdm_transferapply   调动申请
 * @author turborao
 * @date 2025/11/28
 */
public class SynPendingSalaryAdjDataServiceImpl implements SynPendingSalaryAdjDataService {

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

    private static int days = 5;

    private DynamicObjectCollection salaryTypeDyns = null;
    private DynamicObject salaryRankDyn = null;
    private DynamicObject standardItemDyn = null;

    @Override
    public String SynPendingSalaryAdjDataForPersonTransfer() {
        /**
         * 初始化数据
         */
        initialize();

        String msg = getAdjustBillData();

        return msg;
    }

    public void initialize() {
        /**
         * 获取 公共自定义参数  PENDSALARYADJ_DAYS
         */
        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add("PENDSALARYADJ_DAYS");
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        String pendsalaryadjDays  = cusTomMap.get("PENDSALARYADJ_DAYS");
        days = Integer.parseInt(pendsalaryadjDays);

        /**
         * 获取 定调薪类型
         */
        salaryTypeDyns = SWCHelper.getSalaryTypeDyns();

        /**
         * 获取入职时的薪档
         */
        QFilter qFilter12 = new QFilter("number", QCP.equals, "01");
        salaryRankDyn = QueryServiceHelper.queryOne(FormConstant.HSBS_SALARYRANK,"id,number,name",new QFilter[]{qFilter12});

        /**
         * 获取 定调薪项目 岗位工资标准
         */
        QFilter qFilter13 = new QFilter("name", QCP.equals, "岗位工资标准");
        standardItemDyn = QueryServiceHelper.queryOne(FormConstant.HSBS_STANDARDITEM,"id,number,name",new QFilter[]{qFilter13});
    }


    /**
     * 获取入职单与调动单的数据
     */
    public String getAdjustBillData() {

        LocalDate currentDate = LocalDate.now();
        // Subtract 5 days
        LocalDate daysAgo = currentDate.minusDays(days);

        ArrayList<DynamicObject> billDynList = new ArrayList<>();
        StringBuffer errorInfo = new StringBuffer();
        MainEntityType entityType = EntityMetadataCache.getDataEntityType(FormConstant.NCKD_PENDINGSALARYADJ);

        /**
         * 查询入职单
         */
        String selectField2 = "id,billno,b_effectivedate,createtime,ba_em_tid,ba_em_empnumber,ba_em_name,ba_po_position.boid,ba_po_adminorg,ba_po_adminorg.belongcompany.id,ba_po_position.nckd_paystdplan.name";
        QFilter qFilter1 = new QFilter("enrollstatus", QCP.equals, "3"); // 入职状态 = 已入职
        QFilter qFilter2 = new QFilter("billstatus", QCP.equals, "C"); // 单据状态 = 已审核
        QFilter qFilter3 = new QFilter("b_effectivedate", QCP.large_equals, daysAgo);
        QFilter qFilter4 = new QFilter("b_effectivedate", QCP.less_equals, currentDate);
        QFilter qFilter5 = new QFilter("ba_po_position.nckd_paystdplan.name", QCP.equals, "江铜集团岗位绩效工资制");

        DynamicObjectCollection onhasonbrdDyns = QueryServiceHelper.query(FormConstant.HOM_PERSONHASONBRD, selectField2,new QFilter[]{qFilter1,qFilter2,qFilter3,qFilter4,qFilter5});

        Map<Long, DynamicObject> onhasonbrdMap = (Map)onhasonbrdDyns.stream().collect(Collectors.toMap((obj) -> {
            return obj.getLong("id");
        }, (obj) -> {
            return obj;
        }, (k1, k2) -> {
            return k1;
        }));

        //入职  将Map转换为List
        List<Long> onhasonbrdIDs = onhasonbrdMap.keySet().stream().collect(Collectors.toList());

        QFilter qFilter22 = new QFilter("nckd_billid", QCP.in, onhasonbrdIDs);
        List<Object> listIDs = QueryServiceHelper.queryPrimaryKeys(FormConstant.NCKD_PENDINGSALARYADJ,new QFilter[]{qFilter22}, null, Integer.MAX_VALUE);
        DynamicObject billDynType =  BusinessDataServiceHelper.newDynamicObject(FormConstant.NCKD_PENDINGSALARYADJ);
        DynamicObject[] billDyns = BusinessDataServiceHelper.load(listIDs.toArray(),billDynType.getDynamicObjectType());

        int onhasonbrdCount = 0;
        Map<Long, DynamicObject> billMap =
                Arrays.stream(billDyns)
                        .collect(Collectors.toMap(
                                detail -> detail.getLong("nckd_billid"),
                                detail -> detail, // 整个 DynamicObject 作为 value
                                (existing, replacement) -> existing // 保留前面的值
                        ));


        for(DynamicObject onhasonbrdDyn: onhasonbrdDyns){
            DynamicObject billDyn1 = billMap.get(onhasonbrdDyn.getLong("id"));
            if(billDyn1 != null) {
                continue;
            }
            DynamicObject dyn = new DynamicObject(entityType);
            dyn.set("billno", onhasonbrdDyn.getString("billno"));
            dyn.set("nckd_billid", onhasonbrdDyn.getLong("id"));
            dyn.set("nckd_billtype", "入职单");
            dyn.set("billstatus", "A");  ///待处理
            dyn.set("nckd_employeefield", onhasonbrdDyn.getLong("ba_em_tid"));
            dyn.set("nckd_hrorg", onhasonbrdDyn.getLong("ba_po_adminorg.belongcompany.id"));  //薪酬管理组织 来源  调后部门中的公司
            dyn.set("nckd_changedate", onhasonbrdDyn.getDate("b_effectivedate"));
            dyn.set("nckd_dodatetime", onhasonbrdDyn.getDate("createtime"));
            dyn.set("nckd_salaryadjus", salaryTypeDyns.get(0).getLong("id"));  //定调薪类型
            dyn.set("nckd_newhradminorg", onhasonbrdDyn.getLong("ba_po_adminorg"));  //部门
            dyn.set("nckd_newposition", onhasonbrdDyn.getLong("ba_po_position.boid"));  //岗位
            dyn.set("nckd_newsalaryrank", salaryRankDyn.getLong("id"));
            onhasonbrdCount++;
            billDynList.add(dyn);
        }


        /**
         * 查询调动单
         */
        String selectField1 = "id,billno,b_effectivedate,createtime,bb_em_tid,ba_em_empnumber,bb_po_position.boid,aposition.boid,bb_po_adminorg.boid,aorg.boid,aorg.belongcompany.id";
        QFilter qFilter12 = new QFilter("billstatus", QCP.equals, "C"); // 单据状态 = 已审核
        QFilter qFilter17 = new QFilter("perchgstatus", QCP.like, "%99%");   //同步成功
        QFilter qFilter13 = new QFilter("b_effectivedate", QCP.large_equals, daysAgo);  //实际调动日期
        QFilter qFilter14 = new QFilter("b_effectivedate", QCP.less_equals, currentDate);  //实际调动日期
        QFilter qFilter16 = new QFilter("aposition.nckd_paystdplan.name", QCP.equals, "江铜集团岗位绩效工资制");

        DynamicObjectCollection transferDyns = QueryServiceHelper.query(FormConstant.HDM_TRANSFERAPPLY, selectField1,new QFilter[]{qFilter12,qFilter13,qFilter14,qFilter17,qFilter16});

        Map<Long, DynamicObject> transferMap = (Map)transferDyns.stream().collect(Collectors.toMap((obj) -> {
            return obj.getLong("id");
        }, (obj) -> {
            return obj;
        }, (k1, k2) -> {
            return k1;
        }));
        List<Long> transferIDs = transferMap.keySet().stream().collect(Collectors.toList());

        QFilter qFilter15 = new QFilter("nckd_billid", QCP.in, transferIDs);
        List<Object> transferlistIDs = QueryServiceHelper.queryPrimaryKeys(FormConstant.NCKD_PENDINGSALARYADJ,new QFilter[]{qFilter15}, null, Integer.MAX_VALUE);
        DynamicObject[] billDyns1 = BusinessDataServiceHelper.load(transferlistIDs.toArray(),billDynType.getDynamicObjectType());

        int transferCount = 0;
        Map<Long, DynamicObject> billMap1 =
                Arrays.stream(billDyns1)
                        .collect(Collectors.toMap(
                                detail -> detail.getLong("nckd_billid"),
                                detail -> detail, // 整个 DynamicObject 作为 value
                                (existing, replacement) -> existing // 保留前面的值
                        ));

        Map<Long, DynamicObject> adjRecordMap = getAdjRecordInfo(transferDyns);

        for(DynamicObject transferDyn: transferDyns){
            DynamicObject billDyn2 = billMap1.get(transferDyn.getLong("id"));
            if(billDyn2 != null) {
                continue;
            }
            DynamicObject dyn = new DynamicObject(entityType);
            Long employeeID = transferDyn.getLong("bb_em_tid");
            dyn.set("billno", transferDyn.getString("billno"));
            dyn.set("nckd_billid", transferDyn.getLong("id"));
            dyn.set("nckd_billtype", "调动单");
            dyn.set("billstatus", "A");  ///待处理
            dyn.set("nckd_employeefield", employeeID);
            dyn.set("nckd_hrorg", transferDyn.getLong("aorg.belongcompany.id"));  //薪酬管理组织 来源  调后部门中的公司
            dyn.set("nckd_changedate", transferDyn.getDate("b_effectivedate"));
            dyn.set("nckd_dodatetime", transferDyn.getDate("createtime"));
            dyn.set("nckd_salaryadjus", salaryTypeDyns.get(1).getLong("id"));  //定调薪类型
            /**
             * 调动前
             */
            dyn.set("nckd_oldhradminorg", transferDyn.getLong("bb_po_adminorg.boid"));  //部门
            dyn.set("nckd_oldposition", transferDyn.getLong("bb_po_position.boid"));  //岗位
            DynamicObject adjRecordDyn  = adjRecordMap.get(employeeID);
            if(adjRecordDyn != null) {
                dyn.set("nckd_oldsalaryrank", adjRecordDyn.getLong("salaryrank.id"));  //薪档
            }
            /**
             * 调动后
             */
            dyn.set("nckd_newhradminorg", transferDyn.getLong("aorg.boid"));  //部门
            dyn.set("nckd_newposition", transferDyn.getLong("aposition.boid"));  //岗位
            //判断薪档是否改变
            boolean isChange = calaSararyRank(transferDyn.getLong("bb_po_position.boid"), transferDyn.getLong("aposition.boid"));
            if(isChange) {
                dyn.set("nckd_newsalaryrank", salaryRankDyn.getLong("id"));   //薪档
            }else{
                if(adjRecordDyn != null) {
                    dyn.set("nckd_newsalaryrank", adjRecordDyn.getLong("salaryrank.id"));
                }
            }

            transferCount++;
            billDynList.add(dyn);
        }


        /**
         * 批量调动
         */
        String selectField3 = "id,entryentity.id,billno,entryentity.b_effectivedate,createtime,entryentity.bb_em_tid as bb_em_tid,entryentity.ba_em_empnumber,entryentity.bb_po_position.boid,entryentity.aposition.boid,entryentity.bb_po_adminorg.boid,entryentity.aorg.boid,entryentity.aorg.belongcompany.id";
        QFilter qFilter31 = new QFilter("billstatus", QCP.equals, "C");
        QFilter qFilter32 = new QFilter("entryentity.transfereffectstatus", QCP.equals, "2");  //同步结果 =  同步成功
        QFilter qFilter33 = new QFilter("entryentity.b_effectivedate", QCP.large_equals, daysAgo);
        QFilter qFilter34 = new QFilter("entryentity.b_effectivedate", QCP.less_equals, currentDate);
        QFilter qFilter35 = new QFilter("entryentity.aposition.nckd_paystdplan.name", QCP.equals, "江铜集团岗位绩效工资制");
        DynamicObjectCollection transferBatchDyns = QueryServiceHelper.query(FormConstant.HDM_TRANSFERBATCH, selectField3,new QFilter[]{qFilter31,qFilter32,qFilter33,qFilter34,qFilter35});

        Map<Long, DynamicObject> transferBatchMap = (Map)transferBatchDyns.stream().collect(Collectors.toMap((obj) -> {
            return obj.getLong("entryentity.id");
        }, (obj) -> {
            return obj;
        }, (k1, k2) -> {
            return k1;
        }));
        List<Long> transferBatchIDs = transferBatchMap.keySet().stream().collect(Collectors.toList());

        QFilter qFilter38 = new QFilter("nckd_billid", QCP.in, transferBatchIDs);
        List<Object> transferBatchlistIDs = QueryServiceHelper.queryPrimaryKeys(FormConstant.NCKD_PENDINGSALARYADJ,new QFilter[]{qFilter38}, null, Integer.MAX_VALUE);
        DynamicObject[] billDyns3 = BusinessDataServiceHelper.load(transferBatchlistIDs.toArray(),billDynType.getDynamicObjectType());

        int transferBatchCount = 0;
        Map<Long, DynamicObject> billMap3 =
                Arrays.stream(billDyns3)
                        .collect(Collectors.toMap(
                                detail -> detail.getLong("nckd_billid"),
                                detail -> detail, // 整个 DynamicObject 作为 value
                                (existing, replacement) -> existing // 保留前面的值
                        ));

        Map<Long, DynamicObject> adjRecordMap3 = getAdjRecordInfo(transferBatchDyns);

        for(DynamicObject transferDyn: transferBatchDyns) {
            DynamicObject billDyn3 = billMap3.get(transferDyn.getLong("entryentity.id"));

            if(billDyn3 != null) {
                continue;
            }
            DynamicObject dyn = new DynamicObject(entityType);
            Long employeeID = transferDyn.getLong("bb_em_tid");
            dyn.set("billno", transferDyn.getString("billno"));
            dyn.set("nckd_billid", transferDyn.getLong("entryentity.id"));
            dyn.set("nckd_billtype", "调动单");
            dyn.set("billstatus", "A");  ///待处理
            dyn.set("nckd_employeefield", employeeID);
            dyn.set("nckd_hrorg", transferDyn.getLong("entryentity.aorg.belongcompany.id"));  //薪酬管理组织 来源  调后部门中的公司
            dyn.set("nckd_changedate", transferDyn.getDate("entryentity.b_effectivedate"));
            dyn.set("nckd_dodatetime", transferDyn.getDate("createtime"));
            dyn.set("nckd_salaryadjus", salaryTypeDyns.get(1).getLong("id"));  //定调薪类型
            /**
             * 调动前
             */
            dyn.set("nckd_oldhradminorg", transferDyn.getLong("entryentity.bb_po_adminorg.boid"));  //部门
            dyn.set("nckd_oldposition", transferDyn.getLong("entryentity.bb_po_position.boid"));  //岗位
            DynamicObject adjRecordDyn  = adjRecordMap3.get(employeeID);
            if(adjRecordDyn != null) {
                dyn.set("nckd_oldsalaryrank", adjRecordDyn.getLong("salaryrank.id"));  //薪档
            }
            /**
             * 调动后
             */
            dyn.set("nckd_newhradminorg", transferDyn.getLong("entryentity.aorg.boid"));  //部门
            dyn.set("nckd_newposition", transferDyn.getLong("entryentity.aposition.boid"));  //岗位
            //判断薪档是否改变
            boolean isChange = calaSararyRank(transferDyn.getLong("entryentity.bb_po_position.boid"), transferDyn.getLong("entryentity.aposition.boid"));
            if(isChange) {
                dyn.set("nckd_newsalaryrank", salaryRankDyn.getLong("id"));   //薪档
            }else{
                if(adjRecordDyn != null) {
                    dyn.set("nckd_newsalaryrank", adjRecordDyn.getLong("salaryrank.id"));
                }
            }

            transferBatchCount++;
            billDynList.add(dyn);

        }



        int length = 0;
        if(billDynList.size() != 0) {
            //保存
            Object[] update = SaveServiceHelper.save(billDynList.toArray(new DynamicObject[0]));
            length = update.length;
            errorInfo.append("成功导入，"+length+"条数据，其中入职单"+onhasonbrdCount+"条，调动单"+transferCount+transferBatchCount+"条"); // 成功类型
        }else{
            errorInfo.append("没有导入数据");
        }
        return errorInfo.toString();

    }

    /**
     * 获取调薪记录
     * @param transferDyns   通过调动单查询出人员ID
     * @return
     */
    public Map<Long, DynamicObject> getAdjRecordInfo(DynamicObjectCollection transferDyns) {
        Map<Long, DynamicObject> transferMap = (Map)transferDyns.stream().collect(Collectors.toMap((obj) -> {
            return obj.getLong("bb_em_tid");
        }, (obj) -> {
            return obj;
        }, (k1, k2) -> {
            return k1;
        }));

        List<Long> personIDs = transferMap.keySet().stream().collect(Collectors.toList());

        String selectField = "id,adjfile.employee.id,adjfile.datastatus,adjfile.iscurrentversion,employee.id,salaryrank.id";
        QFilter qFilter1 = new QFilter("adjfile.employee.id", QCP.in, personIDs);
        QFilter qFilter2 = new QFilter("adjfile.datastatus", QCP.equals, "1");
        QFilter qFilter3 = new QFilter("adjfile.iscurrentversion", QCP.equals, "1");
        QFilter qFilter4= new QFilter("salaryrank.id", QCP.equals, standardItemDyn.getLong("id"));
        QFilter qFilter5= new QFilter("iscurrentdata", QCP.equals, "1");

        DynamicObjectCollection adjDyns = QueryServiceHelper.query(FormConstant.HCDM_DECADJRECORD, selectField,new QFilter[]{qFilter1,qFilter2,qFilter3,qFilter4,qFilter5});


        Map<Long, DynamicObject> adjRecordMap = (Map)adjDyns.stream().collect(Collectors.toMap((obj) -> {
            return obj.getLong("employee.id");
        }, (obj) -> {
            return obj;
        }, (k1, k2) -> {
            return k1;
        }));

        return adjRecordMap;
    }

    /**
     * 岗位上字段
     * 岗级	管理层级	职位序列	输出
     * 变	不变	不变	岗级变，保留原档次
     * 不变	变	不变	×
     * 不变	不变	变	岗级和档次都不变
     * 变	不变	变	岗级变，保留原档次
     * 变	变	不变	岗级变，档次默认为1档
     * 不变	变	变	×
     * 变	变	变	岗级变，档次默认为1档
     * @param oldPosition
     * @param newPosition
     * @return
     */

    public boolean calaSararyRank(Long oldPosition, Long newPosition) {

        if(oldPosition != null || newPosition != null) {
            String selectField = "id,number,name,nckd_postgrade.id,nckd_mgtlvldtl.nckd_mgmtlevel.id";
            QFilter qFilter = new QFilter("id", QCP.equals, oldPosition);
            DynamicObject oldPositionDyn = QueryServiceHelper.queryOne(FormConstant.HBPM_POSITIONHR, selectField, new QFilter[]{qFilter});

            String selectField1 = "id,number,name,nckd_postgrade.id,nckd_mgtlvldtl.nckd_mgmtlevel.id";
            QFilter qFilter1 = new QFilter("id", QCP.equals, newPosition);
            DynamicObject newPositionDyn = QueryServiceHelper.queryOne(FormConstant.HBPM_POSITIONHR, selectField1, new QFilter[]{qFilter1});
            //岗级
            Long oldPostGrade = EmptyUtil.isEmpty(oldPositionDyn.getLong("nckd_postgrade.id")) ? 0L : oldPositionDyn.getLong("nckd_postgrade.id");
            Long newPostGrade = EmptyUtil.isEmpty(newPositionDyn.getLong("nckd_postgrade.id")) ? 0L : newPositionDyn.getLong("nckd_postgrade.id");
            //管理层级
            Long oldMgtLevel = EmptyUtil.isEmpty(oldPositionDyn.getLong("nckd_mgtlvldtl.nckd_mgmtlevel.id")) ? 0L : oldPositionDyn.getLong("nckd_mgtlvldtl.nckd_mgmtlevel.id");
            Long newMgtLevel = EmptyUtil.isEmpty(newPositionDyn.getLong("nckd_mgtlvldtl.nckd_mgmtlevel.id")) ? 0L : newPositionDyn.getLong("nckd_mgtlvldtl.nckd_mgmtlevel.id");

            System.out.println("原岗位ID："+oldPosition+" 现岗位ID："+newPosition);
            System.out.println("原岗位岗位等级："+oldPostGrade+" 现岗位岗位等级："+newPostGrade);
            System.out.println("原岗位管理层级："+oldMgtLevel+" 现岗位管理层级："+newMgtLevel);

            logger.info("原岗位ID："+oldPosition+" 现岗位ID："+newPosition
                    +"原岗位岗位等级："+oldPostGrade+" 现岗位岗位等级："+newPostGrade
                     +"原岗位管理层级："+oldMgtLevel+" 现岗位管理层级："+newMgtLevel);

            if (!oldPostGrade.equals(newPostGrade) && !oldMgtLevel.equals(newMgtLevel)){
                return true;
            }
        }
        return false;
    }

}
