package nckd.jxccl.opmc.pm.plugin.form.print;

import kd.bos.algo.DataSet;
import kd.bos.algo.GroupbyDataSet;
import kd.bos.algo.JoinType;
import kd.bos.algo.Row;
import kd.bos.common.enums.EnableEnum;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.QueryEntityType;
import kd.bos.entity.report.AbstractReportColumn;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.DynamicReportColumnEvent;
import kd.bos.entity.report.FastFilter;
import kd.bos.entity.report.IReportBatchQueryInfo;
import kd.bos.entity.report.ReportColumn;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.model.PermissionStatus;
import kd.hr.hbp.business.servicehelper.HRQueryEntityHelper;
import kd.hr.hbp.common.cache.HRAppCache;
import kd.sdk.hr.hbp.business.helper.permission.HRPermissionServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.algo.DistinctConcatFunction;
import nckd.jxccl.base.common.algo.GroupMaxStrFunction;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.opmc.pm.common.PerfManagerFormConstant;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* 年度绩效结果明细-报表取数插件
* 实体标识：nckd_annualperfdetail
* @author W.Y.C
* @date 2025/11/13 16:09
* @version 1.0
*/
public class PrintPerfDetailReportListDataPlugin extends AbstractReportListDataPlugin implements Plugin {

    @Override
    public void getDynamicColumns(DynamicReportColumnEvent event) {
        super.getDynamicColumns(event);
    }

