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.DepartmentBo;
import com.ruoyi.scientific.service.IDepartmentService;
import com.ruoyi.scientific.service.IDepartmentService;
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.DepartmentVo;
import com.ruoyi.common.core.page.TableDataInfo;

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

    private final IDepartmentService IdepartmentService =
        SpringUtils.getBean(IDepartmentService.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 departmentProcId = execution.getProcessInstanceId();
        DepartmentBo bo = new DepartmentBo();
        bo.setDepartmentProcId(departmentProcId);
        PageQuery pageQuery = new PageQuery();
        TableDataInfo<DepartmentVo> result = IdepartmentService.queryPageList(bo, pageQuery);
        Long departmentId = result.getRows().get(0).getDepartmentId();

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

        // zqjia: runtimeService获取是否terminated，判断注入review字段可以区分是complete还是cancel
        if("terminated".equals(status)) {
            IdepartmentService.updateDepartmentInfoById(departmentId, "2");
        }
        else {
            if("1".equals(reviewStatus)) {
                IdepartmentService.updateDepartmentInfoById(departmentId, "3");
            }
            else {
                IdepartmentService.updateDepartmentInfoById(departmentId, "0");
            }
        }
    }
}
