package cn.stylefeng.workflow.instance.modular.openapi.service;

import cn.hutool.core.collection.ListUtil;
import cn.stylefeng.workflow.api.entity.instance.RuntimeInstance;
import cn.stylefeng.workflow.api.entity.instance.RuntimeNode;
import cn.stylefeng.workflow.api.enums.WorkflowStartTypeEnum;
import cn.stylefeng.workflow.instance.api.InstanceVariableApi;
import cn.stylefeng.workflow.instance.api.WorkflowControlApi;
import cn.stylefeng.workflow.instance.api.pojo.request.WorkflowFinishNodeRequest;
import cn.stylefeng.workflow.instance.api.pojo.request.WorkflowStartRequest;
import cn.stylefeng.workflow.instance.modular.manage.service.RuntimeNodeService;
import cn.stylefeng.workflow.instance.modular.openapi.pojo.FinishOpenApiRequest;
import cn.stylefeng.workflow.instance.modular.openapi.pojo.UpdateVariablesApiRequest;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class WorkflowOpenApiService {

    @Resource
    private WorkflowControlApi workflowControlApi;

    @Resource
    private RuntimeNodeService runtimeNodeService;

    @Resource
    private InstanceVariableApi variableApi;

    public RuntimeInstance startWorkflow(WorkflowStartRequest workflowStartRequest) {
        workflowStartRequest.setWorkflowStartType(WorkflowStartTypeEnum.API_START.getCode());
        return workflowControlApi.start(workflowStartRequest);
    }

    public void finishNode(FinishOpenApiRequest finishOpenApiRequest) {

        Long runtimeNodeId = finishOpenApiRequest.getRuntimeNodeId();
        RuntimeNode runtimeNode = runtimeNodeService.getRuntimeNodeById(runtimeNodeId);

        WorkflowFinishNodeRequest workflowFinishNodeRequest = new WorkflowFinishNodeRequest();
        workflowFinishNodeRequest.setInstanceId(runtimeNode.getInstanceId());
        workflowFinishNodeRequest.setRuntimeNodeIdList(ListUtil.list(true, runtimeNodeId));
        workflowControlApi.finishNode(workflowFinishNodeRequest);
    }

    public void updateWorkflowVariable(UpdateVariablesApiRequest updateVariablesApiRequest) {
        variableApi.updateInstanceVariable(updateVariablesApiRequest.getInstanceId(), updateVariablesApiRequest.getFlowVariables());
    }

}
