package com.huigou.topsun.sap.sapApplication.application.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.topsun.sap.common.HttpClient;
import com.huigou.topsun.sap.common.domain.SapResult;
import com.huigou.topsun.sap.sapApplication.domain.query.SapDialogOrderQuery;
import com.huigou.topsun.sap.sapApplication.domain.query.SapDialogQuery;
import com.huigou.topsun.sap.sapApplication.application.SapMaterialApplication;
import com.huigou.topsun.sap.sapApplication.domain.vo.OrderQueryVo;

import com.huigou.topsun.sap.sapApplication.domain.vo.SignVo;
import com.huigou.topsun.util.SAPUtils;
import com.huigou.util.JSONUtil;
import com.huigou.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @Auther: xin.lu
 * @Date: 2024/03/03/11:13
 * @Description:
 */
@Service("sapMaterialApplication")
public class SapMaterialApplicationImpl implements SapMaterialApplication {
    @Resource
    private HttpClient httpClient;
    @Override
    public List<Map<String,String>> getSapMaterial(SapDialogQuery queryRequest) throws IOException {
        List<Map<String,String>>  sapMaterialVoList = new ArrayList<>();
        /*if (StringUtil.isBlank(queryRequest.getWerks()) || StringUtil.isBlank(queryRequest.getMatkl())){
            return sapMaterialVoList;
        }*/
        if  (queryRequest.getMaktx()==null){
            queryRequest.setMaktx("");
        }
        if  (queryRequest.getMatkl()==null){
            queryRequest.setMatkl("");
        }
        String json = httpClient.execute(queryRequest, "search/sch_matnr");
        Map<String, Object> map = JSONUtil.toMap(json);
        SapResult sapResult = JSONObject.parseObject(JSONUtil.toString(map.get("MSG")), SapResult.class);
        if ("S".equals(sapResult.getTYPE())){
            ObjectMapper objectMapper = SAPUtils.objectMapper();
            sapMaterialVoList = objectMapper.readValue(JSONUtil.toString(map.get("RDATA")), new TypeReference<List<Map<String, String>>>() {});
            //sapMaterialVoList = (List<Map<String,String>>) JSONArray.parse(JSONUtil.toString(map.get("RDATA")));
        }
//        else {
//            throw new RuntimeException("查询物料失败："+sapResult.getMESSAGE());
//        }
        return sapMaterialVoList;
    }


    @Override
    public List<Map<String, String>>  getSapCustomerOrder(SapDialogOrderQuery queryRequest) throws IOException {
        List<Map<String,String>>  sapOrderVoList= new ArrayList<>();

          OrderQueryVo orderQueryVo=new OrderQueryVo();
          SignVo signVo=null;
        if  (StringUtils.isNotBlank(queryRequest.getWerks())) { //工厂
            signVo=new SignVo();
            signVo.setLow(queryRequest.getWerks());
            List <SignVo> werksList=new ArrayList<>();
            werksList.add(signVo);
            orderQueryVo.setWERKS(werksList);
        }
        if  (StringUtils.isNotBlank(queryRequest.getKunnr())) { //客户
            signVo=new SignVo();
            signVo.setLow(queryRequest.getKunnr());
            List <SignVo> kunnrList=new ArrayList<>();
            kunnrList.add(signVo);
            orderQueryVo.setKUNNR(kunnrList);
            if (StringUtils.isNotBlank(queryRequest.getParamValue())) {  //过滤参数
                signVo=new SignVo();
                signVo.setLow("*"+queryRequest.getParamValue()+"*");
                signVo.setOption("CP");
                List <SignVo> vbelnList=new ArrayList<>();
                vbelnList.add(signVo);
                orderQueryVo.setVBELN(vbelnList);
            }
        }
        if  (StringUtils.isNotBlank(queryRequest.getVbeln())) { //客户销售订单号
             signVo=new SignVo();
            signVo.setLow(queryRequest.getVbeln());
            List <SignVo> vbelnList=new ArrayList<>();
            vbelnList.add(signVo);
            orderQueryVo.setVBELN(vbelnList);
        }
           Object obj =  JSONObject.toJSON(orderQueryVo);
        try {
         String json = httpClient.execute(obj, "SALES_ORDERS/SALES");
         List<Map<String, Object>> mapList = JSONUtil.toListMap(json);
         if (StringUtils.isNotBlank(queryRequest.getVbeln())) { //按生产订单号
             for (Map map : mapList) {
                 Map newMap = new HashMap();
                 List<Map<String, Object>> mapList2=(List<Map<String, Object>>)map.get("ITEM");
                 for (Map mapItem:mapList2) {
                     newMap.put("MATNR", mapItem.get("MATNR"));  //物料编号
                     newMap.put("MAKTX", mapItem.get("MAKTX"));   //物料名称
                     newMap.put("AUFNR", mapItem.get("AUFNR"));  //生产单号
                     newMap.put("PSMNG", mapItem.get("PSMNG")); //生产数量
                     newMap.put("LFDAT", mapItem.get("LFDAT"));               //出货日期

                     newMap.put("MEINS", mapItem.get("MEINS_O"));               //单位
                     // KPEIN //定价单位
                     newMap.put("KWERT", mapItem.get("KWERT"));  //       //折前总金额
                     newMap.put("KOEIN", mapItem.get("KOEIN")); //         币别
                     if (StringUtils.isNotBlank(queryRequest.getParamValue())){  //过滤参数
                         if (mapItem.get("MATNR").toString().contains(queryRequest.getParamValue())
                            ||mapItem.get("MAKTX").toString().contains(queryRequest.getParamValue())
                            ||mapItem.get("AUFNR").toString().contains(queryRequest.getParamValue())
                          ){
                             sapOrderVoList.add(newMap);
                         }
                     } else {
                         sapOrderVoList.add(newMap);
                     }
                 }
             }
         } else if  (StringUtils.isNotBlank(queryRequest.getKunnr())) {  //查询订单号
             for (Map map : mapList) {
                 Map newMap = new HashMap();
                 //newMap.put("VBELN", map.get("VBELN"));
                 newMap.put("VBELN", map.get("BSTNK"));  //09.21冯朝阳要求改为BSTNK
                 newMap.put("KUNNR", map.get("KUNNR"));
                 newMap.put("NAME1", map.get("NAME1"));
                 sapOrderVoList.add(newMap);
             }
         } else {  //仅查询客户
             for (Map map : mapList) {
                 Map newMap = new HashMap();
                 newMap.put("KUNNR", map.get("KUNNR"));
                 newMap.put("NAME1", map.get("NAME1"));
                 sapOrderVoList.add(newMap);
             }
         }
        // ObjectMapper objectMapper = SAPUtils.objectMapper();
        // sapOrderVoList = objectMapper.readValue(JSONUtil.toString(json), new TypeReference<List<Map<String, String>>>() {
        // });

     } catch (Exception ex){
         throw new RuntimeException("查询客户订单失败："+ex.getMessage());
         //ex.printStackTrace();
     }
        return sapOrderVoList;
    }
}
