package com.ruoyi.scientific.listener;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.scientific.service.IProjectPlanService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;
import org.flowable.engine.HistoryService;
import com.ruoyi.scientific.domain.bo.ProjectPlanBo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.scientific.domain.vo.ProjectPlanVo;
import com.ruoyi.common.core.page.TableDataInfo;

//@Component
//public class HandbookUpdateListener implements ExecutionListener {
//
//    @Override
//    public void notify(DelegateExecution execution) {
//        System.out.println("当前活动名称: " + execution.getProcessInstanceBusinessStatus());
//
//        if ("end".equals(execution.getEventName())) {
//            if (execution.isEnded()) {
//                System.out.println("任务被终止: " + execution.getId());
//            } else {
//                System.out.println("任务正常完成: " + execution.getId());
//            }
//        }
//    }
//}

@Component
public class PlanUpdateListener implements ExecutionListener {
    /**
     * 注入字段（名称与流程设计时字段名称一致）
     */

    private final IProjectPlanService iProjectHandbookService =
        SpringUtils.getBean(IProjectPlanService.class);
    private final HistoryService historyService =
        SpringUtils.getBean(HistoryService.class);

    private final RuntimeService runtimeService =
        SpringUtils.getBean(RuntimeService.class);

    @Override
    public void notify(DelegateExecution execution) {
        System.out.println("科研模块：执行申报计划更新任务监听器...");

        String handbookProcId = execution.getProcessInstanceId();
        ProjectPlanBo bo = new ProjectPlanBo();
        bo.setPlanProcId(handbookProcId);
        PageQuery pageQuery = new PageQuery();
        TableDataInfo<ProjectPlanVo> result = iProjectHandbookService.queryPageList(bo, pageQuery);
        Long handbookId = result.getRows().get(0).getPlanId();

        // zqjia:获取在task complete时注入的review状态
        String reviewStatus = (String) execution.getVariable("review");
        // 获取流程状态
        String status = (String) runtimeService.getVariable(handbookProcId, ProcessConstants.PROCESS_STATUS_KEY);

        // zqjia: runtimeService获取是否terminated，判断注入review字段可以区分是complete还是cancel
        // 退回有bug，暂时不知道会不会到这来
        if("terminated".equals(status)) {
            iProjectHandbookService.updateHandbookInfoById(handbookId, "2");
        }
        else {
            if("1".equals(reviewStatus)) {
                iProjectHandbookService.updateHandbookInfoById(handbookId, "3");
            }
            else {
                iProjectHandbookService.updateHandbookInfoById(handbookId, "0");
            }
        }
    }
}
