package nckd.jxccl.sit.hcsi.business.datacomparison;


import kd.bos.algo.DataSet;
import kd.bos.algo.JoinDataSet;
import kd.bos.algo.JoinType;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IFormView;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import nckd.jxccl.sit.hcsi.common.constant.SitConstant;
import nckd.jxccl.sit.hcsi.utils.ReportUtils;

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

/**
 * Tyx 2025-10-31
 * 数据比对服务类
 */
public class DataComparisonQueryService {
    private static final Log logger = LogFactory.getLog(DataComparisonQueryService.class);
    private static final String SINSURTASK = "hcsi_sinsurtask";
    String[] mapFields = new String[]{"welfarepayer", "welfaretypeid", "empnumber", "empname", "empidcard", "employee"};
    String[] leftFields = new String[]{"type", "personSysValue", "personSysValuea", "companySysValue", "companySysValuea"};
    String[] rightFields =  new String[]{"personOutValue", "personOutValuea","companyOutValue", "companyOutValuea"};
    IDataModel model = null;
    IFormView view = null;
    public DataComparisonQueryService(IDataModel model,IFormView view) {
        this.model = model;
        this.view = view;
    }

    /**
     * 查询执行实际方法
     *
     * @return
     */
    public DataSet doQuery() {
        logger.info("Tyx begin DataComparisonQueryService.doQuery");
        // 查询任务ID
        List<Long> taskIds = queryTask();
        // Map数据集，用于获取全量人员+险种数据，用于最后join的底表用
        DataSet dataSetMap = queryAllCalPersonAndWelfareTypeByTaskId(taskIds);
        // 根据计算任务Id+险种获取到计算结果明细数据
        DataSet calPersonDataSet = queryCalPersonDetail(taskIds);
        // 按照个人和单位分组汇总 type = 1为个人，type = 2为单位，这里仅为系统内数据
        DataSet groupDataSet = groupCalPersonDetail(calPersonDataSet);
        // 再关联外部数据导入
        DataSet outsidePersonDetail = queryOutsidePersonDetail();
        // 按照个人和单位分组汇总 type = 1为个人，type = 2为单位，这里仅为系统外数据
        DataSet groupDataSetOut = groupCalPersonDetailOut(outsidePersonDetail);
        // 再join
        DataSet finalDataSet = joinFinallyDataSet(dataSetMap, groupDataSet, groupDataSetOut);
        return finalDataSet;
    }

    /**
     * 查询导入任务ID
     * @return
     */
    private List<Long> queryTask() {
        // 社保期间
        DynamicObject period = (DynamicObject)this.model.getValue("nckd_period");
        // 参保单位
        DynamicObject welfarepayer = (DynamicObject)this.model.getValue("nckd_welfarepayer");
        QFilter taskFilter = new QFilter("sinsurperiod.id", QCP.equals, period.getPkValue());
        taskFilter.and("welfarepayer.id", QCP.equals, welfarepayer.getPkValue());
        // 查找社保计算任务
        DynamicObjectCollection taskCols = queryDynamicObjectCollection(taskFilter, SINSURTASK, "id");
        // 获取所有计算任务Id
        List<Long> taskIds = taskCols.stream().map(obj -> obj.getLong("id")).collect(Collectors.toList());
        return taskIds;
    }

