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

import kd.bos.algo.DataSet;
import kd.bos.algo.GroupbyDataSet;
import kd.bos.algo.JoinType;
import kd.bos.algo.Row;
import kd.bos.consts.PermItemConst;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
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.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.hr.hbp.common.model.AuthorizedOrgResultWithSub;
import kd.hr.hbp.common.model.OrgSubInfo;
import kd.sdk.hr.hbp.business.helper.permission.HRPermissionServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.algo.GroupMaxStrFunction;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* 关键行为评价报表查询插件
* 该插件用于查询和展示关键行为评价结果，支持动态列和行转列功能
* 实体标识：nckd_keybehavevalrept
* @author W.Y.C
* @date 2025/12/27 18:05
* @version 1.0
*/
public class KeyBeHavEvalReptQueryPlugin extends AbstractReportListDataPlugin implements Plugin {

    // 常量定义
    private static final String PERSON_ID_FIELD = String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY);
    private static final String PROJECT_NUMBER_FIELD = String.join(".", PositionStructureConstant.NCKD_KEYBEHAVCONFENTRY, FormConstant.NUMBER_KEY);
    private static final String PROJECT_NAME_FIELD = String.join(".", PositionStructureConstant.NCKD_KEYBEHAVCONFENTRY, FormConstant.NAME_KEY);
    private static final String RESULT_FIELD = "case when "+PositionStructureConstant.NCKD_RESULT+" = '1' then '满足' else '不满足' end";

