package com.ruoyi.scientific.listener;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.scientific.domain.bo.ProjectHandbookBo;
import com.ruoyi.scientific.service.IProjectHandbookService;
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.common.core.domain.PageQuery;
import com.ruoyi.scientific.domain.vo.ProjectHandbookVo;
import com.ruoyi.common.core.page.TableDataInfo;

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

    private final IProjectHandbookService ihandbookServiceProject =
        SpringUtils.getBean(IProjectHandbookService.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();
        ProjectHandbookBo bo = new ProjectHandbookBo();
        bo.setHandbookProcId(handbookProcId);
        PageQuery pageQuery = new PageQuery();
        TableDataInfo<ProjectHandbookVo> result = ihandbookServiceProject.queryPageList(bo, pageQuery);
        Long handbookId = result.getRows().get(0).getHandbookId();

        // 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
        if("terminated".equals(status)) {
            ihandbookServiceProject.updateHandbookInfoById(handbookId, "2");
        }
        else {
            if("1".equals(reviewStatus)) {
                ihandbookServiceProject.updateHandbookInfoById(handbookId, "3");
            }
            else {
                ihandbookServiceProject.updateHandbookInfoById(handbookId, "0");
            }
        }
    }
}