    @Override
    public DataSet queryBatchBy(ReportQueryParam queryParam){
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .orderDesc(FormConstant.NCKD_PERSON,PerfManagerFormConstant.NCKD_BEGINYEAR);
        QFilter qFilter = QFilter.of("1=1");
        //权限过滤
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_pm", PerfManagerFormConstant.PERFMANAGER_ENTITYID,
                PermissionStatus.View, new HashMap<>());
        if(dataRule != null){
            qFilter.and(dataRule);
        }
        IReportBatchQueryInfo byBatchInfo = queryParam.byBatchInfo();
        byBatchInfo.setCountPerBatch(2000);
        return QueryServiceHelper.queryDataSet(this.getClass().getName(),PerfManagerFormConstant.PERFMANAGER_ENTITYID, queryFieldBuilder.buildSelect(), new QFilter[]{qFilter}, queryFieldBuilder.buildOrder(),1000000);
    }

    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {

        Map<Integer,Long> selectPrintPersonIdMap = HRAppCache.get("nckd_pm").get("selectPrintPersonIdMap", Map.class);

        // 构建查询字段
        QueryFieldBuilder queryFieldBuilder = buildQueryFieldBuilder();

        LocalDate now = LocalDate.now();
        // 获取5年前的年份
        int fiveYearsAgo = LocalDate.now().minusYears(5).getYear();
        Date beginDate = DateUtil.toDate(LocalDate.of(fiveYearsAgo, 1, 1));

        int currentYear = LocalDate.now().getYear() - 1; // 不包含今年
        Date endDate = DateUtil.toDate(LocalDate.of(currentYear, 1, 1));


        // 分批加载过滤
        IReportBatchQueryInfo byBatchInfo = reportQueryParam.byBatchInfo();
        // 获取当前批次的分批依据行
        List<Row> currentBatchRows = byBatchInfo.getCurrentBatchRows();
        Set<Long> idsOfCurrentBatch = new HashSet<>(3000);
        for (Row currentBatchRow : currentBatchRows) {
            Long matId = currentBatchRow.getLong(0);
            idsOfCurrentBatch.add(matId);
        }
        //查询最近5年的数据
        /*QFilter qFilter = new QFilter(PerfManagerFormConstant.NCKD_BEGINYEAR, QCP.less_equals, endDate)
                .and(new QFilter(PerfManagerFormConstant.NCKD_ENDYEAR, QCP.large_equals, beginDate));*/
        QFilter qFilter = QFilter.of("1=1");
        if(!idsOfCurrentBatch.isEmpty()){
            qFilter.and(new QFilter(FormConstant.ID_KEY, QCP.in, idsOfCurrentBatch));
        }
        qFilter.and(String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.POS_STATUS,FormConstant.POST_STATE_CLS, FormConstant.NUMBER_KEY),QCP.equals,"1010_S");
        // 处理快速过滤条件
        processFastFilter(reportQueryParam, qFilter);

        //其他过滤条件
        processFilter(reportQueryParam, qFilter);
        //权限过滤
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_pm", PerfManagerFormConstant.PERFMANAGER_ENTITYID,
                PermissionStatus.View, new HashMap<>());
        if(dataRule != null){
            qFilter.and(dataRule);
        }
        // 执行基础查询
        QueryEntityType queryEntityType = (QueryEntityType) EntityMetadataCache.getDataEntityType("printperfquery");
        DataSet dataSet = HRQueryEntityHelper.getInstance().getQueryDataSet(queryEntityType,queryFieldBuilder.buildSelect(), new QFilter[]{qFilter}, null);
        DataSet dataSetCopy = dataSet.copy();
        Set<Long> personIds = new HashSet();
        while (dataSetCopy.hasNext()) {
            Row next = dataSetCopy.next();
            Long personId = next.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY));
            personIds.add(personId);
        }
        if(personIds.isEmpty()){
            return dataSet;
        }
        //过滤调实际结束实际之外的年份分录
        DataSet withYearFields = dataSet.filter("year("+String.join(".", PerfManagerFormConstant.PERFMANAGERENTRY, PerfManagerFormConstant.NCKD_APPRAISALYEAR) +") " +
                "<= year(CASE WHEN nckd_actendyear is not null THEN nckd_actendyear ELSE "+PerfManagerFormConstant.NCKD_ENDYEAR+" end)");

        // 动态添加年份字段；行转列
        int tempIndex = 1;
        for (int year = fiveYearsAgo; year <= currentYear; year++) {
            withYearFields = withYearFields.addField(
                    "CASE WHEN year(" + String.join(".", PerfManagerFormConstant.PERFMANAGERENTRY, PerfManagerFormConstant.NCKD_APPRAISALYEAR) + ") = " + year + " THEN " + String.join(".", PerfManagerFormConstant.PERFMANAGERENTRY, PerfManagerFormConstant.NCKD_APPRAISALRESULT,FormConstant.ID_KEY)+ " ELSE null END",
                    "temp_" + tempIndex);
            withYearFields = withYearFields.addField(year+"","temp_year_" + tempIndex);
            tempIndex++;
        }

        // 按分组字段聚合
        GroupbyDataSet groupbyDataSet = withYearFields.groupBy(new String[]{
                String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY),
                String.join(".", FormConstant.NCKD_EMPPOSORGREL, FormConstant.EMPLOYEE_KEY, FormConstant.EMP_NUMBER_KEY),
                String.join(".", FormConstant.NCKD_EMPPOSORGREL, FormConstant.EMPLOYEE_KEY, FormConstant.NAME_KEY),
                String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG, FormConstant.NCKD_FIRSTORG, FormConstant.ID_KEY),
                String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG, FormConstant.NCKD_SECONDORG, FormConstant.ID_KEY),
                String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG, FormConstant.NCKD_THIRDORG, FormConstant.ID_KEY),
                String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG, FormConstant.NCKD_FOURTHORG, FormConstant.ID_KEY),
                String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG, FormConstant.NCKD_FIFTHORG, FormConstant.ID_KEY),
                String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG, FormConstant.NCKD_SIXTHORG, FormConstant.ID_KEY),
                String.join(".", FormConstant.HRPI_EMPENTREL, FormConstant.LABOR_REL_STATUS, FormConstant.ID_KEY),
                String.join(".", FormConstant.NCKD_PERSON, FormConstant.NCKD_JOINWORKTIME),
                String.join(".", FormConstant.NCKD_PERSON, FormConstant.BIRTHDAY),
                String.join(".", FormConstant.NCKD_PERSON, FormConstant.GENDER,FormConstant.NAME_KEY),
                String.join(".", FormConstant.HRPI_PEREDUEXP, FormConstant.EDUCATION_KEY,FormConstant.NAME_KEY),
