package nckd.jxccl.hr.hstu.plugin.operate;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.hr.hstu.business.helper.HonorStudentHelper;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* 【优秀生】-综合测评问卷-发起评测操作插件
* @author W.Y.C
* @date 2025/8/15 16:58
* @version 1.0
*/
public class EvalQuestBeginEvalOperationPlugin extends AbstractOperationServicePlugIn implements Plugin {

    private static final Log logger = LogFactory.getLog(EvalQuestBeginEvalOperationPlugin.class);

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {

        DynamicObject[] selectedRows = e.getDataEntities();
        if (selectedRows != null && selectedRows.length > 0) {
            List<Long> selectedRowIds = new ArrayList<>(selectedRows.length);
            for (DynamicObject row : selectedRows) {
                // 获取单据ID（主键）
                Long id = (Long) row.getPkValue();
                selectedRowIds.add(id);
            }
            beginEval(selectedRowIds);
        }
    }


    /**
     * 发起评测
     * @return: void
     * @author W.Y.C
     * @date: 2025/07/23 17:20
     */
    private void beginEval(List<Long> selectedRowIds) {
        logger.info("【优秀生考评】-发起评测-开始");
        //查询问卷信息
        HonorStudentHelper.Result result = HonorStudentHelper.getEvalQuest(selectedRowIds);
        logger.info("【优秀生考评】-发起评测-选择的问卷ID：{}",result.selectedRowIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
        // ===================== 1.校验状态 =====================
        StringJoiner errorJoin = new StringJoiner("\n");
        Arrays.stream(result.evalQuestArray).forEach(evalQuest -> {
            String periodState = evalQuest.getString(HonorStudentConstant.NCKD_PERIODSTATE);
            if(!periodState.equals("3")){
                DynamicObject person = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getDynamicObject(FormConstant.PERSON);
                errorJoin.add(StrFormatter.format("评价对象【{}】的测评状态非【已就绪】状态，只有【已就绪】状态的才能发起测评",person.getString(FormConstant.NAME_KEY)));
            }
        });
        if(errorJoin.length() > 0){
            logger.warn("【优秀生考评】-发起评测-业务校验异常：{}",errorJoin.toString());
            throw new ValidationException(errorJoin.toString());
        }

        // ===================== 2.更新问卷状态 & 地区差异分（地区差异分 * 评价规则.地区差异权重占比 * 0.01） & 更新未评分人数 =====================
        List<Long> ruleIds = Arrays.stream(result.evalQuestArray).map(evalQuest -> evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE).getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
        StringJoiner ruleColum = new StringJoiner(",");
        ruleColum.add(FormConstant.ID_KEY);
        //地区差异权重占比（%）
        ruleColum.add(HonorStudentConstant.NCKD_DIFFPROPORTION);
        //查询评价规则
        DynamicObject[] ruleArray = BusinessDataServiceHelper.load(HonorStudentConstant.EVALUATIONRULE_ENTITYID, ruleColum.toString(), new QFilter[]{QFilterCommonHelper.getIdInFilter(ruleIds)});
        Map<Long, Integer> ruleMap = Arrays.stream(ruleArray)
                .collect(Collectors.toMap(
                        rule -> rule.getLong(FormConstant.ID_KEY),
                        rule -> rule.getInt(HonorStudentConstant.NCKD_DIFFPROPORTION),
                        (existingValue, replacementValue) -> existingValue
                ));

        for (DynamicObject evalQuest : result.evalQuestArray) {
            //问卷修改为进行中
            evalQuest.set(HonorStudentConstant.NCKD_PERIODSTATE,"1");
            //HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.PERSON+"."+FormConstant.NAME_KEY
            Long evalPersonId = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getDynamicObject(FormConstant.PERSON).getLong(FormConstant.ID_KEY);
            String evalPersonName = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getDynamicObject(FormConstant.PERSON).getString(FormConstant.NAME_KEY);
            //地区差异分（地区差异分 * 评价规则.地区差异权重占比 * 0.01）
            long adminId = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getDynamicObject(FormConstant.ADMINORG).getLong(FormConstant.ID_KEY);
            String adminName = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getDynamicObject(FormConstant.ADMINORG).getString(FormConstant.NAME_KEY);
            Integer orgDifference = HonorStudentHelper.getOrgDifference(adminId);
            if(orgDifference != null){
                long ruleId = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE).getLong(HonorStudentConstant.ID_KEY);
                Integer diffProportion = ruleMap.get(ruleId);
                double differenceScore = orgDifference * (diffProportion == null ? 0 : diffProportion) * 0.01;
                evalQuest.set(HonorStudentConstant.NCKD_DIFFERENCESCORE,differenceScore);
                logger.info("【优秀生考评】-发起评测-评价对象【{}({})】-部门【{}({})】-地区差异权重占比：{}，地区差异分：{}，换算后：{}",evalPersonName,evalPersonId,adminName,adminId,diffProportion,orgDifference,differenceScore);
            }else{
                logger.info("【优秀生考评】-发起评测-评价对象【{}({})】-部门【{}({})】-无地区差异分",evalPersonName,evalPersonId,adminName,adminId);
            }

            //更新：已评分人员、未评分人数
            long evalQuestId = evalQuest.getLong(FormConstant.ID_KEY);
            Integer questScorePersonCount = HonorStudentHelper.getQuestScorePersonCount(evalQuestId);
            Integer quesNotScorePersonCount = HonorStudentHelper.getQuestNotScorePersonCount(evalQuestId);
            evalQuest.set(HonorStudentConstant.NCKD_HAVEDO,questScorePersonCount);
            evalQuest.set(HonorStudentConstant.NCKD_NODO,quesNotScorePersonCount);
        }


        // ===================== 3.更新答卷状态（答卷修改为：待评分） =====================
        DynamicObject[] evalResultArray = BusinessDataServiceHelper.load(HonorStudentConstant.NCKD_EVALRESULT_ENTITYID,
                "id,nckd_perfplanstate",
                new QFilter[]{new QFilter(HonorStudentConstant.NCKD_EVALQUEST, QCP.in, result.selectedRowIds)});
        for (DynamicObject evalResult : evalResultArray) {
            //答卷修改为待评分
            evalResult.set(HonorStudentConstant.NCKD_PERFPLANSTATE,"1");
        }

        SaveServiceHelper.update(result.evalQuestArray);
        SaveServiceHelper.update(evalResultArray);
        logger.info("【优秀生考评】-发起评测-完成");
    }
}