//    private static final String RESULT_FIELD = PositionStructureConstant.NCKD_RESULT;

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

    /**
     * 查询报表数据
     * 实现行转列逻辑，将评价项目结果转换为报表列
     */
    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {

        // 1. 获取权限范围内的组织ID
//        List<Long> authorizedOrgIds = getAuthorizedOrgIds();
        
        // 2. 查询关键行为评价项目结果数据
        DataSet keyBeHavEvalProjRsltDataSet = queryKeyBeHavEvalProjRsltDataSet();
        
        // 3. 获取唯一项目编号（需要用于动态列的项目）
        Set<String> uniqueProjectNumbers = extractUniqueProjectNumbers(keyBeHavEvalProjRsltDataSet);
        
        // 4. 行转列处理
        DataSet pivotResultDataSet = transformRowsToColumns(keyBeHavEvalProjRsltDataSet, uniqueProjectNumbers);

        // 5. 查询主表数据
        // 处理快速过滤条件
        QFilter qFilter = QFilter.of("1=1");
        //按权限范围过滤
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_psmsfile", PositionStructureConstant.PERSONPOSFILE_ENTITYID,
                PermItemConst.ITEM_VIEW, new HashMap<>());
        if (dataRule != null) {
//            Object value = dataRule.getValue();
            qFilter.and(dataRule);
        }

        processFastFilter(reportQueryParam, qFilter);
        //其他过滤条件
        processFilter(reportQueryParam, qFilter);

        DataSet mainTableDataSet = queryMainTableDataSet(qFilter);
        mainTableDataSet.print(true);

        // 6. 关联主表和行转列结果
        DataSet finalResultDataSet = joinMainAndPivotData(mainTableDataSet, pivotResultDataSet);
        
        return finalResultDataSet;
    }

    /**
     * 获取报表列定义
     * 根据数据库中的项目动态生成报表列
     */
    @Override
    public List<AbstractReportColumn> getColumns(List<AbstractReportColumn> columns) throws Throwable {
        
        // 获取唯一项目信息
        List<ProjectInfo> projectInfoList = getUniqueProjectInfo();
        
        // 为每个唯一项目创建列
        for (ProjectInfo projectInfo : projectInfoList) {
            ReportColumn newColumn = createReportColumn(projectInfo);
            columns.add(newColumn);
        }
        
        return columns;
    }

    /**
     * 创建报表列
     */
    private ReportColumn createReportColumn(ProjectInfo projectInfo) {
        ReportColumn column = new ReportColumn();
        column.setCaption(new LocaleString(projectInfo.getProjectName()));
        column.setFieldKey("p_"+projectInfo.getProjectNumber());
        column.setFieldType(ReportColumn.TYPE_TEXT);
        return column;

/*
        // 1. 创建下拉列表列
        ComboReportColumn comboColumn = new ComboReportColumn();
        // 2. 设置关键属性
        comboColumn.setFieldKey("fruitname"); // 与查询结果字段对应
        comboColumn.setFieldType(ReportColumn.TYPE_COMBO); // 类型必须为 COMBO
        comboColumn.setCaption(new LocaleString("水果名称")); // 列标题

        // 3. （可选）设置下拉选项。这里示例是静态的，实际可从数据库或上下文动态获取。
        List<ValueMapItem> items = new ArrayList<>();
        items.add(new ValueMapItem("apple", "苹果"));
        items.add(new ValueMapItem("banana", "香蕉"));
        comboColumn.setComboItems(items);

        // 4. 将列添加到列集合
        columns.add(comboColumn);*/
    }

    /**
     * 获取项目信息列表
     */
    private List<ProjectInfo> getUniqueProjectInfo() {
        QueryFieldBuilder resultFieldBuilder = createResultFieldBuilder();
//        QFilter filter = createOrgFilter(orgIds);

        QFilter filter = QFilter.of("1=1");
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_psmsfile", PositionStructureConstant.PERSONPOSFILE_ENTITYID,
                PermItemConst.ITEM_VIEW, new HashMap<>());
        if (dataRule != null) {
            Object value = dataRule.getValue();
            filter.and(String.join(".",PositionStructureConstant.NCKD_KEYBEHAVCONFENTRY,"nckd_keybehavconf",FormConstant.NCKD_ORG, FormConstant.ID_KEY), QCP.in, value);
            filter.and(String.join(".",FormConstant.NCKD_PERSON,FormConstant.HRPI_EMPPOSORGREL, FormConstant.ADMINORG), QCP.in, value);
        }
        DynamicObjectCollection keyBeHavEvalProjRslt = QueryServiceHelper.query(
                PositionStructureConstant.KEYBEHAVEVALPROJRSLT_ENTITYID, 
                resultFieldBuilder.buildSelect(), 
                new QFilter[]{filter}
        );
        
        // 根据项目编码去重
        Set<String> processedProjectNumbers = new HashSet<>();
        List<ProjectInfo> uniqueProjectList = new ArrayList<>();
        for (DynamicObject obj : keyBeHavEvalProjRslt) {
            String projectNumber = obj.getString(PROJECT_NUMBER_FIELD);
            String projectName = obj.getString(PROJECT_NAME_FIELD);
            
            if (projectNumber != null && processedProjectNumbers.add(projectNumber)) {
                uniqueProjectList.add(new ProjectInfo(projectNumber, projectName));
            }
        }
        
        return uniqueProjectList;
    }

    /**
     * 获取用户有权限的组织ID列表
     */
    private List<Long> getAuthorizedOrgIds() {
        Long currentUserId = RequestContext.get().getCurrUserId();
        AuthorizedOrgResultWithSub userAdminOrgWithSub = HRPermissionServiceHelper.getUserAdminOrgsWithSub(
                currentUserId, "nckd_psmsbase", "nckd_keybehavconf",
                PermItemConst.ITEM_VIEW, "nckd_org", new HashMap<>());

        if (userAdminOrgWithSub.isHasAllOrgPerm()) {
            return new ArrayList<>(); // 如果有所有组织权限，返回空列表表示无限制
        }
        
        return extractOrgIds(userAdminOrgWithSub.getHasPermOrgsWithSub());
    }

    /**
     * 查询关键行为评价项目结果数据集
     */
    private DataSet queryKeyBeHavEvalProjRsltDataSet() {
        QueryFieldBuilder resultFieldBuilder = createResultFieldBuilder();
//        QFilter filter = createOrgFilter(orgIds);
        QFilter filter = QFilter.of("1=1");
        QFilter dataRule = HRPermissionServiceHelper.getDataRule(
                RequestContext.get().getCurrUserId(), "nckd_psmsfile", PositionStructureConstant.PERSONPOSFILE_ENTITYID,
                PermItemConst.ITEM_VIEW, new HashMap<>());
        if (dataRule != null) {
            Object value = dataRule.getValue();
            filter.and("nckd_person.hrpi_empposorgrel.adminorg",QCP.in, value);
        }
        return QueryServiceHelper.queryDataSet(this.getClass().getName(),
                PositionStructureConstant.KEYBEHAVEVALPROJRSLT_ENTITYID, 
                resultFieldBuilder.buildSelect(), 
                new QFilter[]{filter}, 
                null);
    }

    /**
     * 创建结果字段构建器
     */
    private QueryFieldBuilder createResultFieldBuilder() {
        return QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .addIdNumberName(FormConstant.NCKD_PERSON)
                .addIdNumberName(PositionStructureConstant.NCKD_KEYBEHAVCONFENTRY)
                .add(PositionStructureConstant.NCKD_RESULT);
    }


    /**
     * 提取唯一的项目编号
     */
    private Set<String> extractUniqueProjectNumbers(DataSet keyBeHavEvalProjRsltDataSet) {
        DataSet copyDataSet = keyBeHavEvalProjRsltDataSet.copy();
        Set<String> uniqueProjectNumbers = new HashSet<>();
        
        while (copyDataSet.hasNext()) {
            Row row = copyDataSet.next();
            String projectNumber = row.getString(PROJECT_NUMBER_FIELD);
            if (projectNumber != null) {
                uniqueProjectNumbers.add(projectNumber);
            }
        }
        
        return uniqueProjectNumbers;
    }

    /**
     * 将行数据转换为列数据（行转列）
     */
    private DataSet transformRowsToColumns(DataSet originalDataSet, Set<String> projectNumbers) {
        DataSet workingDataSet = originalDataSet;
        
        // 为每个项目编号添加计算字段（行转列）
        List<String> columnFieldNames = new ArrayList<>();
        for (String projectNumber : projectNumbers) {
            String caseExpression = String.format(
                "CASE WHEN %s = '%s' THEN %s ELSE '' END",
                PROJECT_NUMBER_FIELD,
                projectNumber,
                RESULT_FIELD
            );
            
            workingDataSet = workingDataSet.addField(caseExpression, "p_"+projectNumber);
            columnFieldNames.add("p_"+projectNumber);
        }

        GroupMaxStrFunction groupMaxStr = new GroupMaxStrFunction();
        GroupbyDataSet groupbyDataSet = workingDataSet.groupBy(new String[]{PERSON_ID_FIELD});
        for (String projectNumber : projectNumbers) {
            groupbyDataSet
                    .agg(groupMaxStr,"p_"+projectNumber, "p_"+projectNumber);
        }
        // 添加人员ID字段用于关联
        columnFieldNames.add(PERSON_ID_FIELD);
        return groupbyDataSet.finish();
    }

    /**
     * 查询主表数据
     */
    private DataSet queryMainTableDataSet(QFilter qFilter) {


        QueryFieldBuilder queryFieldBuilder = buildQueryFieldBuilder();
        return QueryServiceHelper.queryDataSet("KeyBeHavEvalReptQueryPlugin", 
                PositionStructureConstant.KEYBEHAVEVAL_ENTITYID, 
                queryFieldBuilder.buildSelect(),
                new QFilter[]{qFilter},
                queryFieldBuilder.buildOrder());
    }

    /**
     * 关联主表和行转列结果
     */
    private DataSet joinMainAndPivotData(DataSet mainTableDataSet, DataSet pivotDataSet) {
        String[] mainTableFieldNames = mainTableDataSet.getRowMeta().getFieldNames();
        String[] pivotFieldNames = pivotDataSet.getRowMeta().getFieldNames();
        
        return mainTableDataSet.join(pivotDataSet, JoinType.LEFT)
                .on(String.join(".", FormConstant.NCKD_PERSON), 
                    PERSON_ID_FIELD)
                .select(mainTableFieldNames, pivotFieldNames)
                .finish();
    }

    /**
     * 构建主表查询字段
     */
    private QueryFieldBuilder buildQueryFieldBuilder() {
        return QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.NCKD_PERSON)
                .add(FormConstant.NCKD_DEP)
                .add(FormConstant.NCKD_DEP, FormConstant.NCKD_FIRSTORG)
                .add(FormConstant.NCKD_DEP, FormConstant.NCKD_SECONDORG)
                .add(FormConstant.NCKD_DEP, FormConstant.NCKD_THIRDORG)
                .add(FormConstant.NCKD_DEP, FormConstant.NCKD_FOURTHORG)
                .add(FormConstant.NCKD_DEP, FormConstant.NCKD_FIFTHORG)
                .add(FormConstant.NCKD_DEP, FormConstant.NCKD_SIXTHORG)
                .add(FormConstant.NCKD_JOBSEQ)
                .add(PositionStructureConstant.NCKD_POSITION)
                .add(PositionStructureConstant.NCKD_JOBLEVEL)
                .add(PositionStructureConstant.NCKD_APPRAISALRESULT)
                .add(PositionStructureConstant.NCKD_APPOINT)
                .add(PositionStructureConstant.NCKD_MATCHCONDDESC)
                .orderDesc(String.join(".",FormConstant.NCKD_PERSON,FormConstant.EMP_NUMBER_KEY))
                .orderAsc(PositionStructureConstant.NCKD_JOBLEVEL);
    }

    /**
     * 提取组织ID列表
     */
    private static List<Long> extractOrgIds(List<OrgSubInfo> orgSubInfos) {
        return orgSubInfos.stream()
                .map(OrgSubInfo::getOrgId)
                .collect(Collectors.toList());
    }

    /**
     * 项目信息内部类
     */
    private static class ProjectInfo {
        private final String projectNumber;
        private final String projectName;

        public ProjectInfo(String projectNumber, String projectName) {
            this.projectNumber = projectNumber;
            this.projectName = projectName;
        }

        public String getProjectNumber() {
            return projectNumber;
        }

        public String getProjectName() {
            return projectName;
        }
    }

    /**
     * 关键行为评价项目结果值对象（保留原有类，用于兼容性）
     */
    class KeyBeHavEvalProjRsltVo {
        private Long personId;
        private String projectNumber;
        private String projectName;
        private String projectResult;

        public KeyBeHavEvalProjRsltVo(Long personId, String projectNumber, String projectName, String projectResult) {
            this.personId = personId;
            this.projectNumber = projectNumber;
            this.projectName = projectName;
            this.projectResult = projectResult;
        }
    }

    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.NCKD_PERSON,FormConstant.EMP_NUMBER_KEY))
                            .replace("nckd_namefastfilter", String.join(".", FormConstant.NCKD_PERSON,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_secondorg.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.NCKD_DEP,FormConstant.NCKD_SECONDORG,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }
            if ("nckd_thirdorg.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.NCKD_DEP,FormConstant.NCKD_THIRDORG,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }
            if ("nckd_fourthorg.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.NCKD_DEP,FormConstant.NCKD_FOURTHORG,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }
            if ("nckd_fifthorg.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.NCKD_DEP,FormConstant.NCKD_FIFTHORG,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }
            if ("nckd_sixthorg.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.NCKD_DEP,FormConstant.NCKD_SIXTHORG,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }
            if ("nckd_position.id".equalsIgnoreCase(property)){
                qFilter.and(new QFilter(String.join(".", FormConstant.NCKD_POSITION_KEY,FormConstant.ID_KEY),filter.getCP(),filter.getValue()));
            }
        }
    }
}