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.hr.hstu.business.helper.HonorStudentHelper;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
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 EvalQuestEndEvalOperationPlugin extends AbstractOperationServicePlugIn implements Plugin {

    private static final Log logger = LogFactory.getLog(EvalQuestEndEvalOperationPlugin.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);
            }
            endEval(selectedRowIds);
        }
    }


    /**
     * 结束评测
     * @return: void
     * @author W.Y.C
     * @date: 2025/07/23 21:15
     */
    private void endEval(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("1")){
                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.判断是否存在未评分的评价对象 =====================
        DynamicObject[] questNotScorePerson = HonorStudentHelper.getQuestNotScorePerson(result.selectedRowIds.toArray(new Long[0]));
        if(questNotScorePerson.length > 0){
            errorJoin.add("未完成所有评分不能结束，以下评价对象未完成所有评分：");
            Map<String, List<String>> personMap = new HashMap<>();
            Arrays.stream(questNotScorePerson).forEach(evalResult -> {
                String personName = evalResult.getDynamicObject(HonorStudentConstant.NCKD_PERSON).getDynamicObject(FormConstant.PERSON).getString(FormConstant.NAME_KEY);
                String scorerName = evalResult.getDynamicObject(HonorStudentConstant.NCKD_SCORER).getDynamicObject(FormConstant.PERSON).getString(FormConstant.NAME_KEY);
                personMap.computeIfAbsent(personName, k -> new ArrayList<>()).add(scorerName);
            });
            for (Map.Entry<String, List<String>> personListEntry : personMap.entrySet()) {
                errorJoin.add(StrFormatter.format("评价对象【{}】-未完成评分人：{}",personListEntry.getKey(), StringUtils.join(personListEntry.getValue(),"，")));
            }
            logger.warn("【优秀生考评】-结束评测-业务校验异常：{}",errorJoin.toString());
            throw new ValidationException(errorJoin.toString());
        }
        //更新问卷状态为：已结束：2
        for (DynamicObject evalQuest : result.evalQuestArray) {
            //问卷修改为已结束
            evalQuest.set(HonorStudentConstant.NCKD_PERIODSTATE,"2");
        }

        //===================== 3.更新答卷状态为：已结束：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,"3");
        }
        SaveServiceHelper.update(result.evalQuestArray);
        SaveServiceHelper.update(evalResultArray);
        logger.info("【优秀生考评】-结束评测-结束");
    }
}