package nckd.jxccl.hr.psms.plugin.form.adjust.report;

import kd.bos.algo.DataSet;
import kd.bos.common.enums.EnableEnum;
import kd.bos.context.RequestContext;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.FastFilter;
import kd.bos.entity.report.FilterItemInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.ORMHint;
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.sdk.hr.hbp.business.helper.permission.HRPermissionServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 未生成动态调整-查询插件
 * @author W.Y.C
 * @date 2025/10/10 19:51
 * @version 1.0
 */
public class UnAdjustedReportReportListDataPlugin extends AbstractReportListDataPlugin {
    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {
        // 构建查询字段
        QueryFieldBuilder queryFieldBuilder = buildQueryFieldBuilder();

        // 构建基础查询条件
        QFilter qFilter = buildBaseQueryFilter();

        // 处理快速过滤条件
        processFastFilter(reportQueryParam, qFilter);

        //其他过滤条件
        processFilter(reportQueryParam, qFilter);
        //权限过滤
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_psmsfile", "unadjustquery",
                PermissionStatus.View, new HashMap<>());
        if(dataRule != null){
            qFilter.and(dataRule);
        }


        // 执行基础查询
        DataSet dataSet = QueryServiceHelper.queryDataSet(PositionStructureConstant.PERSONPOSFILE_ENTITYID, "unadjustquery",
                queryFieldBuilder.buildSelect(), new QFilter[]{qFilter}, null,100000);

        // 添加扩展过滤条件
        DataSet filteredDataSet = addExtendedFilters(dataSet);

        // 添加调整类型字段
        DataSet dataSetWithAdjustTypes = addAdjustTypeFields(filteredDataSet);

        // 处理报表过滤条件
        String filterCondition = processOtherFilter(reportQueryParam);

