package com.aucma.api.service.impl;


import com.aucma.api.domain.dto.SAPPortDto;
import com.aucma.api.domain.dto.WERKSDto;
import com.aucma.api.domain.vo.SAPResultBomVo;
import com.aucma.api.domain.vo.SAPResultOrderInfoVo;
import com.aucma.api.domain.vo.SAPResultVo;
import com.aucma.api.service.ISAPPortService;
import com.aucma.api.service.ISAPPutStorageService;
import com.aucma.api.utils.ApiUtils;
import com.aucma.api.utils.SAPConstants;
import com.aucma.base.domain.BaseDeviceLedger;
import com.aucma.base.domain.BaseMaterialInfo;
import com.aucma.base.domain.BaseOrderInfo;
import com.aucma.base.domain.OrderBomInfo;
import com.aucma.common.exception.base.BaseException;
import com.aucma.common.utils.StringUtils;
import com.aucma.common.utils.http.HttpUtils;
import com.aucma.system.utils.PortLogUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author YinQ
 * @create 2023-09-26 14:34
 */
@Service
public class SAPPortServiceImpl implements ISAPPortService {

    @Autowired
    private ISAPPutStorageService storageService;


    /**
     * 获取SAP物料主数据
     *
     * @param sapPortDto
     * @return
     */
    @Override
    public List<BaseMaterialInfo> getSAPMaterialData(SAPPortDto sapPortDto) {
        String startDate = sapPortDto.getStartDate();
        String endDate = sapPortDto.getEndDate();
        WERKSDto werks = sapPortDto.getFactoryCodes();
        String intervalDate = "(" + startDate + "——" + endDate + ")";
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || StringUtils.isNull(werks)) {
            return null;
        }
        ArrayList<BaseMaterialInfo> materialVos = new ArrayList<>();
        String requestParam = null;
        String result = null;
        try {
            // 创建ObjectMapper实例 对象转JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            // 格式化输出
            // objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
            requestParam = objectMapper.writeValueAsString(sapPortDto);
            result = ApiUtils.sendSAPHttpPost(SAPConstants.SAP_PREFIX_URL + SAPConstants.MATERIAL_URL, requestParam);
            // 处理接口返回消息
            //  result = "{\"O_TAB\":{\"item\":[{\"MAKTX\":\"压缩机,GP14TG,R134a,ACC\",\"WERKS\":\"2004\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000125\"},{\"MAKTX\":\"压缩机,GP14TG,R134a,ACC\",\"WERKS\":\"2006\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000125\"},{\"MAKTX\":\"压缩机,NL7CLX,R404a,丹佛斯\",\"WERKS\":\"2004\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000126\"},{\"MAKTX\":\"压缩机,NL7CLX,R404a,丹佛斯\",\"WERKS\":\"2006\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000126\"},{\"MAKTX\":\"压缩机,HVY57AA,R600a,奥地利ACC\",\"WERKS\":\"2004\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000127\"},{\"MAKTX\":\"压缩机,HVY57AA,R600a,奥地利ACC\",\"WERKS\":\"2006\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000127\"},{\"MAKTX\":\"压缩机,HVY67AA,R600a,奥地利ACC\",\"WERKS\":\"2004\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000128\"},{\"MAKTX\":\"压缩机,HVY67AA,R600a,奥地利ACC\",\"WERKS\":\"2006\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000128\"},{\"MAKTX\":\"压缩机,MR22FB,R404a,ACC\",\"WERKS\":\"2004\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000129\"},{\"MAKTX\":\"压缩机,MR22FB,R404a,ACC\",\"WERKS\":\"2006\",\"MTART\":\"ROH\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-21\",\"MATNR\":\"000000003000000129\"},{\"MAKTX\":\"盖后加固体,BC/BD-127FA\",\"WERKS\":\"2004\",\"MTART\":\"HALB\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-06\",\"MATNR\":\"000000008106000102\"},{\"MAKTX\":\"SC-246,YZXGWB乳品\",\"WERKS\":\"2006\",\"MTART\":\"FERT\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-22\",\"MATNR\":\"000000009002003478\"},{\"MAKTX\":\"SD-460,YZXGW蒙牛冰品\",\"WERKS\":\"2004\",\"MTART\":\"FERT\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-22\",\"MATNR\":\"000000009000004735\"},{\"MAKTX\":\"BC-100E,特需\",\"WERKS\":\"2006\",\"MTART\":\"FERT\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-02\",\"MATNR\":\"000000009001002406\"},{\"MAKTX\":\"BD(C)-310T,特需\",\"WERKS\":\"2004\",\"MTART\":\"FERT\",\"MEINS\":\"EA\",\"UDATE\":\"2019-08-20\",\"MATNR\":\"000000009000000225\"}]},\"WERKS\":null,\"O_RETURN\":{\"item\":[{\"MESSAGE\":\"查询成功1！\",\"ID\":\" 0\",\"TYPE\":\"S\"}]}}";
            ObjectMapper resultMapper = new ObjectMapper();
            // 将 JSON 字符串 转换为 Java 对象
            SAPResultVo resultVo = resultMapper.readValue(result, SAPResultVo.class);
            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !"                  0".equals(resultVo.getO_RETURN().getItem().get(0).get("ID"))){
                Integer integer = Integer.valueOf(resultVo.getO_RETURN().getItem().get(0).get("ID"));
                if (integer!=0){
                    throw new BaseException("处理接口返回消息错误！（ID不为0或O_RETURN为空）");
                }
            }
            //转物料实体类 保存数据
            materialVos = storageService.insertSAPMaterialInfo(resultVo);
            //保存接口日志
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取SAP物料主数据" + intervalDate, "getSAPMaterialData", requestParam, result, null);
        } catch (Exception e) {
            //保存接口日志
            System.out.println(e.getMessage());
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取SAP物料主数据" + intervalDate, "getSAPMaterialData", requestParam, result, e.toString());
        }
        return materialVos;
    }

    /**
     * 获取生产工单
     * @param sapPortDto
     * @return
     */
    @Override
    public List<BaseOrderInfo> getSapBaseOrderInfo(SAPPortDto sapPortDto) {
        String startDate = sapPortDto.getStartDate();
        String endDate = sapPortDto.getEndDate();
        WERKSDto werks = sapPortDto.getFactoryCodes();
        String intervalDate = "(" + startDate + "——" + endDate + ")";
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || StringUtils.isNull(werks)) {
             return null;
        }
        ArrayList<BaseOrderInfo> baseOrderInfoVos = new ArrayList<>();
        String requestParam = null;
        String result = null;
        try{
            // 创建ObjectMapper实例 对象转JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            requestParam = objectMapper.writeValueAsString(sapPortDto);
            //发送post请求 调用获取工单接口
            result = ApiUtils.sendSAPHttpPost(SAPConstants.SAP_PREFIX_URL + SAPConstants.PRODUCTION_ORDERS_URL, requestParam);
            // 处理接口返回消息
            ObjectMapper resultMapper = new ObjectMapper();
            // 将 JSON 字符串转换为 Java 对象
            SAPResultOrderInfoVo resultVo = resultMapper.readValue(result, SAPResultOrderInfoVo.class);

            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !"                  0".equals(resultVo.getO_RETURN().getItem().get(0).get("ID"))){
                String id = resultVo.getO_RETURN().getItem().get(0).get("ID");
                Integer integer = Integer.valueOf(id);
                if (integer!=0&&integer!=null){
                throw new BaseException("处理接口返回消息错误！（ID不为0或O_RETURN为空）");
            }
            }
            //转物料实体类 保存数据
            baseOrderInfoVos = storageService.insertSAPBaseOrderInfo(resultVo);
            //保存接口日志
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取生产工单" + intervalDate, "getSAPBaseOrderInfo", requestParam, result, null);
        } catch (Exception e){
            //保存接口日志
            System.out.println(e.getMessage());
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取生产工单" + intervalDate, "getSAPBaseOrderInfo", requestParam, result, e.toString());

        }
         return baseOrderInfoVos;
    }

    /**
     * 获取设备台账
     * @param sapPortDto
     * @return
     */
    @Override
    public List<BaseDeviceLedger> getSapDeviceLedgers(SAPPortDto sapPortDto) {
        String startDate = sapPortDto.getStartDate();
        String endDate = sapPortDto.getEndDate();
        WERKSDto werks = sapPortDto.getFactoryCodes();
        String intervalDate = "(" + startDate + "——" + endDate + ")";
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || StringUtils.isNull(werks)) {
            return null;
        }
        ArrayList<BaseDeviceLedger> baseDeviceLedgersVos = new ArrayList<>();
        String requestParam = null;
        String result = null;
        try {
            // 创建ObjectMapper实例 对象转JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            requestParam = objectMapper.writeValueAsString(sapPortDto);
            result = ApiUtils.sendSAPHttpPost(SAPConstants.SAP_PREFIX_URL + SAPConstants.EQUIPMENT_URL, requestParam);
            // 处理接口返回消息
            ObjectMapper resultMapper = new ObjectMapper();
            // 将 JSON 字符串转换为 Java 对象
            SAPResultOrderInfoVo resultVo = resultMapper.readValue(result, SAPResultOrderInfoVo.class);
            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !"                  0".equals(resultVo.getO_RETURN().getItem().get(0).get("ID"))){
                throw new BaseException("处理接口返回消息错误！（ID不为0或O_RETURN为空）");
            }
            //转物料实体类 保存数据
            baseDeviceLedgersVos = storageService.insertSAPDeviceLedger(resultVo);
            //保存接口日志
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取设备台账数据" + intervalDate, "getSAPBaseDeviceLedger", requestParam, result, null);
        } catch (Exception e) {
            //保存接口日志
            System.out.println(e.getMessage());
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取设备台账数据" + intervalDate, "getSAPBaseDeviceLedger", requestParam, result, e.toString());
        }
        return baseDeviceLedgersVos;
    }

    /**
     * 获取产品bom信息
     * @param sapPortDto
     * @return
     */
    @Override
    public List<OrderBomInfo> getSapOrderBomInfo(SAPPortDto sapPortDto) {
        String startDate = sapPortDto.getStartDate();
        String endDate = sapPortDto.getEndDate();
        WERKSDto werks = sapPortDto.getFactoryCodes();
        String intervalDate = "(" + startDate + "——" + endDate + ")";
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate) || StringUtils.isNull(werks)) {
            return null;
        }
        ArrayList<OrderBomInfo> orderBomInfosVos = new ArrayList<>();
        String requestParam = null;
        String result = null;
        try {
            // 创建ObjectMapper实例 对象转JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            // 格式化输出
            // objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
            requestParam = objectMapper.writeValueAsString(sapPortDto);
            result = ApiUtils.sendSAPHttpPost(SAPConstants.SAP_PREFIX_URL + SAPConstants.PRODUCTS_BOM_URL, requestParam);
            // 处理接口返回消息
            ObjectMapper resultMapper = new ObjectMapper();
            // 将 JSON 字符串转换为 Java 对象
            SAPResultOrderInfoVo resultVo = resultMapper.readValue(result, SAPResultOrderInfoVo.class);
            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !"                  0".equals(resultVo.getO_RETURN().getItem().get(0).get("ID"))){
                String id = resultVo.getO_RETURN().getItem().get(0).get("ID");
                String s = id.replaceAll(" ", "");
                if (0!=Long.valueOf(s)){
                    throw new BaseException("处理接口返回消息错误！（ID不为0或O_RETURN为空）");
                }

            }
            //转物料实体类 保存数据
            orderBomInfosVos = storageService.insertSAPOrderBomInfo(resultVo);
            //保存接口日志
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取产品bom数据" + intervalDate, "getSapBaseBomInfo", requestParam, result, null);
        } catch (Exception e) {
            //保存接口日志
            System.out.println(e.getMessage());
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取产品bom数据" + intervalDate, "getSapBaseBomInfo", requestParam, result, e.toString());
        }
        return orderBomInfosVos;
    }


}
