package com.huigou.bpm.webservice.call.application.impl;

import com.alibaba.fastjson.JSONObject;
import com.huigou.bpm.webservice.call.application.CallSapWebServiceApplication;
import com.huigou.bpm.webservice.call.domain.model.SapWebServiceConfig;
import com.huigou.bpm.webservice.call.domain.model.SapWebServiceFields;
import com.huigou.bpm.webservice.call.domain.model.SapWebServiceParameter;
import com.huigou.bpm.webservice.call.repository.SapWebServiceConfigRepository;
import com.huigou.bpm.webservice.call.repository.SapWebServiceFieldsRepository;
import com.huigou.bpm.webservice.call.repository.SapWebServiceParameterRepository;
import com.huigou.bpm.webservice.common.SapWsProxyFactoryCreater;
import com.huigou.bpm.webservice.utils.SapJcoClient;
import com.huigou.bpm.webservice.utils.SapJcoUtils;
import com.huigou.exception.ApplicationException;
import com.huigou.util.StringUtil;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

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

@Service("callSapWebServiceApplication")
public class CallSapWebServiceApplicationImpl extends SapWsProxyFactoryCreater implements CallSapWebServiceApplication {

    @Autowired
    private SapWebServiceParameterRepository sapWebServiceParameterRepository;
    @Autowired
    private SapWebServiceConfigRepository sapWebServiceConfigRepository;
    @Autowired
    private SapWebServiceFieldsRepository sapWebServiceFieldsRepository;
    @Autowired
    @Qualifier("sapCallThread")
    private TaskExecutor taskExecutor;
    @Produce(uri = "jms:startProcess")
    private ProducerTemplate startProcess;
    @Produce(uri = "jms:startTask")
    private ProducerTemplate startTask;
    @Produce(uri = "jms:completeTask")
    private ProducerTemplate completeTask;

    @Override
    public Map<String, Object> callSapWebService(String funcationName, Map<String, Object> imputData) {

        SapJcoClient client = new SapJcoClient();
        Map<String, Object> resultMap = client.execCall(funcationName, imputData);
        Map<String,Object> ruleMap = new HashMap<>();
        SapWebServiceConfig config = sapWebServiceConfigRepository.findByCodeAndStatus(funcationName,1);
        List<SapWebServiceParameter> parameters = sapWebServiceParameterRepository.findByConfigIdOrderBySequence(config.getId());
        for(SapWebServiceParameter parameter:parameters){
            if(StringUtil.isNotBlank(parameter.getLocalParameterName())){
                ruleMap.put(parameter.getParameterName(),parameter.getLocalParameterName());
            }
            List<SapWebServiceFields> fields = sapWebServiceFieldsRepository.findByParameterIdAndStatus(parameter.getId(),1);
            for(SapWebServiceFields field:fields){
                if(StringUtil.isNotBlank(field.getLocalFieldCode())){
                    ruleMap.put(field.getCode(),field.getLocalFieldCode());
                }
            }
        }
        Map<String,Object> localResultMap = SapJcoUtils.toLocalMap(resultMap,ruleMap);

        return localResultMap;
    }

    public String callSapWebServiceToJson(String funcationName, Map<String, Object> imputData) {

        SapJcoClient client = new SapJcoClient();
        Map<String, Object> resultMap = client.execCall(funcationName, imputData);
        return new JSONObject(resultMap).toJSONString();
    }

    @Override
    public void bpmToSap(String bizId, String bpmFlowCode, String functionName, Map<String, Object> inputData) {
        SapWebServiceConfig config = sapWebServiceConfigRepository.findByCodeAndStatus(functionName, 1);
        if (config == null) {
            throw new ApplicationException("无效的方法名称，系统未配置，请联系管理员！");
        }
        Map<String,Object> ruleMap = new HashMap<>();
        List<SapWebServiceParameter> parameters = sapWebServiceParameterRepository.findByConfigIdOrderBySequence(config.getId());
        for(SapWebServiceParameter parameter:parameters){
            if(StringUtil.isNotBlank(parameter.getLocalParameterName())){
                ruleMap.put(parameter.getLocalParameterName(),parameter.getParameterName());
            }
            List<SapWebServiceFields> fields = sapWebServiceFieldsRepository.findByParameterIdAndStatus(parameter.getId(),1);
            for(SapWebServiceFields field:fields){
                if(StringUtil.isNotBlank(field.getLocalFieldCode())){
                    ruleMap.put(field.getLocalFieldCode(),field.getCode());
                }
            }
        }
        Map<String,Object> sapInputData = SapJcoUtils.toSapMap(inputData,ruleMap);
        taskExecutor.execute(() -> {
            JSONObject data = new JSONObject();
            data.put("bizKey", bizId);
            data.put("serviceCode", bpmFlowCode);
            //  try {
            Map<String, Object> result = callSapWebService(functionName, sapInputData);
            startTask.requestBody(data.toJSONString());
            data.put("bizData", result);
            completeTask.requestBody(data.toJSONString());
            //   } catch (Exception e) {
            //       e.printStackTrace();
            //       JSONObject error = new JSONObject();
            //       error.put("TYPE", "ERROR");
            //        error.put("MESSAGE", e.getMessage());
            //         completeTask.requestBody(data.toJSONString());
            //    }

        });
    }
}
