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

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
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.QueryServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.hr.hstu.business.CreateEvalQuestService;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;

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

/**
* 【优秀生】-获取评价对象插件
* @author W.Y.C
* @date 2025/8/15 16:11
* @version 1.0
*/
public class CreateQvalQuestAffirmOperationPlugin extends AbstractOperationServicePlugIn implements Plugin {

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

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        logger.info("【优秀生考评】-生成综合评测问卷-开始");
        DynamicObject[] data = e.getDataEntities();
        if(data == null || data.length == 0){
            e.setCancel(true);
            e.setCancelMessage("请选择要获取问卷的数据");
            return;
        }
        DynamicObject evalQuestTpl = data[0].getDynamicObject(HonorStudentConstant.NCKD_EVALQUESTTPL);
        DynamicObject selectedEvalRule = data[0].getDynamicObject(HonorStudentConstant.NCKD_SELECTEDEVALRULE);
        DynamicObjectCollection selectedPerson = data[0].getDynamicObjectCollection(HonorStudentConstant.NCKD_SELECTEDPERSON);
        //------------ 校验是否已生成过问卷（校验规则：评价对象是否已经有对应的评价规则或模板问卷） begin ------------
        List<Long> idList = new ArrayList<>();
        selectedPerson.forEach(map ->{
            DynamicObject depEmpRow = (DynamicObject)map.getDynamicObject(FormConstant.BASEDATAID_KEY);
            idList.add(depEmpRow.getLong(HonorStudentConstant.ID_KEY));
        });
        logger.info("【优秀生考评】-生成综合评测问卷-选择的问卷模板ID：{}",evalQuestTpl.getLong(FormConstant.ID_KEY));
        logger.info("【优秀生考评】-生成综合评测问卷-选择的评价规则ID：{}",selectedEvalRule.getLong(HonorStudentConstant.ID_KEY));
        logger.info("【优秀生考评】-生成综合评测问卷-选择的人员ID：{}",idList.stream().map(String::valueOf).collect(Collectors.joining(",")));
        QFilter filter = new QFilter(HonorStudentConstant.NCKD_EVALPERSON, QCP.in, idList);
        filter.and(
                new QFilter(HonorStudentConstant.NCKD_EVALUATIONRULE,QCP.equals,selectedEvalRule.getLong(HonorStudentConstant.ID_KEY))
                        .or(new QFilter(HonorStudentConstant.NCKD_EVALQUESTTPL,QCP.equals,evalQuestTpl.getLong(FormConstant.ID_KEY)))
        );
        DynamicObjectCollection evalQuestColl = QueryServiceHelper.query(HonorStudentConstant.NCKD_EVALQUEST_ENTITYID,HonorStudentConstant.NCKD_EVALPERSON+".person.name",new QFilter[]{filter});
        if(!evalQuestColl.isEmpty()){
            StringJoiner exitsPersonName = new StringJoiner("，");
            evalQuestColl.forEach(dynamicObject -> exitsPersonName.add(dynamicObject.getString(HonorStudentConstant.NCKD_EVALPERSON+".person.name")));
            String format = StrFormatter.format("下列人员已存在问卷：{}；不能重复生成，请检查！", exitsPersonName.toString());
            logger.warn("【优秀生考评】-生成综合评测问卷-业务校验异常：{}",format);
            e.setCancel(true);
            e.setCancelMessage( format);

        }
        //------------ 校验是否已生成过问卷（校验规则：评价对象是否已经有对应的评价规则或模板问卷） end ------------
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {

        DynamicObject[] data = e.getDataEntities();
        DynamicObject evalQuestTpl = data[0].getDynamicObject(HonorStudentConstant.NCKD_EVALQUESTTPL);
        DynamicObject selectedEvalRule = data[0].getDynamicObject(HonorStudentConstant.NCKD_SELECTEDEVALRULE);
        DynamicObjectCollection selectedPerson = data[0].getDynamicObjectCollection(HonorStudentConstant.NCKD_SELECTEDPERSON);
        if (selectedPerson.size() > 10) {
            // 选择生成人员超过10人开启异步任务
            this.getOption().setVariableValue("task","true");
        } else {
            CreateEvalQuestService.batchGenerateEvalQuest(evalQuestTpl, selectedEvalRule, selectedPerson, null, null, null);
        }
    }
}