package com.huigou.bpm.engine.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.huigou.bpm.engine.domain.InMessage;
import com.huigou.bpm.engine.domain.OutMessage;
import com.huigou.bpm.webservice.call.application.CallSapWebServiceApplication;
import com.huigou.util.ApplicationContextWrapper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * SAP访问流程
 * @author wuyounan
 */
public class SapInterfaceProcessor implements Processor {

    private final Logger log = LoggerFactory.getLogger(SapInterfaceProcessor.class);
    @Autowired
    private CallSapWebServiceApplication callSapWebServiceApplication;

    @Override
    public void process(Exchange exchange) throws Exception {
        Message msg = exchange.getMessage();
        String textMsg = msg.getBody(String.class);
        JSONObject request = JSONObject.parseObject(textMsg);
        InMessage inMsg = request.toJavaObject(InMessage.class);
        if (StringUtils.isBlank(inMsg.getProcdefCode())) {
            RuntimeService runtimeService = ApplicationContextWrapper.getBean(RuntimeService.class);
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(inMsg.getBizKey()).singleResult();
            inMsg.setProcdefCode(pi.getProcessDefinitionKey());
        }

        Map<String, Object> data = null;
        int code = 0;
        String errorMsg = null;

        try {
            if (inMsg.getBizData() == null) {
                inMsg.setBizData(new HashMap<>(16));
            }
            data = processInternal(inMsg);
        } catch (Exception e) {
            code = 1;
            errorMsg = e.getMessage();
            log.error(String.format("处理业务系统的SAP请求出错, request=%s", textMsg), e);
        }

        OutMessage outMsg = new OutMessage();
        outMsg.setCode(code);
        outMsg.setMsg(errorMsg);
        outMsg.setData(data);
        msg.setBody(JSON.toJSONString(outMsg, SerializerFeature.WriteDateUseDateFormat), String.class);
    }

    private Map<String,Object> processInternal(InMessage inMessage){
        if (log.isInfoEnabled()) {
            log.info("启动BPMN流程，code={},bizKey={},bizData={}", inMessage.getProcdefCode(), inMessage.getBizKey(), inMessage.getBizData());
        }
        callSapWebServiceApplication.bpmToSap(inMessage.getBizKey(),inMessage.getProcdefCode(),inMessage.getSapFunctionName(),inMessage.getBizData());
        return null;
    }
}
