package nckd.jxccl.sit.hcsi.utils;

import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;

import java.util.List;
import java.util.stream.Collectors;

public class ReportUtils {

    private static final String CALPERSON_ENTITY = "hcsi_calperson";
    private static final String INSURANCEITEM_ENTITY = "sitbs_insuranceitem";
    private static final String TEMPDATA_ENTITY = "nckd_sinsurtempdata";
    private static final String TEMPDATA_FIELDS = "nckd_importtask.nckd_welfarepayer.id as welfarepayer,"
            +"nckd_empnumber as empnumber,nckd_empname as empname, nckd_idcard as empidcard, entryentity.nckd_itemid as itemid,"
            +"entryentity.nckd_itemvalue as value";

    //参保单位，险种，工号，姓名，证件号，单位缴费金额 = 单位固定+单位缴费+单位补缴，个人缴费金额=个人固定+个人缴费+个人补缴
    //2025-11-17调整 单位缴费金额 = 单位固定+单位缴费，单位补缴金额 = 单位补缴，个人缴费金额=个人固定+个人缴费；个人补缴 = 个人补缴；
    private static String CALPERSON_FIELDS = "welfarepayer.id as welfarepayer,entryentity.insuranceitem.group.id as welfaretypeid,"
            +"empnumberdb as empnumber,namedb as empname,percrenum as empidcard,employee.id as employee,"
            +"case when entryentity.insuranceitem.insurancetypeattr.number in ('1006_S','1005_S','1009_S','1010_S') then entryentity.amountvalue else 0 end as value,"
            +"case when entryentity.insuranceitem.insurancetypeattr.number in ('1011_S','1012_S') then entryentity.amountvalue else 0 end as value1,"
            +"case when entryentity.insuranceitem.insurancetypeattr.number in ('1005_S','1009_S','1011_S') then '1'"
            +"     when entryentity.insuranceitem.insurancetypeattr.number in ('1006_S','1010_S','1012_S') then '2' end as type";
    private static final String[] INSURANCEPROP = new String[]{"1005_S","1006_S","1009_S","1010_S","1011_S","1012_S"};


    public ReportUtils() {

    }
    /**
     * 获取人员计算详情数据-系统内数据
     * @param welfareTypeIds
     * @param taskIds
     */
    public static DataSet queryCalPersonDetail(List<Long> welfareTypeIds, List<Long> taskIds) {
        List<Long> itemIds = queryInsuranceItem(welfareTypeIds);
        QFilter filter = new QFilter("sinsurtask.id", QCP.in, taskIds);
        filter.and("entryentity.insuranceitem.id", QCP.in, itemIds);
        HRBaseServiceHelper helper = new HRBaseServiceHelper(CALPERSON_ENTITY);
        return helper.queryDataSet("DetailComReport", CALPERSON_FIELDS, new QFilter[]{filter});
    }

    /**
     * 获取人员计算详情数据-系统外数据
     * 先根据参保单位和期间获取外部系统导入任务
     * @return
     */
    public static DataSet queryOutsidePersonDetail(ReportQueryParam reportQueryParam) {
        FilterInfo filterInfo = reportQueryParam.getFilter();
        DynamicObject period = (DynamicObject) filterInfo.getFilterItem("nckd_period").getValue();
        DynamicObject walfarepayer = (DynamicObject) filterInfo.getFilterItem("nckd_welfarepayer").getValue();
        // 险种
        DynamicObjectCollection welfareTypeCols = (DynamicObjectCollection)filterInfo.getFilterItem("nckd_welfaretype").getValue();
        List<Long> welfareTypeIds = welfareTypeCols.stream().map(obj -> obj.getLong("id")).collect(Collectors.toList());
        List<Long> itemIds = queryInsuranceItem(welfareTypeIds);

        QFilter filter = buildOutsideFilter(period, walfarepayer, itemIds);
        HRBaseServiceHelper helper = new HRBaseServiceHelper(TEMPDATA_ENTITY);
        // 查询出外部系统数据
        DataSet outsideDataSet = helper.queryDataSet("DetailComReport_TEMPDATA", TEMPDATA_FIELDS, new QFilter[]{filter});
        // 中间表中没直接存险种项目的基础资料只存了ID，这里再关联一下，需要获取到险种属性
        DataSet insuranceItemDataSet = queryInsuranceItemDataSet(itemIds);
        DataSet dataSet = outsideDataSet.join(insuranceItemDataSet).on("itemid","id").select(
                new String[]{"welfarepayer","empnumber","empname","empidcard","cast(value as Decimal(10,2)) as value"},
                new String[]{"welfaretypeid", "case when attrnumber in ('1005_S','1009_S','1011_S') then '1' when attrnumber in ('1006_S','1010_S','1012_S') then '2' end as type"}).finish();
        return dataSet;
    }

