package nckd.jxccl.swc.hscs.business.custfetch;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
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.QueryServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.swc.hcdm.business.helper.HCDMSalaryStdServiceHelper;
import kd.sdk.swc.hcdm.common.dto.stdtab.match.StdTableDataMatchParam;
import kd.sdk.swc.hcdm.common.dto.stdtab.match.StdTableDataMatchResult;
import kd.sdk.swc.hscs.common.api.ICustomFetchDataService;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.swc.hcdm.common.SwcAdjFileServiceHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
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
* @date 2026/1/4 10:14
* @version 1.0
*/
public class PosSalaryGrade1 implements ICustomFetchDataService {

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

    @Override
    public Map<Long, Map<String, Object>> fetchDataCalPerson(List<Long> calPersonIdList, Map<Long, Map<String, Object>> paramsMap, Map<String, Object> extParamMap) {
        Map<Long, Map<String, Object>> resultMap = new HashMap<Long, Map<String, Object>>();

        Long salaryItemId = EntityHelper.getIdByNumber(FormConstant.HSBS_STANDARDITEM, FormConstant.POS_STANDARD_ITEM_NUMBER);
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.EMP_NUMBER_KEY)
                .add(FormConstant.NAME_KEY)
                .add(FormConstant.ORG_KEY)
                .addGroup(new String[]{"caltask"}, "calcount", "payrolldate")
                .addGroup(new String[]{"caltask", "calrule"}, FormConstant.ID_KEY)
                .addGroup(new String[]{FormConstant.EMPLOYEE_KEY}, FormConstant.ID_KEY);
        QFilter qFilter = new QFilter(FormConstant.ID_KEY, "in", calPersonIdList);
        DynamicObject[] load = new HRBaseServiceHelper("hsas_calperson").load(queryFieldBuilder.buildSelect(), new QFilter[]{qFilter});
        if(load != null && load.length > 0) {
            Map<Long, Long> employeeToCalPersonMap = Arrays.stream(load)
                    .collect(Collectors.toMap(
                            obj -> obj.getLong(FormConstant.ID_KEY),
                            obj -> obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))
                    ));
            long orgId = load[0].getLong(String.join(".", FormConstant.ORG_KEY, FormConstant.ID_KEY));
            //核算任务
            DynamicObject calTask = load[0].getDynamicObject("caltask");
            //薪资所属年月
            Date date = calTask.getDate("payrolldate");
            int year = DateUtil.getYear(date);
            int month = DateUtil.getMonthValue(date);
            //核算规则
            long calRuleId = calTask.getLong(String.join(".", "calrule", FormConstant.ID_KEY));
            //核算次数
            int calCount = calTask.getInt("calcount");


            Map<Long, BigDecimal> amountMap = new HashMap<>(employeeToCalPersonMap.size());
            if(!employeeToCalPersonMap.isEmpty()) {
                //获取人员最新岗位工资标准定薪记录
                List<Long> allPersonIds = ConvertUtil.toList(employeeToCalPersonMap.values());
                List<SwcAdjFileServiceHelper.SalaryAdjustmentResult> salaryAdjustmentResultList = SwcAdjFileServiceHelper.getLastDecAdjRecords(allPersonIds, FormConstant.POS_STANDARD_ITEM_NUMBER);
                if (!salaryAdjustmentResultList.isEmpty()) {
                    //薪酬标准ID
                    List<Long> salaryStIds = salaryAdjustmentResultList.stream().map(result -> result.salaryStDv.getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
                    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});
                    Map<Long, DynamicObject> salaryStandardMap = salaryStandardColl.stream()
                            .collect(Collectors.toMap(
                                    obj -> obj.getLong(FormConstant.ID_KEY),
                                    obj -> obj
                            ));

                    if (!salaryStandardMap.isEmpty()) {
                        List<StdTableDataMatchParam> matchParams = new ArrayList<>();
                        for (SwcAdjFileServiceHelper.SalaryAdjustmentResult result : salaryAdjustmentResultList) {
                            StdTableDataMatchParam stdTableDataMatchParam = new StdTableDataMatchParam();
                            stdTableDataMatchParam.setStdTableId(result.salaryStDv.getLong(FormConstant.ID_KEY));
                            stdTableDataMatchParam.setStdItemId(salaryItemId);
                            stdTableDataMatchParam.setGradeId(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.setRankId(rankId);
                                matchParams.add(stdTableDataMatchParam);
                            }
                        }
                        if (!matchParams.isEmpty()) {
                            //获取薪酬项目、薪等、薪档对应金额（入参params的数组下标和出参的数组下标一一对应）
                            List<StdTableDataMatchResult> stdTableDataMatchResults = HCDMSalaryStdServiceHelper.matchStdTableData(matchParams);
                            for (int i = 0; i < salaryAdjustmentResultList.size(); i++) {
                                SwcAdjFileServiceHelper.SalaryAdjustmentResult result = salaryAdjustmentResultList.get(i);
                                if (i < stdTableDataMatchResults.size() && stdTableDataMatchResults.get(i) != null) {
                                    //当前薪等01档的金额
                                    amountMap.put(result.employee.getLong(FormConstant.ID_KEY), stdTableDataMatchResults.get(i).getAmount());
                                }
                            }
                        }
                    } else {
                        logger.warn("未获取薪酬标准表中01档的薪档数据，薪酬标准ID：{}", salaryStIds);
                    }
                } else {
                    logger.warn("未获取到人员岗位工资标准定薪记录，人员ID：{}", allPersonIds);
                }
            }

            for (Long calPersonId : calPersonIdList) {
                Long personId = employeeToCalPersonMap.get(calPersonId);
                BigDecimal amount = amountMap.get(personId);
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("postSalGrade",amount != null ? amount : BigDecimal.ZERO);
                resultMap.put(calPersonId, result);
            }

        }
        return resultMap;
    }

    @Override
    public Map<String, Object> fetchDataCalTask(Long calTaskId, Map<String, Object> paramsMap, Map<String, Object> extParamMap) {
        return null;
    }
}
