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;
          String InterfaceName="SALES_ORDERS/SALES"; //客户异常 查询销售订单接口
        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())&&"3".equals(queryRequest.getReasonType())) { //客户编号
            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);
                if ("3".equals(queryRequest.getReasonType())) { //如果是客户异常
                    orderQueryVo.setBSTNK(vbelnList);
                } else {   // 是生产异常
                    orderQueryVo.setAUFNR(vbelnList);
                }
       }
        if ("3".equals(queryRequest.getReasonType())){ //如果是客户异常
                List <SignVo>auartList=new ArrayList<>();
                signVo=new SignVo();
                signVo.setLow("ZDO");
                auartList.add(signVo);
                SignVo signVo2=new SignVo();
                signVo2.setLow("ZEO");
                auartList.add(signVo2);
                orderQueryVo.setAUART(auartList);
         } else{  //生产异常
                InterfaceName="SEARCH/SCH_AUFNR";
         }

        if  (StringUtils.isNotBlank(queryRequest.getVbeln())&&"3".equals(queryRequest.getReasonType())) { //客户单号

             signVo=new SignVo();
             signVo.setLow(queryRequest.getVbeln());
             List <SignVo> vbelnList=new ArrayList<>();
             vbelnList.add(signVo);
             orderQueryVo.setBSTNK(vbelnList);
        }
           Object obj =  JSONObject.toJSON(orderQueryVo);
        try {
            String json ="";
            List<Map<String, Object>> mapList=new ArrayList<>();
            if ("3".equals(queryRequest.getReasonType())) { //如果是客户异常
                if (StringUtils.isNotBlank(queryRequest.getParamValue())||StringUtils.isNotBlank(queryRequest.getVbeln())) {  //必须输入参数
                     json = httpClient.execute(obj, InterfaceName);
                     mapList = JSONUtil.toListMap(json);
                }
            } else {  //生产异常
                 Map<String,Object> param = new HashMap<>();
                 param.put("BUKRS",queryRequest.getWerks());
                 if (StringUtils.isNotBlank(queryRequest.getVbeln())){ //生产订单号
                     param.put("AUFNR",queryRequest.getVbeln());
                 }
                if (StringUtils.isNotBlank(queryRequest.getParamValue())){
                    param.put("AUFNR",queryRequest.getParamValue());
                }
                 List<Map<String,String>> mapList2 = new ArrayList<>();
                 json=httpClient.execute(param, "search/sch_aufnr");
                 Map<String, String> map = JSONObject.parseObject(json, Map.class);
                SapResult sapResult = JSONObject.parseObject(cn.hutool.json.JSONUtil.toJsonStr(map.get("MSG")), SapResult.class);
                if ("S".equals(sapResult.getTYPE())) {
                    ObjectMapper objectMapper = SAPUtils.objectMapper();
                    mapList2 = objectMapper.readValue(com.huigou.util.JSONUtil.toString(map.get("RDATA")), new TypeReference<List<Map<String, String>>>() {
                    });
                    if (StringUtils.isNotBlank(queryRequest.getVbeln())) {
                        for (Map mapItem : mapList2) {
                            Map newMap = new HashMap();
                            newMap.put("MATNR", mapItem.get("PLNBEZ"));  //物料编号
                            newMap.put("MAKTX", mapItem.get("MAKTX"));  //物料描述
                            newMap.put("PSMNG", mapItem.get("GAMNG"));  //数量
                            newMap.put("MEINS", mapItem.get("GMEIN"));  //单位

                            sapOrderVoList.add(newMap);
                        }
                    } else {

                        for (Map mapItem : mapList2) {
                            Map newMap = new HashMap();
                            newMap.put("VBELN", mapItem.get("AUFNR"));  //订单号
                            newMap.put("KTEXT", mapItem.get("KTEXT"));  //订单描述
                            newMap.put("MATNR", mapItem.get("PLNBEZ"));  //物料编号
                            newMap.put("MAKTX", mapItem.get("MAKTX")!=null?mapItem.get("MAKTX"):"");  //物料描述
                            newMap.put("PSMNG", mapItem.get("GAMNG"));  //数量
                            newMap.put("MEINS", mapItem.get("GMEIN"));  //单位
                            if (StringUtils.isNotBlank(queryRequest.getParamValue())
                               &&mapItem.get("AUFNR").toString().indexOf(queryRequest.getParamValue())>-1
                            ) {  //过滤参数
                                sapOrderVoList.add(newMap);
                                break;
                            }
                            //sapOrderVoList.add(newMap);
                        }
                    }
                }
            }
         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")); //生产数量
                     String sendDate="";
                     if (!"00000000".equals(mapItem.get("LFDAT").toString())){
                       sendDate=mapItem.get("LFDAT").toString();
                       sendDate=sendDate.substring(0,4)+"-"+sendDate.substring(4,6)+"-"+sendDate.substring(6,8);
                     }
                     newMap.put("LFDAT", sendDate);               //出货日期

                     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   如果是客户异常需要 增加过滤条件"AUART"字段值是: "ZDO"或者"ZEO" 返回是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;
    }
}
