package com.ruoyi.scientific.listener;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.scientific.service.IProjectApplicationService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

@Component
public class ProjectDeclareStatusListener implements ExecutionListener {

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

    @Override
    public void notify(DelegateExecution execution) {
        System.out.println("科研模块：执行项目申报状态更新任务监听器...");
        // 获得项目的流程ID
        String projectProcId = execution.getProcessInstanceId();
        // 获取项目的ID
        String projectIdStr = (String) execution.getVariable("projectId");
        Long projectId = Long.parseLong(projectIdStr);

        String reviewStatus = (String) execution.getVariable("review");
        String status = (String) runtimeService.getVariable(projectProcId, ProcessConstants.PROCESS_STATUS_KEY);

        // 判断流程是否结束
        if ("terminated".equals(status)) {
            // 审批人员选择拒绝 申报状态修改为2 审核失败
            projectApplicationService.updateDecStatusInfoById(projectId, "2");
        } else {
            if ("1".equals(reviewStatus)) {
                // 如果reviewStatus == 1 说明申报成功 3 审核通过
                projectApplicationService.updateDecStatusInfoById(projectId, "3");
            } else {
                // 其他状态设置为0 未审核
                projectApplicationService.updateDecStatusInfoById(projectId, "0");
            }
        }
    }
}
