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

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.CloseCallBack;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.list.ListView;
import kd.bos.schedule.api.JobInfo;
import kd.bos.schedule.api.JobType;
import kd.bos.schedule.form.JobForm;
import kd.bos.schedule.form.JobFormInfo;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;
import nckd.jxccl.hr.hstu.task.CreateEvalQuestTask;
import nckd.jxccl.hr.hstu.task.CreateEvalQuestTaskClick;

import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

/**
* 生成评价对象（弹窗）表单插件
* @author W.Y.C
* @date 2025/7/1 10:19
* @version 1.0
*/
public class CreateEvalQuestFormPlugin extends AbstractFormPlugin implements Plugin {

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

    @Override
    public void registerListener(EventObject e) {
        this.addClickListeners(HonorStudentConstant.BTN_OK_OP);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        Long evalQuestTplId = ConvertUtil.toLong(this.getView().getFormShowParameter().getCustomParams().get(HonorStudentConstant.NCKD_EVALQUESTTPLID));
        this.getModel().setValue(HonorStudentConstant.NCKD_EVALQUESTTPL, evalQuestTplId);
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        boolean success = e.getOperationResult() != null && e.getOperationResult().isSuccess();
        if(HonorStudentConstant.AFFIRM_OP.equalsIgnoreCase(operateKey) && success) {
            FormOperate formOperate = (FormOperate) e.getSource();
            // ------------------------------------- 获取评价对象开启异步生成 begin -------------------------------------
            // 只有操作插件确认开启异步后才会开启
            Boolean task = ConvertUtil.toBoolean(formOperate.getOption().getVariableValue("task"));
            if(task){
                DynamicObject evalQuestTpl = ((DynamicObject)this.getModel().getValue(HonorStudentConstant.NCKD_EVALQUESTTPL));
                DynamicObject selectedEvalRule = (DynamicObject) this.getModel().getValue(HonorStudentConstant.NCKD_SELECTEDEVALRULE);
                DynamicObjectCollection selectedPerson = (DynamicObjectCollection) this.getModel().getValue(HonorStudentConstant.NCKD_SELECTEDPERSON);

                // 1. 创建任务实例
                JobInfo jobInfo = new JobInfo();
                jobInfo.setTaskClassname(CreateEvalQuestTask.class.getName());
                Map<String, Object> params = new HashMap<>();
                params.put(HonorStudentConstant.NCKD_EVALQUESTTPL, evalQuestTpl);
                params.put(HonorStudentConstant.NCKD_SELECTEDEVALRULE, selectedEvalRule);
                params.put(HonorStudentConstant.NCKD_SELECTEDPERSON, selectedPerson);
                //调度任务中获取不到当前用户信息
                long currUserId = RequestContext.get().getCurrUserId();
                long orgId = RequestContext.get().getOrgId();
                params.put(HonorStudentConstant.KEY_CURR_USER_ID, currUserId);
                params.put(HonorStudentConstant.CURR_ORG_ID, orgId);
                jobInfo.setParams(params);
                jobInfo.setJobType(JobType.REALTIME);
                jobInfo.setSuccessNotify(Boolean.TRUE);

                // 2. 配置进度界面
                JobFormInfo formInfo = new JobFormInfo(jobInfo);
                formInfo.setCaption("生成综合评测问卷进度");

                String billFormId = ((ListView) this.getView().getParentView()).getBillFormId();
                if(HonorStudentConstant.NCKD_EVALQUESTTPL_ENTITYID.equals(billFormId)) {
                    formInfo.setCloseCallBack(new CloseCallBack(EvalQuestTplListPlugin.class.getName(), HonorStudentConstant.TASK_CREATEEVAL));
                }else if(HonorStudentConstant.NCKD_EVALQUEST_ENTITYID.equals(billFormId)) {
                    formInfo.setCloseCallBack(new CloseCallBack(EvalQuestListPlugin.class.getName(), HonorStudentConstant.TASK_CREATEEVAL));
                }
                formInfo.setClickClassName(CreateEvalQuestTaskClick.class.getName());
                // 允许用户中途取消
                //formInfo.setCanStop(true);
                // 允许切到后台
                //formInfo.setCanBackground(true);

                // 3. 发布任务并显示进度界面
                JobForm.dispatch(formInfo, this.getView().getParentView());
                this.getView().close();
                logger.info("【优秀生考评】-生成综合评测问卷-开启异步任务");
                // ------------------------------------- 获取评价对象开启异步生成 end -------------------------------------
            }else{
                this.getView().getParentView().invokeOperation(FormConstant.REFRESH_OP);
                this.getView().getParentView().showSuccessNotification("生成综合评测问卷成功，可在【查看评价列表】中查看");
                this.getView().close();
            }
        }
    }
}