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

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.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
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.DispatchServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.enums.psms.TypeStateEnum;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.swc.helper.AdjFileServiceHelper;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;

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

/**
* 员工职位档案-保存
* 实体标识：nckd_personposfile
* @author W.Y.C
* @date 2025/12/4 19:36
* @version 1.0
*/
public class PersonPosFileSaveOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

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



    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        logger.info("beginOperationTransaction start: processing {} data entities", e.getDataEntities().length);

        //职位津贴=职位系数 X 所在岗级岗位工资一档金额
        List<Long> allPersonIds = new ArrayList<>(e.getDataEntities().length);
        List<Long> jobLevelIds = new ArrayList<>(e.getDataEntities().length);
        for (DynamicObject dataEntity : e.getDataEntities()) {
            String typeState = dataEntity.getString(PositionStructureConstant.NCKD_TYPESTATE);
            if(Arrays.asList(TypeStateEnum.NEW_ENTRY.getCode(), TypeStateEnum.IN_SERVICE_LEVEL.getCode(), TypeStateEnum.ANNUAL_ADJUSTMENT.getCode(), TypeStateEnum.POSITION_TRANSFER.getCode()).contains(typeState)){
                //只有新入职、在职人员初定、年度调整、动态调整才要获取薪酬
                BigDecimal coefficient = dataEntity.getBigDecimal(PositionStructureConstant.NCKD_COEFFICIENT);
                BigDecimal currentPostSalary = dataEntity.getBigDecimal(PositionStructureConstant.NCKD_CURRENTPOSTSALARY);
                BigDecimal postAllowance = dataEntity.getBigDecimal(PositionStructureConstant.NCKD_POSTALLOWANCE);
                //当职位系数、岗位工资一档金额、岗位津贴为0时才处理，不为空则跳过
                if((coefficient == null || coefficient.compareTo(BigDecimal.ZERO) <= 0) && (currentPostSalary == null || currentPostSalary.compareTo(BigDecimal.ZERO) <= 0) && (postAllowance == null || postAllowance.compareTo(BigDecimal.ZERO) <= 0)){
                    long personId = dataEntity.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY));
                    if(personId > 0){
                        allPersonIds.add(personId);
                    }
                    long jobLevelId = dataEntity.getLong(String.join(".", PositionStructureConstant.NCKD_JOBLEVELHR, FormConstant.ID_KEY));
                    jobLevelIds.add(jobLevelId);
                }
            }
        }
        
        logger.info("Collected person IDs count: {}, job level IDs count: {}", allPersonIds.size(), jobLevelIds.size());

        //====================================== 获取当前人员所在定调的岗位标准工资一档金额 begin ======================================
        try {
            Long salaryItemId = EntityHelper.getIdByNumber(FormConstant.HSBS_STANDARDITEM, FormConstant.POS_STANDARD_ITEM_NUMBER);
            logger.info("Retrieved salary item ID: {}", salaryItemId);
            
            Map<Long, BigDecimal> amountMap = new HashMap<>(e.getDataEntities().length);
            if (!allPersonIds.isEmpty() && !jobLevelIds.isEmpty()) {
                logger.info("Processing salary adjustment records for {} person IDs", allPersonIds.size());
                
                //获取人员最新岗位工资标准定薪记录
                List<AdjFileServiceHelper.SalaryAdjustmentResult> salaryAdjustmentResultList = AdjFileServiceHelper.getLastDecAdjRecords(allPersonIds, FormConstant.POS_STANDARD_ITEM_NUMBER);
                logger.info("Retrieved {} salary adjustment results", salaryAdjustmentResultList.size());
                
                if (!salaryAdjustmentResultList.isEmpty()) {
                    //薪酬标准ID
                    List<Long> salaryStIds = salaryAdjustmentResultList.stream().map(result -> result.salaryStDv.getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
                    logger.info("Retrieved salary standard IDs: {}", salaryStIds.size());
                    
                    QFilter filter = new QFilter(FormConstant.ID_KEY, QCP.in, salaryStIds)
                            .and(String.join(".", "rankentry", "rank", FormConstant.NUMBER_KEY), QCP.equals, "01");
                    //获取标准表中01档的薪档
                    QueryFieldBuilder salaryStandFieldBuilder = QueryFieldBuilder.create()
                            .add(FormConstant.ID_KEY)
                            .addIdNumberNameWithExtras(new String[]{"rankentry", "rank"}, FormConstant.INDEX_KEY);
                    DynamicObjectCollection salaryStandardColl = QueryServiceHelper.query("hcdm_salarystandard", salaryStandFieldBuilder.buildSelect(), new QFilter[]{filter});
                    logger.info("Retrieved {} salary standard records", salaryStandardColl.size());
                    
                    Map<Long, DynamicObject> salaryStandardMap = salaryStandardColl.stream()
                            .collect(Collectors.toMap(
                                    obj -> obj.getLong(FormConstant.ID_KEY),
                                    obj -> obj
                            ));

                    if (!salaryStandardMap.isEmpty()) {
                        logger.info("Created salary standard map with {} entries", salaryStandardMap.size());
                        List<Map<String,Object>> matchParams = new ArrayList<>();
                        for (AdjFileServiceHelper.SalaryAdjustmentResult result : salaryAdjustmentResultList) {
                            Map<String,Object> stdTableDataMatchParam = new HashMap<>();

                            stdTableDataMatchParam.put("stdTableId",result.salaryStDv.getLong(FormConstant.ID_KEY));
                            stdTableDataMatchParam.put("stdItemId",salaryItemId);
                            stdTableDataMatchParam.put("gradeId",result.salaryGrade.getLong(FormConstant.ID_KEY));
                            DynamicObject dynamicObject = salaryStandardMap.get(result.salaryStDv.getLong(FormConstant.ID_KEY));
                            if (dynamicObject != null) {
                                long rankId = dynamicObject.getLong(String.join(".", "rankentry", "rank", FormConstant.ID_KEY));
                                stdTableDataMatchParam.put("rankId",rankId);
                                matchParams.add(stdTableDataMatchParam);
                            }
                        }
                        logger.info("Created {} match parameters", matchParams.size());
                        
                        if (!matchParams.isEmpty()) {
                            //获取薪酬项目、薪等、薪档对应金额（入参params的数组下标和出参的数组下标一一对应）
//                            List<StdTableDataMatchResult> stdTableDataMatchResults = HCDMSalaryStdServiceHelper.matchStdTableData(matchParams);
                            List<Map<String,Object>> stdTableDataMatchResults = DispatchServiceHelper.invokeService("nckd.jxccl.swc.hcdm.servicehelper", "hcdm", "ISwcService", "matchStdTableData", matchParams);
                            logger.info("Retrieved {} standard table match results", stdTableDataMatchResults.size());
                            
                            for (int i = 0; i < salaryAdjustmentResultList.size(); i++) {
                                AdjFileServiceHelper.SalaryAdjustmentResult result = salaryAdjustmentResultList.get(i);
                                if (i < stdTableDataMatchResults.size() && stdTableDataMatchResults.get(i) != null) {
                                    //当前薪等01档的金额
                                    amountMap.put(result.employee.getLong(FormConstant.ID_KEY), ConvertUtil.toBigDecimal(stdTableDataMatchResults.get(i).get("amount")));
                                }
                            }
                            logger.info("Populated amount map with {} entries", amountMap.size());
                        }
                    } else {
                        logger.warn("未获取薪酬标准表中01档的薪档数据，薪酬标准ID：{}", salaryStIds);
                    }
                } else {
                    logger.warn("未获取到人员岗位工资标准定薪记录，人员ID：{}", allPersonIds);
                }
            }
            //====================================== 获取当前人员所在定调的岗位标准工资一档金额 end ======================================
            Map<Long, DynamicObject> jobLevelMap = new HashMap<>(e.getDataEntities().length);
            if (!jobLevelIds.isEmpty()) {
                logger.info("Loading job level information for {} IDs", jobLevelIds.size());
                MainEntityType jobLevelEntityType = EntityMetadataCache.getDataEntityType(FormConstant.HBJM_JOBLEVELHR);
                //重新加载职级信息，避免获取不到系数
                DynamicObject[] load = BusinessDataServiceHelper.load(jobLevelIds.toArray(new Long[0]), jobLevelEntityType);
                jobLevelMap = Arrays.stream(load)
                        .collect(Collectors.toMap(
                                obj -> obj.getLong(FormConstant.ID_KEY),
                                obj -> obj
                        ));
                logger.info("Loaded {} job level records", jobLevelMap.size());
            }

            logger.info("Processing {} data entities for coefficient and salary calculation", e.getDataEntities().length);
            for (DynamicObject dataEntity : e.getDataEntities()) {
                long jobLevelId = dataEntity.getLong(String.join(".", PositionStructureConstant.NCKD_JOBLEVELHR, FormConstant.ID_KEY));
                DynamicObject jobLevel = jobLevelMap.get(jobLevelId);
                if (jobLevel != null) {
                    DynamicObject person = dataEntity.getDynamicObject(FormConstant.NCKD_PERSON);
                    long personId = person.getLong(FormConstant.ID_KEY);
                    //当前岗位工资01档金额
                    BigDecimal amount = amountMap.get(personId);
                    if (amount != null && amount.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal coefficient = jobLevel.getBigDecimal(PositionStructureConstant.NCKD_COEFFICIENT);
                        if (coefficient.compareTo(BigDecimal.ZERO) > 0) {
                            dataEntity.set(PositionStructureConstant.NCKD_COEFFICIENT, coefficient);
                            dataEntity.set(PositionStructureConstant.NCKD_CURRENTPOSTSALARY, amount);
                            dataEntity.set(PositionStructureConstant.NCKD_POSTALLOWANCE, coefficient.multiply(amount));
                            logger.info("Updated person ID: {}, coefficient: {}, current post salary: {}, post allowance: {}", 
                                personId, coefficient, amount, coefficient.multiply(amount));
                        }
                    } else {
                        logger.warn("未获取到员工【{}】最新岗位工资标准定薪记录01档的薪等金额，人员ID：{}", person.getString(FormConstant.NAME_KEY), personId);
                    }
                }
            }
            logger.info("beginOperationTransaction completed successfully");
        }catch (Exception e1){
            logger.error("获取人员岗位工资标准定薪记录01档的薪等金额异常", e1);
        }
    }

}