package com.jy.flow.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.jy.flow.controller.ExecuteController;
import com.jy.flow.model.dto.WarmFlowHandleDto;
import com.jy.flow.model.enums.FlowStatusEnum;
import com.jy.framework.satoken.LoginContext;
import com.jy.framework.utils.AssertUtil;
import org.dromara.warm.flow.core.dto.FlowParams;
import org.dromara.warm.flow.core.entity.Instance;
import org.dromara.warm.flow.core.entity.Task;
import org.dromara.warm.flow.core.service.InsService;
import org.dromara.warm.flow.core.service.TaskService;
import org.dromara.warm.flow.orm.entity.FlowInstance;
import org.dromara.warm.flow.orm.entity.FlowTask;

import java.util.Map;

public class FlowUtil {
    private final static InsService insService = SpringUtil.getBean(InsService.class);
    private final static TaskService taskService = SpringUtil.getBean(TaskService.class);
    private final static ExecuteController executeController = SpringUtil.getBean(ExecuteController.class);

    /**
     * 发起流程
     */
    public static void start(String flowCode, Long businessId) {
        FlowParams flowParams = FlowParams.build()
                .flowCode(flowCode)
                .handler(LoginContext.getUserId().toString())
                .flowStatus(FlowStatusEnum.APPROVAL.getKeyStr());

        insService.start(businessId.toString(), flowParams);
    }

    /**
     * 发起流程
     */
    public static void start(String flowCode, Long businessId, Map<String, Object> variable) {
        FlowParams flowParams = FlowParams.build()
                .flowCode(flowCode)
                .handler(LoginContext.getUserId().toString())
                .variable(variable)
                .flowStatus(FlowStatusEnum.APPROVAL.getKeyStr());

        insService.start(businessId.toString(), flowParams);
    }

    public static void next(Long businessId) {
        Instance instance = insService.getOne(new FlowInstance().setBusinessId(businessId.toString()));
        AssertUtil.notNull(instance, "未知流程实例");

        Task task = taskService.getOne(new FlowTask().setInstanceId(instance.getId()));
        AssertUtil.notNull(task, "未知流程任务");

        WarmFlowHandleDto dto = new WarmFlowHandleDto();
        dto.setTaskId(task.getId());
        dto.setHandleType(1);
        executeController.handle(dto);
    }

}