    /**
     * 获取人员计算详情数据-系统外数据
     * 先根据参保单位和期间获取外部系统导入任务
     * @return
     */
    public static DataSet queryOutsidePersonDetail(DynamicObject period, DynamicObject walfarepayer, DynamicObjectCollection welfareTypeCols) {
        List<Long> welfareTypeIds = welfareTypeCols.stream().map(obj -> obj.getDynamicObject("fbasedataid").getLong("id")).collect(Collectors.toList());
        List<Long> itemIds = queryInsuranceItem(welfareTypeIds);

        QFilter filter = buildOutsideFilter(period, walfarepayer, itemIds);
        HRBaseServiceHelper helper = new HRBaseServiceHelper(TEMPDATA_ENTITY);
        // 查询出外部系统数据
        DataSet outsideDataSet = helper.queryDataSet("DetailComReport_TEMPDATA", TEMPDATA_FIELDS, new QFilter[]{filter});
        // 中间表中没直接存险种项目的基础资料只存了ID，这里再关联一下，需要获取到险种属性
        DataSet insuranceItemDataSet = queryInsuranceItemDataSet(itemIds);
        DataSet dataSet = outsideDataSet.join(insuranceItemDataSet).on("itemid","id").select(
                new String[]{"welfarepayer","empnumber","empname","empidcard","cast(value as Decimal(10,2)) as value"},
                new String[]{"attrnumber", "welfaretypeid", "case when attrnumber in ('1005_S','1009_S','1011_S') then '1' when attrnumber in ('1006_S','1010_S','1012_S') then '2' end as type"}).finish();
        DataSet dataSet1 = dataSet.select("welfarepayer","empnumber","empname","empidcard","welfaretypeid","attrnumber","type",
                "case when attrnumber in ('1006_S','1005_S','1009_S','1010_S') then value else 0 end as value",
                "case when attrnumber in ('1011_S','1012_S') then value else 0 end as value1");
        return dataSet1;
    }

    /**
     * 根据险种ID获取险种项目
     * @param welfareTypeIds
     * @return
     */
    public static List<Long> queryInsuranceItem(List<Long> welfareTypeIds) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper(INSURANCEITEM_ENTITY);
        QFilter filter = new QFilter("group.id", QCP.in, welfareTypeIds);
        filter.and("insurancetypeattr.number", QCP.in, INSURANCEPROP);
        DynamicObjectCollection cols = helper.queryOriginalCollection("id", new QFilter[]{filter});
        List<Long> itemIds = cols.stream().map(obj -> obj.getLong("id")).collect(Collectors.toList());
        return itemIds;
    }

    public static DataSet queryInsuranceItemDataSet(List<Long> itemIds) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper(INSURANCEITEM_ENTITY);
        QFilter filter = new QFilter("id", QCP.in, itemIds);
        filter.and("insurancetypeattr.number", QCP.in, INSURANCEPROP);
        return helper.queryDataSet("DetailComReport_INSURANCEITEM", "id, insurancetypeattr.number as attrnumber, group.id as welfaretypeid", new QFilter[]{filter});
    }

    /**
     * 构建查询外部数据的Filter
     *
     * @param period
     * @param walfarepayer
     * @param itemIds
     * @return
     */
    public static QFilter buildOutsideFilter(DynamicObject period, DynamicObject walfarepayer, List<Long> itemIds) {
        QFilter filter = new QFilter("nckd_importtask.nckd_period.id", QCP.equals, period.getPkValue());
        filter.and("nckd_importtask.nckd_welfarepayer.id", QCP.equals, walfarepayer.getPkValue());
        filter.and("entryentity.nckd_itemid", QCP.in, itemIds);
        return filter;
    }

}