    public DynamicObjectCollection queryDynamicObjectCollection(QFilter filter, String entityName, String selectFields) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper(entityName);
        DynamicObjectCollection cols = helper.queryOriginalCollection(selectFields, new QFilter[]{filter});
        return cols;
    }

    /**
     * 根据任务ID获取所有核算人员+险种的笛卡尔积
     * @return
     */
    public DataSet queryAllCalPersonAndWelfareTypeByTaskId(List<Long> taskIds) {
        // 获取核算任务下的所有人
        QFilter filter = new QFilter("sinsurtask.id", QCP.in, taskIds);
        String selectFields = "welfarepayer.id as welfarepayer, empnumberdb as empnumber,namedb as empname,percrenum as empidcard,employee.id as employee, '1' as flag ";
        DataSet dataSet1 = SitConstant.CALPERSON_HELPER.queryDataSet("queryAllCalPerson", selectFields, filter.toArray());

        // 获取所有险种
        DataSet dataSet2 = getWelfAreTypeIdsDataSet();

        DataSet dataSetMap = dataSet1.fullJoin(dataSet2).on("flag", "flag").select(new String[]{"welfarepayer", "empnumber", "empname", "empidcard", "employee"}, new String[]{"id as welfaretypeid"}).finish();
        return dataSetMap;
    }




    /**
     * 获取人员计算详情数据-系统内数据
     * @param taskIds
     * @return
     */
    public DataSet queryCalPersonDetail(List<Long> taskIds) {
        List<Long> welfareTypeIds = getWelfAreTypeIds();
        return ReportUtils.queryCalPersonDetail(welfareTypeIds, taskIds);
    }


    /**
     * 获取险种ID
     * @return
     */
    public List<Long> getWelfAreTypeIds() {
        DynamicObjectCollection welfareTypeCols = (DynamicObjectCollection)model.getValue("nckd_welfaretype");
        List<Long> welfareTypeIds = welfareTypeCols.stream().map(obj -> obj.getDynamicObject("fbasedataid").getLong("id")).collect(Collectors.toList());
        return welfareTypeIds;
    }

    /**
     * 返回险种的DataSet
     * @return
     */
    public DataSet getWelfAreTypeIdsDataSet() {
        List<Long> welfareTypeIds = getWelfAreTypeIds();
        QFilter filter = new QFilter("id", QCP.in, welfareTypeIds);
        return SitConstant.WELFARETYPE_HELPER.queryDataSet("queryWelfAreType", "id, '1' as flag", filter.toArray());
    }

    /**
     * 分组汇总人员明细
     * @param calPersonDataSet
     * @return
     */
    public DataSet groupCalPersonDetail (DataSet calPersonDataSet) {
        calPersonDataSet.groupBy(new String[]{"welfarepayer","welfaretypeid","empnumber","empname","empidcard","employee","type"}).sum("value").sum("value1");
        DataSet dataSet1 = calPersonDataSet.copy();
        DataSet dataSet2 = calPersonDataSet.copy();

        // 按照类型分组汇总
        DataSet sumSet1 = dataSet1.filter("type = '1'").groupBy(new String[]{"welfarepayer", "welfaretypeid", "empnumber", "empname", "empidcard", "employee", "type"}).sum("value").sum("value1").finish();
        DataSet sumSet2 = dataSet2.filter("type = '2'").groupBy(new String[]{"welfarepayer","welfaretypeid","empnumber","empname","empidcard", "employee", "type"}).sum("value").sum("value1").finish();

        // join
        JoinDataSet joinDataSet = sumSet1.join(sumSet2).on("welfarepayer", "welfarepayer").on("welfaretypeid", "welfaretypeid").on("empname", "empname").on("empidcard", "empidcard");
        DataSet dataSet = joinDataSet.select(new String[]{"welfarepayer", "welfaretypeid", "empnumber", "empname", "empidcard", "employee", "type", "value as personSysValue","value1 as personSysValuea"}, new String[]{"value as companySysValue","value1 as companySysValuea"}).finish();

        return dataSet;
    }

    /**
     * 获取人员计算详情数据-系统外数据
     * @return
     */
    private DataSet queryOutsidePersonDetail() {
        // 社保期间
        DynamicObject period = (DynamicObject)this.model.getValue("nckd_period");
        // 参保单位
        DynamicObject welfarepayer = (DynamicObject)this.model.getValue("nckd_welfarepayer");
        DynamicObjectCollection welfareTypeCols = (DynamicObjectCollection)model.getValue("nckd_welfaretype");
        return ReportUtils.queryOutsidePersonDetail(period, welfarepayer, welfareTypeCols);
    }

    public DataSet groupCalPersonDetailOut (DataSet calPersonDataSet) {
        calPersonDataSet.groupBy(new String[]{"welfarepayer","welfaretypeid","empnumber","empname","empidcard","type"}).sum("value").sum("value1");
        DataSet dataSet1 = calPersonDataSet.copy();
        DataSet dataSet2 = calPersonDataSet.copy();

        // 按照类型分组汇总
        DataSet sumSet1 = dataSet1.filter("type = '1'").groupBy(new String[]{"welfarepayer", "welfaretypeid", "empnumber", "empname", "empidcard", "type"}).sum("value").sum("value1").finish();
        DataSet sumSet2 = dataSet2.filter("type = '2'").groupBy(new String[]{"welfarepayer","welfaretypeid","empnumber","empname","empidcard","type"}).sum("value").sum("value1").finish();

        // join
        JoinDataSet joinDataSet = sumSet1.join(sumSet2).on("welfarepayer", "welfarepayer").on("welfaretypeid", "welfaretypeid").on("empname", "empname").on("empidcard", "empidcard");
        DataSet dataSet = joinDataSet.select(new String[]{"welfarepayer", "welfaretypeid", "empnumber", "empname", "empidcard", "type", "value as personOutValue", "value1 as personOutValuea"}, new String[]{"value as companyOutValue","value1 as companyOutValuea"}).finish();

        return dataSet;
    }

    public DataSet joinFinallyDataSet (DataSet dataSetMap, DataSet groupDataSet, DataSet groupDataSetOut) {
        // 中间过度用DataSet
        DataSet midDataSet = dataSetMap.leftJoin(groupDataSet).on("welfarepayer", "welfarepayer").on("welfaretypeid", "welfaretypeid").
                on("empname", "empname").
                on("empidcard", "empidcard").select(mapFields, leftFields).finish();
        // 最终返回DataSet
        DataSet finalDataSet = midDataSet.leftJoin(groupDataSetOut).on("welfarepayer", "welfarepayer").on("welfaretypeid", "welfaretypeid").
                on("empname", "empname").
                on("empidcard", "empidcard").select(midDataSet.getRowMeta().getFieldNames(), rightFields).finish();

        return finalDataSet;
    }

}
