package com.mortals.xhx.daemon.demo;

import com.alibaba.fastjson.JSON;
import com.mortals.xhx.common.model.RequestTaskReq;
import com.mortals.xhx.common.pdu.api.ApiReqPdu;
import com.mortals.xhx.common.pdu.api.ApiRespPdu;
import com.mortals.xhx.feign.flowable.IApiFlowInstanceFeign;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author karlhoo
 */
@CommonsLog
@RestController
@RequestMapping("test")
public class RequestInstanceController {

    @Autowired
    private IApiFlowInstanceFeign apiFlowInstanceFeign;

    @PostMapping("/instance/startById")
    public ApiRespPdu startById(@RequestBody ApiReqPdu<RequestTaskReq> req) {
        ApiRespPdu<String> respPdu = new ApiRespPdu<>();
        try {
            HashMap<String, Object> variables = new HashMap<>();

            variables.put("initiator", req.getTransmission().getUserId());
            variables.put("_FLOWABLE_SKIP_EXPRESSION_ENABLED", true);

            respPdu = apiFlowInstanceFeign.startById(req.getTransmission().getProcDefId(), variables);
        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }

    @PostMapping("/instance/updateState")
    public ApiRespPdu updateState(@RequestBody ApiReqPdu<RequestTaskReq> req) {
        ApiRespPdu<String> respPdu = new ApiRespPdu<>();
        try {

            respPdu = apiFlowInstanceFeign.updateState(req.getTransmission().getState(),req.getTransmission().getProcessInstanceId());
        } catch (Exception e) {
            log.error("error", e);
        }
        return respPdu;
    }

    public static void main(String[] args) {

        RequestTaskReq requestTaskReq = new RequestTaskReq();
        requestTaskReq.setProcessInstanceId("11111");
        requestTaskReq.setDeployId("1");
        requestTaskReq.setUserId("admin");
        requestTaskReq.setDataKey("mydata");

        ApiReqPdu<RequestTaskReq> requestTaskReqApiReqPdu = new ApiReqPdu<>();
        requestTaskReqApiReqPdu.setTransmission(requestTaskReq);
        requestTaskReqApiReqPdu.setSeq("123456");

        System.out.println(JSON.toJSONString(requestTaskReqApiReqPdu));

    }

}
