package com.aucma.api.service.impl;


import com.aucma.api.domain.dto.SAPBOMPortDto;
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.DateUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.production.domain.CalendarInfo;
import com.aucma.system.utils.PortLogUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
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);
            // 处理接口返回消息
            ObjectMapper resultMapper = new ObjectMapper();
            // 将 JSON 字符串 转换为 Java 对象
            SAPResultVo resultVo = resultMapper.readValue(result, SAPResultVo.class);
            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !resultVo.getO_RETURN().getItem().get(0).get("ID").contains("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) {
            //保存接口日志
            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()) || !resultVo.getO_RETURN().getItem().get(0).get("ID").contains("0")){
                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()) || !resultVo.getO_RETURN().getItem().get(0).get("ID").contains("0")){
                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(SAPBOMPortDto sapPortDto) {
        String startDate = sapPortDto.getStartDate();
        String endDate = sapPortDto.getEndDate();
        WERKSDto werks = sapPortDto.getFactoryCodes();
        sapPortDto.setType("S");
        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 对象
            SAPResultBomVo resultVo = resultMapper.readValue(result, SAPResultBomVo.class);
            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !resultVo.getO_RETURN().getItem().get(0).get("ID").contains("0")){
                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) {
            //保存接口日志
            PortLogUtils.savePortLog(werks.getItem().get(0).get("WERKS"), "获取产品bom数据" + intervalDate, "getSapBaseBomInfo", requestParam, result, e.toString());
        }
        return orderBomInfosVos;
    }

    /**
     * 新增SAP生产日历
     * @param calendarInfo 生产日历
     * @return
     */
    @Override
    public int addSAPCalendar(CalendarInfo calendarInfo) {
        if (StringUtils.isNull(calendarInfo.getPlanStartDate())
                || StringUtils.isNull(calendarInfo.getPlanEndDate())){
            return 0;
        }
        SAPPortDto sapPortDto = new SAPPortDto();
        WERKSDto werksDto = new WERKSDto();
        List<HashMap<String, String>> factoryList = new ArrayList<>();
        HashMap<String, String> hashMap = new HashMap<>();
        sapPortDto.setStartDate(DateUtils.dateTime(calendarInfo.getPlanStartDate()));
        sapPortDto.setEndDate(DateUtils.dateTime(calendarInfo.getPlanEndDate()));
        hashMap.put("WERKS", "1301");
        factoryList.add(hashMap);
        werksDto.setItem(factoryList);
        sapPortDto.setFactoryCodes(werksDto);
        this.getSapBaseOrderInfo(sapPortDto);
        return 1;
    }

    /**
     * 获取生产工单测试
     * @param params
     * @return
     */
    @Override
    public List<BaseOrderInfo> getProduceWorkTest(String params) {
        // 处理接口返回消息
        ArrayList<BaseOrderInfo> baseOrderInfoVos = null;
        try {
            ObjectMapper resultMapper = new ObjectMapper();
            // 将 JSON 字符串转换为 Java 对象
            SAPResultOrderInfoVo resultVo = resultMapper.readValue(params, SAPResultOrderInfoVo.class);

            //判断返回数据是否正确
            if (StringUtils.isNull(resultVo.getO_RETURN()) || !resultVo.getO_RETURN().getItem().get(0).get("ID").contains("0")){
                throw new BaseException("处理接口返回消息错误！（ID不为0或O_RETURN为空）");
            }
            //转工单实体类 保存数据
            baseOrderInfoVos = storageService.insertSAPBaseOrderInfo(resultVo);
        } catch (JsonProcessingException | BaseException | ParseException e) {
            e.printStackTrace();
        }
        return baseOrderInfoVos;
    }
}