        return dataSetWithAdjustTypes.filter(filterCondition);
    }

    /**
     * 构建查询字段
     */
    private QueryFieldBuilder buildQueryFieldBuilder() {
        return QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .addGroup(new String[]{FormConstant.EMPLOYEE_KEY}, FormConstant.EMP_NUMBER_KEY, FormConstant.NAME_KEY)
                .addGroup(new String[]{PositionStructureConstant.PERSONPOSFILE_ENTITYID},
                        PositionStructureConstant.NCKD_POSITIONHR,
                        PositionStructureConstant.NCKD_JOBSEQHR,
                        PositionStructureConstant.NCKD_PROTITLELEVEL,
                        PositionStructureConstant.NCKD_OCPQUALLEVEL,
                        PositionStructureConstant.NCKD_DIPLOMA,
                        PositionStructureConstant.NCKD_ALLSUMSCORE,
                        PositionStructureConstant.NCKD_BEGINDATE,
                        PositionStructureConstant.NCKD_JOBLEVELHR,
                        PositionStructureConstant.NCKD_PERSON,
                        PositionStructureConstant.NCKD_DEP,
                        PositionStructureConstant.NCKD_ALLOWANCERANKMARK,
                        PositionStructureConstant.NCKD_ALLOWANCERANKSEL,
                        PositionStructureConstant.NCKD_COEFFICIENT,
                        PositionStructureConstant.NCKD_CURRENTPOSTSALARY,
                        PositionStructureConstant.NCKD_POSTALLOWANCE
                )
                .addGroup(new String[]{PositionStructureConstant.PERSONPOSFILE_ENTITYID,PositionStructureConstant.NCKD_DEP},"belongcompany")
                .addGroup(new String[]{FormConstant.HRPI_PERPROTITLE}, FormConstant.PROLEVEL_KEY)
                .addGroup(new String[]{FormConstant.HRPI_PEROCPQUAL}, FormConstant.QUALIFICATION_KEY)
                .addGroup(new String[]{FormConstant.HRPI_PEREDUEXP}, FormConstant.EDUCATION_KEY)
                .add(FormConstant.COMPANY_KEY)
                .addIdNumberName(FormConstant.COMPANY_KEY)
                .add(FormConstant.ADMINORG)
                .addIdNumberName(FormConstant.POSITION_KEY)
                .addGroup(new String[]{FormConstant.HBPM_POSITIONHR}, PositionStructureConstant.NCKD_JOBSEQ)
                .addGroup(new String[]{FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ}, FormConstant.NUMBER_KEY)
                .addGroup(new String[]{FormConstant.ADMINORG},
                        FormConstant.NCKD_FIRSTORG,
                        FormConstant.NCKD_SECONDORG,
                        FormConstant.NCKD_THIRDORG,
                        FormConstant.NCKD_FOURTHORG,
                        FormConstant.NCKD_FIFTHORG,
                        FormConstant.NCKD_SIXTHORG);

    }

    /**
     * 构建基础查询条件
     */
    private QFilter buildBaseQueryFilter() {
        return new QFilter(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID,
                PositionStructureConstant.NCKD_ISCURRENTNEWEST), QCP.equals, EnableEnum.YES.getCode())
                .and(new QFilter(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID,
                        PositionStructureConstant.NCKD_DISABLE), QCP.equals, EnableEnum.NO.getCode()))
                .and(new QFilter(String.join(".", FormConstant.ASSIGNMENT, FormConstant.IS_PRIMARY),
                        QCP.equals, EnableEnum.YES.getCode()))
                .and(new QFilter(FormConstant.IS_PRIMARY, QCP.equals, EnableEnum.YES.getCode()))
                .and(FormConstant.IS_SEQLATESTRECORD, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.IS_DELETED, QCP.equals, EnableEnum.NO.getCode())
                .and(QFilter.join(FormConstant.EMPLOYEE_KEY, String.join(".", FormConstant.HRPI_PERPROTITLE, FormConstant.EMPLOYEE_KEY), new QFilter(String.join(".", FormConstant.HRPI_PERPROTITLE, "iscompany"),
                                QCP.equals, EnableEnum.YES.getCode()),
                        ORMHint.JoinHint.LEFT, Boolean.FALSE))
                .and(QFilter.join(FormConstant.EMPLOYEE_KEY, String.join(".", FormConstant.HRPI_PEROCPQUAL, FormConstant.EMPLOYEE_KEY), new QFilter(String.join(".", FormConstant.HRPI_PEROCPQUAL, "ismajor"),
                                QCP.equals, EnableEnum.YES.getCode()),
                        ORMHint.JoinHint.LEFT, Boolean.FALSE))
                .and(QFilter.join(FormConstant.EMPLOYEE_KEY, String.join(".", FormConstant.HRPI_PEREDUEXP, FormConstant.EMPLOYEE_KEY), new QFilter(String.join(".", FormConstant.HRPI_PEREDUEXP, "ishighestdegree"),
                                QCP.equals, EnableEnum.YES.getCode()),
                        ORMHint.JoinHint.LEFT, Boolean.FALSE))
                //在岗
                .and(String.join( ".", FormConstant.POS_STATUS, FormConstant.POST_STATE_CLS, FormConstant.NUMBER_KEY),QCP.equals,"1010_S");
    }

    /**
     * 处理快速过滤条件
     */
    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", "employee.empnumber")
                            .replace("nckd_namefastfilter", "employee.name");
                }
                //valueList转到values
                String[] values = new String[valueList.size()];
                for (int i = 0; i < valueList.size(); i++) {
                    values[i] = valueList.get(i).toString();
                }
                qFilter.and(QFilter.ftlike(values, fields));
            }
        }
    }

    /**
     * 处理过滤条件
     */
    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()));
            }
        }
    }

    /**
     * 添加扩展过滤条件
     */
    private DataSet addExtendedFilters(DataSet dataSet) {
        StringJoiner filters = new StringJoiner(" and ");
        //职位档案不为空
        filters.add(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_PERSON) + " is not null");

        StringJoiner joinOr = new StringJoiner(" or ");
        //职称等级变化
        joinOr.add("(" + String.join(".", FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ, FormConstant.NUMBER_KEY) + " <> '03' and " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_PROTITLELEVEL) + " <> " +
                String.join(".", FormConstant.HRPI_PERPROTITLE, FormConstant.PROLEVEL_KEY) + ")");
        //技能等级变化
        joinOr.add("(" + String.join(".", FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ, FormConstant.NUMBER_KEY) + " = '03' and " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_OCPQUALLEVEL) + " <> " +
                String.join(".", FormConstant.HRPI_PEROCPQUAL, FormConstant.QUALIFICATION_KEY) + ")");
        //学历变化
        joinOr.add(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_DIPLOMA) + " <> " +
                String.join(".", FormConstant.HRPI_PEREDUEXP, FormConstant.EDUCATION_KEY));
        //公司变化
        joinOr.add(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, FormConstant.NCKD_DEP,"belongcompany") + " <> " + FormConstant.COMPANY_KEY);
        //序列变化
        joinOr.add(String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_JOBSEQHR) + " <> " +
                String.join(".", FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ));

        filters.add("(" + joinOr.toString() + ")");
        return dataSet.filter(filters.toString());
    }

    /**
     * 添加调整类型字段
     */
    private DataSet addAdjustTypeFields(DataSet dataSet) {
        DataSet newDataSet = dataSet.addField("CASE WHEN " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_DIPLOMA) +
                " <> " +
                String.join(".", FormConstant.HRPI_PEREDUEXP, FormConstant.EDUCATION_KEY) +
                " THEN '学历变化' END", "a");

        newDataSet = newDataSet.addField("CASE WHEN (" +
                String.join(".", FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ, FormConstant.NUMBER_KEY) +
                " <> '03' and " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_PROTITLELEVEL) +
                " <> " +
                String.join(".", FormConstant.HRPI_PERPROTITLE, FormConstant.PROLEVEL_KEY) +
                ") THEN '职称变化' END", "b");

        newDataSet = newDataSet.addField("CASE WHEN (" +
                String.join(".", FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ, FormConstant.NUMBER_KEY) +
                " = '03' and " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_OCPQUALLEVEL) +
                " <> " +
                String.join(".", FormConstant.HRPI_PEROCPQUAL, FormConstant.QUALIFICATION_KEY) +
                ") THEN '技能变化' END", "c");

        newDataSet = newDataSet.addField("CASE WHEN " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, FormConstant.NCKD_DEP,"belongcompany") +
                " <> " + FormConstant.COMPANY_KEY +
                " THEN '跨单位变动' END", "d");

        newDataSet = newDataSet.addField("CASE WHEN " +
                String.join(".", PositionStructureConstant.PERSONPOSFILE_ENTITYID, PositionStructureConstant.NCKD_JOBSEQHR) +
                " <> " +
                String.join(".", FormConstant.HBPM_POSITIONHR, PositionStructureConstant.NCKD_JOBSEQ) +
                " THEN '跨序列变动' END", "f");

        // 合并调整类型字符串
        newDataSet = newDataSet.addField(buildAdjustTypeConcatExpression(), "nckd_adjusttypestr");
        return newDataSet;
    }

    /**
     * 构建调整类型连接表达式
     */
    private String buildAdjustTypeConcatExpression() {
        return "CONCAT(" +
                "CASE WHEN a IS NOT NULL AND a != '' THEN CONCAT(a,',') ELSE '' END," +
                "CASE WHEN b IS NOT NULL AND b != '' THEN CONCAT(b,',') ELSE '' END," +
                "CASE WHEN c IS NOT NULL AND c != '' THEN CONCAT(c,',') ELSE '' END," +
                "CASE WHEN d IS NOT NULL AND d != '' THEN CONCAT(d,',') ELSE '' END," +
                "CASE WHEN f IS NOT NULL AND f != '' THEN CONCAT(f,',') ELSE '' END" +
                ")";
    }

    /**
     * 处理报表过滤条件
     */
    private String processOtherFilter(ReportQueryParam reportQueryParam) {
        StringJoiner joinAnd = new StringJoiner(" and ");
        joinAnd.add("1=1");

        List<FilterItemInfo> filterItems = reportQueryParam.getFilter().getFilterItems();
        for (FilterItemInfo filterItem : filterItems) {
            String propName = filterItem.getPropName();
            if ("nckd_adjusttypefilter".equalsIgnoreCase(propName)) {
                processAdjustTypeFilter(filterItem, joinAnd);
            }
        }

        return joinAnd.toString();
    }

    /**
     * 处理调整类型过滤条件
     */
    private void processAdjustTypeFilter(FilterItemInfo filterItem, StringJoiner joinAnd) {
        if (filterItem.getValue() instanceof List) {
            List<String> values = ConvertUtil.toList(filterItem.getValue());
            StringJoiner or = new StringJoiner(" or ");
            for (String value : values) {
                or.add("nckd_adjusttypestr like '%" + value + "%'");
            }
            joinAnd.add("(" + or.toString() + ")");
        } else {
            joinAnd.add("nckd_adjusttypestr like '%" + filterItem.getValue() + "%'");
        }
    }

}