package com.huigou.bpm.engine.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huigou.bpm.engine.domain.InMessage;
import com.huigou.bpm.engine.domain.OutMessage;
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 java.util.HashMap;
import java.util.Map;

/**
 * @author yonghuan
 */
abstract class AbstractBusinessProcessor implements Processor {

    private final Logger LOG = LoggerFactory.getLogger(AbstractBusinessProcessor.class);

    @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("处理业务系统的BPM请求出错, request=%s", textMsg), e);
        }
        OutMessage outMsg = new OutMessage();
        outMsg.setCode(code);
        outMsg.setMsg(errorMsg);
        outMsg.setData(data);
        msg.setBody(JSON.toJSONString(outMsg), String.class);
    }

    /**
     * @param inMessage
     * @return 返回给调用方的数据。
     */
    protected abstract Map<String, Object> processInternal(InMessage inMessage);
}
