package cn.axzo.workflow.server.xxljob;

import cn.axzo.workflow.common.model.request.bpmn.RestBpmnProcessVariable;
import cn.axzo.workflow.core.service.BpmnProcessJobService;
import cn.axzo.workflow.core.service.BpmnProcessVariableService;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

import static com.xxl.job.core.biz.model.ReturnT.FAIL_CODE;

/**
 * deadletter-job重试
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DeadLetterJobRetryHandler {

    @Resource
    private BpmnProcessVariableService variableService;

    @Resource
    private BpmnProcessJobService jobService;

    @XxlJob("deadLetterJobRetry")
    public ReturnT<String> execute(String param) {
        if (StringUtils.isBlank(param)) {
            return new ReturnT<>(FAIL_CODE, "参数不能为空");
        }
        try {
            AsyncJobRetryDto bean = JSONUtil.toBean(param, AsyncJobRetryDto.class);
            if (bean == null) {
                throw new NullPointerException("反序列化实体为空");
            }
            if (StringUtils.isBlank(bean.getProcessInstanceId())) {
                throw new IllegalArgumentException("流程实例id不能为空");
            }
            //设置变量
            if (bean.getVariables() != null && !bean.getVariables().isEmpty()) {
                variableService.updateVariables(bean.getProcessInstanceId(), bean.getVariables());
            }
            //进行重试
            jobService.executeDeadLetterJobActionByProcInstId(bean.getProcessInstanceId());
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            return new ReturnT<>(FAIL_CODE, e.getMessage());
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static final class AsyncJobRetryDto {
        private String processInstanceId;
        private List<RestBpmnProcessVariable> variables;
    }
}
