package com.sw.mes.wms.service.impl;

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

import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sw.mes.core.dto.wms.MesasnDto;
import com.sw.mes.core.dto.wms.RematDto;
import com.sw.mes.core.dto.wms.RemesstaDto;
import com.sw.mes.jip.dto.TokenDto;
import com.sw.mes.jip.entity.JipHeaderConfig;
import com.sw.mes.jip.enums.IFKeyWordEnums;
import com.sw.mes.jip.service.JipHeaderConfigService;
import com.sw.mes.jip.utils.JipRestUtils;
import com.sw.mes.jip.utils.JipUtil;
import com.sw.mes.sap.dto.jip.JipISBCINFO;
import com.sw.mes.utils.StringUtils;
import com.sw.mes.wms.entity.LogWmsMesInteractive;
import com.sw.mes.wms.service.LogWmsMesInteractiveService;
import com.sw.mes.wms.service.WMSOutputService;

@Service
@Slf4j
public class WMSOutputServiceImpl implements WMSOutputService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JipHeaderConfigService jipHeaderConfigService;

    @Autowired
    private LogWmsMesInteractiveService logWmsMesInteractiveService;

    @Override
    public void sendremessta(List<RemesstaDto> data) throws JsonProcessingException {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.REMESSTA.getKeyword());

        if (jipHeaderConfig == null)
            throw new RuntimeException("MES中未配置成品返工车间MES接收状态回传接口信息");

        if (StringUtils.isBlank(jipHeaderConfig.getUrl()))
            throw new RuntimeException("MES中未配置成品返工车间MES接收状态回传接口URL请求地址");

        JipISBCINFO jipISBCINFO = JipUtil.initISBCINFO(jipHeaderConfig);
        TokenDto token = JipUtil.initToken(jipHeaderConfig);

        Map<String, Object> dataObj = new HashMap<>();
        dataObj.put("IS_BC_INFO", jipISBCINFO);//header信息
        dataObj.put("IT_DATA", data);


        String dataJson = JSON.toJSONString(dataObj);

        //2.发送工单消耗数据到SAP
        JSONObject result = null;
        try {
            result = JipRestUtils.post(jipHeaderConfig.getUrl(), JSONObject.parseObject(dataJson), token);

            //保存交互记录
            saveInteractiveLog("mes->wms", "成品返工车间MES接收状态回传接口", "sendremessta", dataObj, result);

            JSONObject ES_BC_INFO = result.getJSONObject("ES_BC_INFO");
            if (!ES_BC_INFO.getString("TYPE").equals("S")) {
                throw new RuntimeException(ES_BC_INFO.getString("MSG"));
            }
        } catch (Exception e) {
            log.error("error_in_sendremessta", e);
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void sendremat(RematDto data) throws JsonProcessingException {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.REMAT.getKeyword());

        if (jipHeaderConfig == null)
            throw new RuntimeException("MES中未配置退料入库接口信息");

        if (StringUtils.isBlank(jipHeaderConfig.getUrl()))
            throw new RuntimeException("MES中未配置退料入库接口URL请求地址");

        JipISBCINFO jipISBCINFO = JipUtil.initISBCINFO(jipHeaderConfig);
        TokenDto token = JipUtil.initToken(jipHeaderConfig);

        Map<String, Object> dataObj = new HashMap<>();
        dataObj.put("IS_BC_INFO", jipISBCINFO);//header信息
        dataObj.put("IT_DATA", data);

        //String dataJson = objectMapper.writeValueAsString(dataObj);
        String dataJson = JSON.toJSONString(dataObj);

        //2.发送工单消耗数据到SAP
        JSONObject result = null;
        try {
            result = JipRestUtils.post(jipHeaderConfig.getUrl(), JSONObject.parseObject(dataJson), token);

            //保存交互记录
            saveInteractiveLog("mes->wms", "车间退料入库接口", "sendremat", dataObj, result);

            JSONObject ES_BC_INFO = result.getJSONObject("ES_BC_INFO");
            if (!ES_BC_INFO.getString("TYPE").equals("S")) {
                throw new RuntimeException(ES_BC_INFO.getString("MSG"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void sendMesasn(List<MesasnDto> data) throws JsonProcessingException {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.MESASN.getKeyword());

        if (jipHeaderConfig == null)
            throw new RuntimeException("MES中未配置成品MES入库接口接口信息");

        if (StringUtils.isBlank(jipHeaderConfig.getUrl()))
            throw new RuntimeException("MES中未配置成品MES入库接口接口URL请求地址");

        JipISBCINFO jipISBCINFO = JipUtil.initISBCINFO(jipHeaderConfig);
        TokenDto token = JipUtil.initToken(jipHeaderConfig);

        Map<String, Object> dataObj = new HashMap<>();
        dataObj.put("IS_BC_INFO", jipISBCINFO);//header信息
        dataObj.put("IT_DATA", data);

        //String dataJson = objectMapper.writeValueAsString(dataObj);
        String dataJson = JSON.toJSONString(dataObj);

        //2.发送工单消耗数据到SAP
        JSONObject result = null;
        try {
            if (!GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_COMMON_SWITCH, "wmsInterfaceSwitch", true)) {
                saveInteractiveLog("mes->wms", "成品MES入库接口接口", "sendMesasn", dataObj, "没有发给wms的数据");
                return;
            }
            result = JipRestUtils.post(jipHeaderConfig.getUrl(), JSONObject.parseObject(dataJson), token);

            //保存交互记录
            saveInteractiveLog("mes->wms", "成品MES入库接口接口", "sendMesasn", dataObj, result);

            JSONObject ES_BC_INFO = result.getJSONObject("ES_BC_INFO");
            if (!ES_BC_INFO.getString("TYPE").equals("S")) {
                throw new RuntimeException(ES_BC_INFO.getString("MSG"));
            }
        } catch (Exception e) {
            log.error("error_in_sendMesasn", e);
            saveInteractiveLog("mes->wms", "成品MES入库接口接口", "sendMesasn", dataObj, result);
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void sendrework(List<RemesstaDto> data) throws JsonProcessingException {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.REWORK.getKeyword());

        if (jipHeaderConfig == null)
            throw new RuntimeException("MES中未配置成品返工车间MES接收状态回传接口信息");

        if (StringUtils.isBlank(jipHeaderConfig.getUrl()))
            throw new RuntimeException("MES中未配置成品返工车间MES接收状态回传接口URL请求地址");

        JipISBCINFO jipISBCINFO = JipUtil.initISBCINFO(jipHeaderConfig);
        TokenDto token = JipUtil.initToken(jipHeaderConfig);

        Map<String, Object> dataObj = new HashMap<>();
        dataObj.put("IS_BC_INFO", jipISBCINFO);//header信息
        dataObj.put("IT_DATA", data);

        String dataJson = objectMapper.writeValueAsString(dataObj);

        //2.发送工单消耗数据到SAP
        JSONObject result = null;
        try {
            result = JipRestUtils.post(jipHeaderConfig.getUrl(), JSONObject.parseObject(dataJson), token);

            //保存交互记录
            saveInteractiveLog("mes->wms", "返工箱号车间接收/拒收状态信息接口", "sendrework", dataObj, result);

            JSONObject ES_BC_INFO = result.getJSONObject("ES_BC_INFO");
            if (!ES_BC_INFO.getString("TYPE").equals("S")) {
                throw new RuntimeException(ES_BC_INFO.getString("MSG"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    @Override
    public void synPlantStorage(String werks) throws JsonProcessingException {
        JipHeaderConfig jipHeaderConfig = jipHeaderConfigService.getByKeyword(IFKeyWordEnums.PLANTSTORAGE.getKeyword());

        if (jipHeaderConfig == null)
            throw new RuntimeException("MES中未配置成品返工车间MES接收状态回传接口信息");

        if (StringUtils.isBlank(jipHeaderConfig.getUrl()))
            throw new RuntimeException("MES中未配置成品返工车间MES接收状态回传接口URL请求地址");

        JipISBCINFO jipISBCINFO = JipUtil.initISBCINFO(jipHeaderConfig);
        TokenDto token = JipUtil.initToken(jipHeaderConfig);


        JSONArray it_data = new JSONArray();
        JSONObject item = new JSONObject();
        item.put("WERKS", werks);
        it_data.add(item);


        Map<String, Object> dataObj = new HashMap<>();
        dataObj.put("IS_BC_INFO", jipISBCINFO);//header信息
        dataObj.put("IT_DATA", it_data);

        String dataJson = objectMapper.writeValueAsString(dataObj);

        //2.发送工单消耗数据到SAP
        JSONObject result = null;
        try {
            result = JipRestUtils.post(jipHeaderConfig.getUrl(), JSONObject.parseObject(dataJson), token);

            //保存交互记录
            saveInteractiveLog("mes->wms", "返工箱号车间接收/拒收状态信息接口", "synPlantStorage", dataObj, result);

            JSONObject ES_BC_INFO = result.getJSONObject("ES_BC_INFO");
            if (!ES_BC_INFO.getString("TYPE").equals("S")) {
                throw new RuntimeException(ES_BC_INFO.getString("MSG"));
            }
        } catch (Exception e) {
        	 //保存交互记录
            saveInteractiveLog("mes->wms", "返工箱号车间接收/拒收状态信息接口", "synPlantStorage", dataObj, result);
            log.error("synPlantStorage",e);
            throw new RuntimeException(e.getMessage());
        }


    }


    // 保存原始记录到数据表
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private void saveInteractiveLog(String direction, String controllerName, String oprMethod, Object data, Object result) {
        try {
            LogWmsMesInteractive log = new LogWmsMesInteractive();
            log.setDataDirection(direction);
            log.setControllerName(controllerName);
            log.setOprMethod(oprMethod);
            log.setContext(JSONObject.toJSONString(data));
            log.setReturnContext(JSONObject.toJSONString(result));
            log.setCreateTime(new Date());
            logWmsMesInteractiveService.saveOrUpdate(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