//                String.join(".", FormConstant.NCKD_EMPPOSORGREL, FormConstant.POSITION_KEY, FormConstant.ID_KEY),
                String.join(".", "last_perfmanager", PerfManagerFormConstant.NCKD_BEGINYEAR),
                String.join(".", "last_perfmanager", PerfManagerFormConstant.NCKD_ENDYEAR),
                String.join(".", PerfManagerFormConstant.DOCSTAMP_ENTITYID, PerfManagerFormConstant.NCKD_STAMPTIME),
                String.join(".", PerfManagerFormConstant.DOCSTAMP_ENTITYID, PerfManagerFormConstant.NCKD_FILEISSUETIME),
                String.join(".", PerfManagerFormConstant.HRPI_EMPPOSORGREL, PerfManagerFormConstant.POSITION_KEY, FormConstant.ID_KEY),
                String.join(".", PerfManagerFormConstant.HRPI_PERSERLEN, PerfManagerFormConstant.FIRSTJOINCOMDATE_KEY),
                String.join(".", PerfManagerFormConstant.HRPI_PERSERLEN, PerfManagerFormConstant.JOINCOMDATE_KEY),
                String.join(".", PerfManagerFormConstant.HRPI_PERSERLEN, PerfManagerFormConstant.STARTDATE),
        });
        int tempIndex1 = 1;
        for (int year = fiveYearsAgo; year <= currentYear; year++) {
            groupbyDataSet
                    .max("temp_"+tempIndex1, tempIndex1+"_result");
            groupbyDataSet
                    .max("temp_year_"+tempIndex1, "year_"+tempIndex1);
            tempIndex1++;
        }
        //职称/技能使用逗号分拼接
        groupbyDataSet.agg(new DistinctConcatFunction(),"hrpi_perprotitle.professional.name","perprotitlenames");
        groupbyDataSet.agg(new DistinctConcatFunction(),"nckd_hrpi_empskill.nckd_qualiname","qualinames");

        DataSet annualPerfDetailQueryDataSet = groupbyDataSet.finish();
        annualPerfDetailQueryDataSet.print(true);
        String[] mainTableFieldNames = annualPerfDetailQueryDataSet.getRowMeta().getFieldNames();
        // 创建新数组，长度比原数组多1
        String[] newMainTableFieldNames = new String[mainTableFieldNames.length + 1];
        System.arraycopy(mainTableFieldNames, 0, newMainTableFieldNames, 0, mainTableFieldNames.length);
        // 在最后添加新字段
        newMainTableFieldNames[mainTableFieldNames.length] = "REPLACE(REPLACE(REPLACE(concat(perprotitlenames,'；',qualinames),'null，',''),'null；',''),'null','') as perprotitlOrQuali";
        mainTableFieldNames = newMainTableFieldNames;
        annualPerfDetailQueryDataSet.select(mainTableFieldNames);

