package nckd.jxccl.swc.hcdm.business.annualincome;


import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.QueryEntityType;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRQueryEntityHelper;
import kd.sdk.swc.hsas.business.internal.spi.CalResultQueryService;
import nckd.jxccl.swc.constants.SwcConstant;
import nckd.jxccl.swc.utils.SwcUtils;

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


/**
 * Tyx 2025-11-05
 * 年度收入相关单据用服务类
 */
public class AnnualIncomeService {

    private static final Log logger = LogFactory.getLog(AnnualIncomeService.class);
    List<Long> groupIds;
    Date startDate;
    Date endDate;

    public AnnualIncomeService(List<Long> groupIds, Date startDate, Date endDate) {
        this.groupIds = groupIds;
        this.startDate = startDate;
        this.endDate = endDate;
    }


    /**
     * 根据核算人员+薪酬项目获取薪资明细
     * @param calPersonIds
     * @param itemIds
     */
    public Map<Long, Map<Long, Object>> querySalaryDetail(List<Long> calPersonIds, List<Long> itemIds) {
        logger.info("开始查询薪资明细数据，参数：{},{}", calPersonIds, itemIds);
        Map<Long, Map<Long, Object>> map = CalResultQueryService.get().getSalaryResult(calPersonIds, itemIds);
        return map;
    }


    /**
     * 通过薪资核算组获取核算人员
     *
     * @return
     */
    public DynamicObjectCollection queryCalPersonByPayRollGroup() {
        // 先获取核算任务ID
        List<Long> taskIds = queryCalPayRollTaskByPayRollGroup();
        // 再根据任务ID获取核算人员
        return queryCalPersonByCalPayRollTask(taskIds);
    }

    /**
     * 根据薪资核算组+日期范围获取核算任务
     * @return
     */
    private List<Long> queryCalPayRollTaskByPayRollGroup () {
        logger.info("开始查询核算任务数据，参数：{},{},{}", groupIds, startDate, endDate);
        QFilter filter = new QFilter("payrollgroup.id", QCP.in, groupIds);
        // 2025-11-25 Tyx
        // 由payrolldate薪资所属年月 改为 paydate预计支付日期
        filter.and("paydate", QCP.large_equals, startDate);
        filter.and("paydate", QCP.less_equals, endDate);
        DynamicObject[] taskCols = queryCalPayRollTaskByPayRollGroup("id, paydate, payrolldate, payrollgroup", filter.toArray());
        List<Long> taskIds = (List) Arrays.stream(taskCols).map((o) -> {
            return o.getLong("id");
        }).collect(Collectors.toList());
        return taskIds;
    }
    /**
     * 根据薪资核算组获取核算任务
     * @param filter 过滤条件
     * @return
     */
    private DynamicObject[] queryCalPayRollTaskByPayRollGroup (String selectFields, QFilter[] filter) {
        logger.info("开始查询核算任务数据，参数：{}", filter.toString());
        return SwcConstant.CALPAYROLLTASK_HELPER.load(selectFields, filter);
    }
    /**
     * 根据核算任务ID获取核算人员
     * 标品CalResultQueryService.get().getCalPersonInfos会报错，详见问题列表52项；
     * 新增一个hsas_salarycalresultqueryex查询
     * 这里改成先通过getCalPersonIds获取到核算人员ID，再获取相关信息
     * @param taskIds
     * @return
     */
    private DynamicObjectCollection queryCalPersonByCalPayRollTask (List<Long> taskIds) {
        logger.info("开始查询核算人员数据，参数：{}", taskIds);
        QFilter filter = new QFilter("hsas_calpayrolltask.id", QCP.in, taskIds);
        filter.and("calstatus", QCP.equals, "4");
        QueryEntityType queryEntityType = (QueryEntityType) EntityMetadataCache.getDataEntityType("hsas_salarycalresultqueryex");
        DataSet dataSet = HRQueryEntityHelper.getInstance().getQueryDataSet(queryEntityType, "id,hsbs_percre.number,hsbs_employee.id,hsbs_employee.empnumber,hsas_calpayrolltask.payrolldate", new QFilter[]{filter}, "id", false, 0, 1000);
        DynamicObjectCollection calPersonCols = ORM.create().toPlainDynamicObjectCollection(dataSet);
        return calPersonCols;
    }

    /**
     * 根据薪资核算组+日期范围获取薪资明细
     * @return
     */
    public DynamicObjectCollection querySalaryDetailBySql() {
        StringBuilder sb = SwcUtils.getSalaryDetailSql(groupIds, startDate, endDate);
        DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("swc"), sb.toString());
        DynamicObjectCollection cols = ORM.create().toPlainDynamicObjectCollection(dataSet);
        return cols;

    }

    /**
     * 查询年收入的人员ID，后续排除用
     * @return
     */
    public List<Long> queryIncomeBillEmployeeId() {
        QFilter filter = new QFilter("nckd_entryentity.nckd_payrollgrp.id", QCP.in, groupIds);
        filter.and("nckd_calyear", QCP.equals, startDate);
        filter.and("nckd_entryentity.nckd_pushstatus", QCP.not_equals2 , "3");  // 不等于废弃
        String selectFields = "nckd_entryentity.nckd_employee.id";
        DynamicObjectCollection dyns = SwcConstant.SALANNUALINCOMEBILL_ENTITY.queryOriginalCollection(selectFields, filter.toArray());

        return dyns.stream().map((o) -> {
            return o.getLong("nckd_entryentity.nckd_employee.id");
        }).collect(Collectors.toList());

    }

    public List<Long> getExcludePayRollGroupIds (Date startDate) {
        List<Long> excludeGroupIds = new ArrayList<Long>();
        QFilter filter = new QFilter("nckd_calyear", QCP.equals, startDate);
        DynamicObjectCollection cols = SwcConstant.SALANNUALINCOMEBILL_ENTITY.queryOriginalCollection("nckd_payrollgrp.id", filter.toArray());
        excludeGroupIds.addAll(cols.stream().map(obj -> obj.getLong("nckd_payrollgrp.id")).collect(Collectors.toList()));
        return excludeGroupIds;
    }


}
