package nckd.jxccl.base.swc.helper;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.validate.BillStatus;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.DispatchServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.hrpi.helper.EmpPosOrgRelHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定调薪帮助类
 *
 * @author W.Y.C
 * @version 1.0
 * @date 2025/12/21 16:02
 */
public class AdjFileServiceHelper {

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

    /**
     * 获取员工某个薪酬项目最新定调薪记录
     * @param personIds 人员id
     * @param standardItemNumber 定调薪项目编码
     * @return: java.util.List<nckd.jxccl.base.swc.helper.AdjFileServiceHelper.SalaryAdjustmentResult>
     * @author W.Y.C
     * @date: 2025/12/21 16:06
     */
    public static List<SalaryAdjustmentResult> getLastDecAdjRecords(List<Long> personIds,String standardItemNumber) {
        Long salaryItemId = EntityHelper.getIdByNumber(FormConstant.HSBS_STANDARDITEM, standardItemNumber);
        //获取员工最新任职
        Map<Long, DynamicObject> empPosOrgRelByEmployeesMap = EmpPosOrgRelHelper.queryEmpPosOrgRelByEmployeesMap(personIds);
        List<Long> allEmpPosOrgRelIds = empPosOrgRelByEmployeesMap.values().stream()
                .map(result -> result.getLong(FormConstant.ID_KEY))
                .collect(Collectors.toList());

        List<SalaryAdjustmentResult> salaryAdjustmentResultList = new ArrayList<>();

        DynamicObject standardItem = EntityHelper.newEntity(FormConstant.HSBS_STANDARDITEM);
        standardItem.set(FormConstant.ID_KEY, salaryItemId);
        Map<String, Object> adjFileParams = new HashMap<>();
        adjFileParams.put("employees", personIds);
        List<String> status = new ArrayList<>();
        status.add(BillStatus.C.toString());
        adjFileParams.put("status", status);
        //获取人员定薪档案
        Map<String, Object> adjFileResult = DispatchServiceHelper.invokeBizService("swc", "hcdm", "IAdjFileInfoService", "queryAdjFileBoByEmp", adjFileParams);
        if (ConvertUtil.toBoolean(adjFileResult.get("success"))) {
            List<Map> list = ConvertUtil.toList(adjFileResult.get("data"), ArrayList::new);
            List<Long> adjFileIds = new ArrayList<>();
            for (Map map : list) {
                Long id = ConvertUtil.toLong(map.get(FormConstant.ID_KEY));
                //根据员工任职匹配
                Long empPosOrgRelId = ConvertUtil.toLong(map.get("empposorgrel_id"));
                if (allEmpPosOrgRelIds.contains(empPosOrgRelId)) {
                    adjFileIds.add(id);
                }
            }
            //构建定调薪记录查询条件
            Map<String, Object> adjRecordParams = new HashMap<>();
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (Long adjFileId : adjFileIds) {
                Map<String, Object> dataItem = new HashMap<>();
                // 调薪档案ID
                dataItem.put("adjfile", adjFileId);
                // 调薪项目ID
                dataItem.put("standarditem", salaryItemId);
                // 查询基准日期
                dataItem.put("startdate", new Date());
                // 唯一标识
                dataItem.put("_uniquecode", "unique" + adjFileId);
                dataList.add(dataItem);
            }
            adjRecordParams.put("data", dataList);
            adjRecordParams.put("selprops", "salarystdv.rankentry.rank.id,salarystdv.rankentry.rank.name,salarystdv.rankentry.rank.number,salarystdv.rankentry.rank.index,salarystdv.rankentry.frankindex,company.id,company.name,hcdmorg.id,");
            //查询定调薪记录
            //hcdm_decadjrecor
            Map<String, Object> lastDecAdjRecordMap = DispatchServiceHelper.invokeService("nckd.jxccl.swc.hcdm.servicehelper", "hcdm", "ISwcService", "getLastDecAdjRecords", adjRecordParams);
            if (ConvertUtil.toBoolean(lastDecAdjRecordMap.get("success"))) {
                List<Map> datas = ConvertUtil.toList(lastDecAdjRecordMap.get("data"), ArrayList::new);
                for (Map data : datas) {
                    if (ConvertUtil.toBoolean(data.get("success"))) {
                        List<DynamicObject> adjRecordList = ConvertUtil.toList(data.get("data"), ArrayList::new);
                        for (DynamicObject dynamicObject : adjRecordList) {
                            // 人员
                            DynamicObject employee = dynamicObject.getDynamicObject("adjfile").getDynamicObject("employee");
                            SalaryAdjustmentResult salaryAdjustmentResult = new SalaryAdjustmentResult();
                            //薪酬管理组织
                            DynamicObject hcdmOrg = dynamicObject.getDynamicObject("hcdmorg");
                            //薪酬标准表版本
                            DynamicObject salaryStDv = dynamicObject.getDynamicObject("salarystdv");
                            //薪等（01岗、02岗）
                            DynamicObject salaryGrade = dynamicObject.getDynamicObject("salarygrade");
                            //薪档（1档、2档）
                            DynamicObject salaryRank = dynamicObject.getDynamicObject("salaryrank");
                            //金额
                            BigDecimal amount = dynamicObject.getBigDecimal("amount");
                            salaryAdjustmentResult.employee = employee;
                            salaryAdjustmentResult.hcdmOrg = hcdmOrg;
                            salaryAdjustmentResult.adjFileInfo = dynamicObject.getDynamicObject("adjfile");
                            salaryAdjustmentResult.salaryStDv = salaryStDv;
                            salaryAdjustmentResult.standardItem = standardItem;
                            salaryAdjustmentResult.salaryGrade = salaryGrade;
                            salaryAdjustmentResult.salaryRank = salaryRank;
                            salaryAdjustmentResult.amount = amount;
                            salaryAdjustmentResultList.add(salaryAdjustmentResult);
                        }
                    }
                }
            } else {
                logger.error("查询定调薪记录失败");
            }
        } else {
            logger.error("获取人员定薪档案失败");
        }
        return salaryAdjustmentResultList;
    }


    public static class SalaryAdjustmentResult {
        /** 人员ID*/
        public DynamicObject employee;
        public DynamicObject hcdmOrg;
        /**定调薪档案*/
        public DynamicObject adjFileInfo;
        /**薪酬标准表*/
        public DynamicObject salaryStDv;
        /** 定调薪项目 */
        public DynamicObject standardItem;
        /** 薪等（01岗、02岗）*/
        public DynamicObject salaryGrade;
        /** 薪档（1档、2档）*/
        public DynamicObject salaryRank;
        //金额
        public BigDecimal amount;
    }
}