/*//        获取近5年的岗位信息
        DataSet positionDateSet = getPositions(fiveYearsAgo, currentYear, personIds);
        String[] pivotFieldNames = positionDateSet.getRowMeta().getFieldNames();
        annualPerfDetailQueryDataSet = annualPerfDetailQueryDataSet.join(positionDateSet, JoinType.LEFT)
                .on(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY), String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))
                .select(mainTableFieldNames, pivotFieldNames).finish();

        DataSet perfRankMgmtDataSet = getPerfRankMgmt(personIds, fiveYearsAgo, currentYear);

        mainTableFieldNames = annualPerfDetailQueryDataSet.getRowMeta().getFieldNames();
        pivotFieldNames = perfRankMgmtDataSet.getRowMeta().getFieldNames();
        java.util.List<String> filteredFieldNames = new java.util.ArrayList<>();
        for (String fieldName : pivotFieldNames) {
            if (!"nckd_person.id".equals(fieldName)) {
                filteredFieldNames.add(fieldName);
            }
        }
        pivotFieldNames = filteredFieldNames.toArray(new String[0]);
        return annualPerfDetailQueryDataSet.join(perfRankMgmtDataSet, JoinType.LEFT)
                .on(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY), String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY))
                .select(mainTableFieldNames, pivotFieldNames).finish();*/



        return annualPerfDetailQueryDataSet;
    }

    private static DataSet getPerfRankMgmt(Set<Long> personIds, int beginYear, int endYear) {
        // 年度绩效排名管理
        QueryFieldBuilder perfRankMgmtFieldBuilder = QueryFieldBuilder.create()
                .addIdNumberName(FormConstant.NCKD_PERSON)
                .add("nckd_toprank")
                .addGroup(new String[]{"nckd_perfrankmgmt"},"nckd_topranks","nckd_theyear");
        QFilter perfRankMgmtFilter = new QFilter("nckd_isranking", "=", EnableEnum.YES.getCode())
                .and(FormConstant.NCKD_PERSON, QCP.in, personIds)
                .and("nckd_perfrankmgmt.nckd_theyear",QCP.large_equals, beginYear)
                .and("nckd_perfrankmgmt.nckd_theyear",QCP.less_equals, endYear);
        DataSet perfRankMgmtDataSet = QueryServiceHelper.queryDataSet("PrintPerfDetailReportListDataPlugin_perfRank", "nckd_perfrankmgmtentry", perfRankMgmtFieldBuilder.buildSelect(), new QFilter[]{perfRankMgmtFilter}, perfRankMgmtFieldBuilder.buildOrder(), 10000);
        int tempIndex = 1;
        for (int year = beginYear; year <= endYear; year++) {
            //排名
            String toprankField = "CASE WHEN nckd_perfrankmgmt.nckd_theyear = "+year+" THEN nckd_toprank ELSE null END";
            perfRankMgmtDataSet = perfRankMgmtDataSet.addField(toprankField, "perfrankmgmt_topran_temp_" + tempIndex);
            //总人数
            String topranksField = "CASE WHEN nckd_perfrankmgmt.nckd_theyear = "+year+" THEN nckd_perfrankmgmt.nckd_topranks ELSE null END";
            perfRankMgmtDataSet = perfRankMgmtDataSet.addField(topranksField, "perfrankmgmt_topranks_temp_" + tempIndex);
            tempIndex++;
        }
        GroupbyDataSet groupbyDataSet = perfRankMgmtDataSet.groupBy(new String[]{String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY)});
        tempIndex = 1;
        for (int year = beginYear; year <= endYear; year++) {
            groupbyDataSet.max("perfrankmgmt_topran_temp_"+tempIndex, "perfrank_topran_"+tempIndex);
            groupbyDataSet.max("perfrankmgmt_topranks_temp_"+tempIndex, "perfrank_topranks_"+tempIndex);
            tempIndex++;
        }
        return groupbyDataSet.finish();
    }


    /**
     * 获取近N年的岗位信息
     * 用于查询每个员工在指定年份范围内每年年底（12月31日）所在的有效岗位
     * 当一个员工在同一年有多个有效岗位时，选择结束日期最晚的那个岗位
     *
     * @param beginYear 起始年份（包含）
     * @param endYear   结束年份（包含）
     * @return 包含每个员工每年岗位信息的数据集
     */
    private DataSet getPositions(int beginYear,int endYear,Set<Long> personIds){
        // 查询全职任职关系，获取员工、岗位、任职起止时间等信息
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.STARTDATE)  // 任职开始日期
                .add(FormConstant.ENDDATE)    // 任职结束日期
                .addIdNumberName(FormConstant.POSITION_KEY)  // 岗位信息（ID、编码、名称）
                .addIdNumberNameWithExtras(new String[]{FormConstant.EMPLOYEE_KEY},FormConstant.EMP_NUMBER_KEY)  // 员工信息（ID、编码、姓名）+ 工号
                .orderDesc(FormConstant.EMPLOYEE_KEY,FormConstant.STARTDATE);  // 按员工ID和开始日期降序排列
        // 筛选条件：只查询全职任职（IS_PRIMARY = YES）
        QFilter qFilter = new QFilter(FormConstant.IS_PRIMARY,QCP.equals, EnableEnum.YES.getCode());
        if(!personIds.isEmpty()){
            qFilter = new QFilter(FormConstant.EMPLOYEE_KEY,QCP.in,personIds.toArray());
        }
        DataSet dataSet = QueryServiceHelper.queryDataSet("PrintPerfDetailReportListDataPlugin_EMPREL", FormConstant.HRPI_EMPPOSORGREL, queryFieldBuilder.buildSelect(), new QFilter[]{qFilter}, queryFieldBuilder.buildOrder(), 1000000);

        int tempIndex = 1;
        // 遍历指定年份范围，为每一年生成对应的岗位查询字段
        for (int year = beginYear; year <= endYear; year++) {
            // 获取每年12-31 23:59:59作为目标日期，用于判断该员工当年年底的岗位状态
            Date targetDate = DateUtil.toDate(LocalDateTime.of(year, 12, 31, 23, 59, 59));
            String targetDateStr = DateUtil.format(targetDate, DateUtil.NORM_DATE_PATTERN); // 使用日期格式而非日期时间格式

            // 创建复合字段：如果在目标日期员工处于有效任职状态，则生成"结束日期|岗位名称"格式的字符串
            // 这样使用GroupMaxStrFunction时，会根据结束日期选择最晚的那个任职记录
            //为什么用“00000000000000|”，不用null。因为当GroupMaxStrFunction进行字符串比较时，有效的日期值（如'20231231235959|经济技术部部长'）会比'00000000000000|'大，从而被正确选择
            String combinedField = "CASE WHEN " + FormConstant.STARTDATE + " <= to_date('" + targetDateStr + "','yyyy-MM-dd') " +
                    "AND " + FormConstant.ENDDATE + " >= to_date('" + targetDateStr + "','yyyy-MM-dd') " +
                    "THEN CONCAT(TO_CHAR(" + FormConstant.ENDDATE + ", 'YYYYMMDDHHmmss'), '|', " +
                    String.join(".", FormConstant.POSITION_KEY, FormConstant.NAME_KEY) + ") ELSE '00000000000000|' END";

            // 添加岗位复合字段（包含结束日期和岗位名称）
            dataSet = dataSet.addField(combinedField, "position_temp_" + tempIndex);

            // 同时创建仅包含日期部分的字段，用于后续解析时去除日期部分，只保留岗位名称
            String dateField = "CASE WHEN " + FormConstant.STARTDATE + " <= to_date('" + targetDateStr + "','yyyy-MM-dd') " +
                    "AND " + FormConstant.ENDDATE + " >= to_date('" + targetDateStr + "','yyyy-MM-dd') " +
                    "THEN CONCAT(TO_CHAR(" + FormConstant.ENDDATE + ", 'YYYYMMDDHHmmss'),'|') ELSE '00000000000000|' END";
            dataSet = dataSet.addField(dateField, "position_date_" + tempIndex);

//            dataSet = dataSet.addField("'"+year+"'", "position_year_" + tempIndex);
            tempIndex++;
        }

        // 行转列处理：按员工ID分组，使用GroupMaxStrFunction获取每个员工每年结束日期最晚的任职记录
        tempIndex = 1;
        GroupMaxStrFunction groupMaxStr = new GroupMaxStrFunction();
        // 按员工ID进行分组聚合
        GroupbyDataSet groupbyDataSet = dataSet.groupBy(new String[]{String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY)});
        // 对每一年的数据进行聚合，获取结束日期最晚的任职记录
        for (int year = beginYear; year <= endYear; year++) {
            // 获取岗位复合字段的最大值（即结束日期最晚的记录）
            groupbyDataSet.agg(new GroupMaxStrFunction(),"position_temp_"+tempIndex, "position_max_"+tempIndex);
            // 同时获取日期字段的最大值，用于后续解析
            groupbyDataSet.agg(groupMaxStr,"position_date_"+tempIndex, "position_date_max_"+tempIndex);
            tempIndex++;
        }
        DataSet result = groupbyDataSet.finish();

        // 解析复合字段，提取真正的岗位名称
        // 通过去除日期部分（YYYYMMDDHHmmss|）来获取原始的岗位名称
        tempIndex = 1;
        for (int year = beginYear; year <= endYear; year++) {
            final int currentYearIndex = year - beginYear + 1;
            result = result.addField(
                    // 如果岗位字段有效（不为默认值'00000000000000|'），则去除日期部分，只保留岗位名称
                    "CASE WHEN position_max_" + tempIndex + " IS NOT NULL AND position_max_" + tempIndex + " != '00000000000000|' THEN " +
                            "REPLACE(position_max_" + tempIndex + ",position_date_max_"+tempIndex+",'') " +  // 去除日期部分，得到岗位名称
                            "ELSE null END",
                    "position_" + tempIndex  // 最终的岗位名称字段
            );
            tempIndex++;
        }
        return result;
    }

    @Override
    public List<AbstractReportColumn> getColumns(List<AbstractReportColumn> columns) throws Throwable {
        // 获取5年前的年份
        int fiveYearsAgo = LocalDate.now().minusYears(5).getYear();
        int currentYear = LocalDate.now().getYear() - 1; // 不包含今年

        for (AbstractReportColumn column : columns) {
            if (column instanceof ReportColumn) {
                ReportColumn rColumn = (ReportColumn) column;
                String fieldKey = rColumn.getFieldKey();
                // 检查是否为年份相关的字段
                if (fieldKey != null && fieldKey.startsWith("nckd_year")) {
                    try {
                        // 提取年份索引（从字段名中提取数字）
                        int yearIndex = Integer.parseInt(fieldKey.replace("nckd_year", ""));
                        // 设置对应年份的标题
                        int displayYear = fiveYearsAgo + yearIndex - 1;
                        if(displayYear <= currentYear) {
                            rColumn.setCaption(new LocaleString(displayYear + "年"));
                            rColumn.setHide(false);
                        }
                    } catch (NumberFormatException ignored) {
                    }
                }
            }
        }
        return columns;
    }

    /**
     * 构建查询字段
     */
    private QueryFieldBuilder buildQueryFieldBuilder() {
        return QueryFieldBuilder.create()
                .add(PerfManagerFormConstant.NCKD_BEGINYEAR)
                .add(PerfManagerFormConstant.NCKD_ENDYEAR)
                .add(PerfManagerFormConstant.NCKD_ACTENDYEAR)
                .addGroup(new String[]{PerfManagerFormConstant.PERFMANAGERENTRY},PerfManagerFormConstant.NCKD_APPRAISALRESULT)
                .addIdNumberName(PerfManagerFormConstant.PERFMANAGERENTRY,PerfManagerFormConstant.NCKD_APPRAISALRESULT)
                .addGroup(new String[]{PerfManagerFormConstant.PERFMANAGERENTRY},PerfManagerFormConstant.NCKD_APPRAISALYEAR)
                .addGroup(new String[]{PerfManagerFormConstant.PERFMANAGERENTRY},PerfManagerFormConstant.ID_KEY)
                .addGroup(new String[]{FormConstant.NCKD_EMPPOSORGREL,FormConstant.EMPLOYEE_KEY}, FormConstant.EMP_NUMBER_KEY, FormConstant.NAME_KEY)
                .addIdNumberName(FormConstant.NCKD_PERSON)
                .add(String.join(".", FormConstant.NCKD_PERSON, FormConstant.NCKD_JOINWORKTIME))
                .add(String.join(".", FormConstant.NCKD_PERSON, FormConstant.BIRTHDAY))
                .add(String.join(".", FormConstant.NCKD_PERSON, FormConstant.GENDER,FormConstant.NAME_KEY))
                .add(String.join(".", FormConstant.HRPI_PEREDUEXP, FormConstant.EDUCATION_KEY,FormConstant.NAME_KEY))
                .addGroup(new String[]{FormConstant.HRPI_PERSERLEN},FormConstant.FIRSTJOINCOMDATE_KEY,FormConstant.JOINCOMDATE_KEY,FormConstant.STARTDATE)
                .addIdNumberName(FormConstant.HRPI_EMPENTREL,FormConstant.LABOR_REL_STATUS)
                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG,FormConstant.NCKD_FIRSTORG)
                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG,FormConstant.NCKD_SECONDORG)
                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG,FormConstant.NCKD_THIRDORG)
                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG,FormConstant.NCKD_FOURTHORG)
                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG,FormConstant.NCKD_FIFTHORG)
                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG,FormConstant.NCKD_SIXTHORG)
                .addIdNumberName( PerfManagerFormConstant.HRPI_EMPPOSORGREL, PerfManagerFormConstant.POSITION_KEY)
