package cn.axzo.workflow.server.controller.web.bpmn;

import cn.axzo.workflow.client.feign.bpmn.ProcessJobApi;
import cn.axzo.workflow.common.exception.WorkflowEngineException;
import cn.axzo.workflow.core.service.BpmnProcessJobService;
import cn.axzo.workflow.server.common.annotation.ErrorReporter;
import cn.azxo.framework.common.model.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.axzo.workflow.common.code.AsyncJobRespCode.RESUME_JOB_REQUEST_PARAM_ERROR;
import static cn.azxo.framework.common.model.CommonResponse.success;

/**
 * 流程job控制器
 */
@Slf4j
@RequestMapping({"/web/v1/api/process/job", "/api/process/job"})
@RestController
@ErrorReporter
@Validated
public class BpmnProcessJobController implements ProcessJobApi {

    @Resource
    private BpmnProcessJobService bpmnProcessJobService;

    @Override
    @GetMapping("/dead-letter/resume")
    public CommonResponse<Void> executeDeadLetterJobAction(@RequestParam String jobId, @RequestParam String procInstId) {
        log.info("将死信任务重新激活 executeDeadLetterJobAction ===>>>参数：{}, {}", jobId, procInstId);
        if (StringUtils.isBlank(jobId) && StringUtils.isBlank(procInstId)) {
            throw new WorkflowEngineException(RESUME_JOB_REQUEST_PARAM_ERROR);
        }
        if (StringUtils.isNotBlank(jobId)) {
            bpmnProcessJobService.executeDeadLetterJobActionByJobId(jobId);
        } else {
            bpmnProcessJobService.executeDeadLetterJobActionByProcInstId(procInstId);
        }
        return success();
    }

    @Override
    @GetMapping("/dead-letter/exception/stacktrace")
    public String getDeadLetterJobExceptionStacktrace(@RequestParam String procInstId) {
        if (StringUtils.isBlank(procInstId)) {
            return "";
        }
        return bpmnProcessJobService.getDeadLetterJobExceptionStacktrace(procInstId);
    }

    @Override
    @GetMapping("/dead-letter/exception/stacktrace/byId")
    public String getDeadLetterJobExceptionStacktraceByJobId(@RequestParam String jobId) {
        if (StringUtils.isBlank(jobId)) {
            return "";
        }
        return bpmnProcessJobService.getDeadLetterJobExceptionStacktraceByJobId(jobId);
    }
}
