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 ProjectAppStatusUpdateListener 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("科研模块：执行项目立项状态更新任务监听器...");

        String projectProcId = execution.getProcessInstanceId();

        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)) {
            projectApplicationService.updateAppstausInfoById(projectId, "2");
        } else {
            if ("1".equals(reviewStatus)) {
                projectApplicationService.updateAppstausInfoById(projectId, "3");
            } else {
                projectApplicationService.updateAppstausInfoById(projectId, "0");
            }
        }
    }
}