//                .addIdNumberName(FormConstant.HRPI_EMPPOSORGREL,FormConstant.POSITION_KEY)
                .addGroup(new String[]{"last_perfmanager"},
                        PerfManagerFormConstant.NCKD_BEGINYEAR,
                        PerfManagerFormConstant.NCKD_ENDYEAR)
                .addGroup(new String[]{PerfManagerFormConstant.DOCSTAMP_ENTITYID},PerfManagerFormConstant.NCKD_STAMPTIME,PerfManagerFormConstant.NCKD_FILEISSUETIME)
                .add(String.join(".", FormConstant.HRPI_PERPROTITLE, FormConstant.PROFESSIONAL_KEY,FormConstant.NAME_KEY))
                .add(String.join(".", FormConstant.NCKD_HRPI_EMPSKILL, FormConstant.NCKD_QUALINAME));

    }

    /**
     * 处理过滤条件
     */
    private void processFilter(ReportQueryParam reportQueryParam, QFilter qFilter) {
        List<QFilter> qFilters = reportQueryParam.getFilter().getQFilters();
            for (QFilter filter : qFilters) {
            //由于页面命名限制不允许配置对应数据库字段（例如：position.id的格式），这里只能手动转换为数据库实际的字段
            String property = filter.getProperty();
            if ("nckd_posstatus.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.HRPI_EMPPOSORGREL,FormConstant.POS_STATUS,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }else if("nckd_beginyearfilter".equalsIgnoreCase(property)){
                qFilter.and(new QFilter("last_perfmanager."+PerfManagerFormConstant.NCKD_BEGINYEAR,filter.getCP(),filter.getValue()));
            }else if("nckd_endyearfilter".equalsIgnoreCase(property)){
                qFilter.and(new QFilter("last_perfmanager."+PerfManagerFormConstant.NCKD_ENDYEAR,filter.getCP(),filter.getValue()));
            }else if("nckd_org.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".",FormConstant.HRPI_EMPPOSORGREL,FormConstant.ADMINORG),filter.getCP(),filter.getValue()));
            }else if("nckd_employee.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".",FormConstant.NCKD_EMPPOSORGREL,FormConstant.EMPLOYEE_KEY),filter.getCP(),filter.getValue()));
            }
        }
    }

    /**
     * 处理快速过滤条件
     */
    private void processFastFilter(ReportQueryParam reportQueryParam, QFilter qFilter) {
        FastFilter fastFilter = reportQueryParam.getFilter().getFastFilter();
        if (fastFilter != null) {
            List<Map<String, List<Object>>> fastFilterList = fastFilter.getFastFilter();
            for (Map<String, List<Object>> stringListMap : fastFilterList) {
                //nckd_empnumfastfilter转为employee.empnumber，nckd_namefastfilter转换为employee.name，转换后添加到fields中
                List<Object> fieldList = stringListMap.get("FieldName");
                List<Object> valueList = stringListMap.get("Value");
                String[] fields = new String[fieldList.size()];
                for (int i = 0; i < fieldList.size(); i++) {
                    fields[i] = fieldList.get(i).toString()
                            .replace("nckd_empnumfastfilter", String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.EMPLOYEE_KEY,FormConstant.EMP_NUMBER_KEY))
                            .replace("nckd_namefastfilter", String.join(".", FormConstant.HRPI_EMPPOSORGREL, FormConstant.EMPLOYEE_KEY,FormConstant.NAME_KEY));
                }
                //valueList转到values
                String[] values = new String[valueList.size()];
                for (int i = 0; i < valueList.size(); i++) {
                    values[i] = valueList.get(i).toString();
                }
                QFilter orFilter = null;
                for (String field : fields) {
                    for (String value : values) {
                        if (orFilter == null) {
                            orFilter = new QFilter(field, QCP.like, "%" + value + "%");
                        } else {
                            orFilter = orFilter.or(field, QCP.like, "%" + value + "%");
                        }
                    }

                }

               if(orFilter != null) {
                   qFilter.and(orFilter);
               }
            }
        }
    }

    /**
     * 处理过滤条件
     */
   /* private void processFilter(ReportQueryParam reportQueryParam, QFilter qFilter) {
        List<QFilter> qFilters = reportQueryParam.getFilter().getQFilters();
        for (QFilter filter : qFilters) {
            //由于页面命名限制不允许配置对应数据库字段（例如：position.id的格式），这里只能手动转换为数据库实际的字段
            String property = filter.getProperty();
            if ("nckd_positionfilter.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.POSITION_KEY, FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }else if("nckd_orgfilter.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.COMPANY_KEY, FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }else if("nckd_joblevelhrffilter.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_JOBLEVELHR,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }else if("nckd_begindatefilter".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_BEGINDATE),filter.getCP(),filter.getValue()));
            }
        }
    }*/


}