package com.santos.iost.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.santos.iost.dao.SoSsDao;
import com.santos.iost.dto.Result;
import com.santos.iost.dto.SoSsResponseDate;
import com.santos.iost.service.SoSsSalesDeliveryService;
import com.santos.iost.utils.JsonUtil;
import com.santos.iost.utils.StringUtil;
import com.santos.iost.vo.SoSsRequestVo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
//发货单
@Service
public class SoSsSalesDeliveryServiceImpl implements SoSsSalesDeliveryService {
    @Autowired
    SoSsDao soSsDao;

    String Url;//拼接用请求地址-（http://127.0.0.1/K3API/Material/GetList?token=${token}）
    String includeDetailUrl;
    String fields;//需要查询出的字段

    /**
     * K3金蝶方请求字段
     */
    String FSupplyID = "FSupplyID";//购货单位
    String FHeadSelfB0162 = "FHeadSelfB0162";//地址
    String FBillNo = "FBillNo";//编号
    String Fdate = "Fdate";//日期
    String FHeadSelfB0159 = "FHeadSelfB0159";//物流公司
    String FHeadSelfB0157 = "FHeadSelfB0157";//物流单号
    String FExplanation = "FExplanation";//摘要
    /**
     * K3金蝶方请求字段-明细字段
     */
    String FItemID = "FItemID";//产品代码
    String FItemName = "FItemName";//产品名称
    String FEntrySelfB0164 = "FEntrySelfB0164";//中文描述
    String FUnitID = "FUnitID";//单位
    String FConsignPrice = "FConsignPrice";//销售单价
    String FConsignAmount = "FConsignAmount";//销售金额
    String FAuxQtyMust = "FAuxQtyMust";//应发数量
    String Fauxqty = "Fauxqty";//实发数量
    String FEntrySelfB0165 = "FEntrySelfB0165";//未发数量
    String FDCStockID1 = "FDCStockID1";//发货仓库
    String FOrderBillNo = "FOrderBillNo";//订单单号

    public SoSsSalesDeliveryServiceImpl() {
        this.Url = "/K3API/Sales_Delivery/GetList";//拼接用请求地址-（http://127.0.0.1/K3API/Material/GetList?token=${token}）
        this.includeDetailUrl = "/K3API/Sales_Delivery/GetDetail";
        this.fields = "FSupplyID,FHeadSelfB0162,FHeadSelfB0173,FHeadSelfB0159,FExplanation";//需要查询出的字段
    }

    @Override
    public Result getData(SoSsRequestVo soSsRequestVo) {
        String s = new String();
        Map map = changeGeta(soSsRequestVo);
        try {
            s = soSsDao.requestK3Api(Url, JsonUtil.Mapjson(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        SoSsResponseDate soSsResponseDate = JSON.parseObject(s, SoSsResponseDate.class, Feature.OrderedField);//转换数据类型
        Result result = changeResponse(soSsResponseDate, soSsRequestVo);//转换返回的数据格式
        return result;
    }


    /*转换请求参数*/
    public Map changeGeta(SoSsRequestVo soSsRequestVo) {
        Map paramsMap = new HashMap();
        Map Data = new LinkedHashMap();
        Data.put("Top",soSsRequestVo.getLimit());//返回行数
        Data.put("PageSize", soSsRequestVo.getLimit());//每页行数
        Data.put("PageIndex", soSsRequestVo.getOffset());//第几页
        if (checkFilter(soSsRequestVo)) {
            Data.put("Filter", setFilter(soSsRequestVo));//过滤条件
        }
        Data.put("OrderBy", "[FBillNo] asc");//排序规则
        Data.put("SelectPage", "1");//表体索引，文档默认为2
        Data.put("Fields", fields);//查询字段
        paramsMap.put("Data", Data);
        return paramsMap;
    }

    //检查ERM日期是否可用作过滤条件
    boolean checkFilter(SoSsRequestVo soSsRequestVo) {
        if (null == soSsRequestVo.getStartTime() && null == soSsRequestVo.getEndTime()) {
            return false;
        }
        return true;
    }

    //配置过滤条件
    String setFilter(SoSsRequestVo soSsRequestVo) {
        String startTime = StringUtil.TimeStamp2Date(soSsRequestVo.getStartTime(), null);
        String endTime = StringUtil.TimeStamp2Date(soSsRequestVo.getEndTime(), null);
        return "[" + Fdate + "] >= '" + startTime + "' and [" + Fdate + "] < '" + endTime + "'";
    }

    List includeDetailFalse(List list) {
        List dataList = new ArrayList<>();
        for (Object o : list) {
            Map listDateMap = JSON.parseObject(o.toString(), Map.class, Feature.OrderedField);
            Map masterField = new LinkedHashMap<>();
            Map masterFieldVal = new LinkedHashMap<>();
            masterFieldVal.put("customerName", listDateMap.get(FSupplyID));//客户名称
            masterFieldVal.put("customerAddress", listDateMap.get(FHeadSelfB0162));//客户地址
            masterFieldVal.put("erpNumber", listDateMap.get(FBillNo));//erp编号
            masterFieldVal.put("orderDate", listDateMap.get(Fdate));//下单日期
            masterFieldVal.put("logisticsCompany", listDateMap.get(FHeadSelfB0159));//物流公司
            masterFieldVal.put("logisticsOrderNo", listDateMap.get(FHeadSelfB0157));//物流单号
            masterFieldVal.put("remarks", listDateMap.get(FExplanation));//备注

            masterField.put("masterFieldVal", masterFieldVal);
            dataList.add(masterField);
        }
        return dataList;
    }

    List includeDetailTrue(List list) {
        List dataList = new ArrayList<>();
        for (Object o : list) {
            Map listDateMap = JSON.parseObject(o.toString(), Map.class, Feature.OrderedField);
            Map masterField = new LinkedHashMap<>();
            Map masterFieldVal = new LinkedHashMap<>();
            masterFieldVal.put("customerName", listDateMap.get(FSupplyID));//客户名称
            masterFieldVal.put("customerAddress", listDateMap.get(FHeadSelfB0162));//客户地址
            masterFieldVal.put("erpNumber", listDateMap.get(FBillNo));//erp编号
            masterFieldVal.put("orderDate", listDateMap.get(Fdate));//下单日期
            masterFieldVal.put("logisticsCompany", listDateMap.get(FHeadSelfB0159));//物流公司
            masterFieldVal.put("logisticsOrderNo", listDateMap.get(FHeadSelfB0157));//物流单号
            masterFieldVal.put("remarks", listDateMap.get(FExplanation));//备注
            masterField.put("masterFieldVal", masterFieldVal);
            masterField.put("detailFieldVals", getDetail(listDateMap.get(FBillNo).toString()));
            dataList.add(masterField);
        }
        return dataList;
    }

    Map getDetail(String code) {//获取明细并且转换为需要的格式
        Map returnDate = new LinkedHashMap();
        Map paramsMap = new HashMap();
        Map requestData = new HashMap();
        requestData.put(FBillNo, code);
        paramsMap.put("Data", requestData);

        try {
            String s = soSsDao.requestK3ApiDetail(includeDetailUrl, JsonUtil.Mapjson(paramsMap));
            SoSsResponseDate soSsResponseDate = JSON.parseObject(s, SoSsResponseDate.class);//转换数据类型
            if (null != soSsResponseDate.getStatusCode() && soSsResponseDate.getStatusCode().equals("200")) {
                Map Data = JSON.parseObject(soSsResponseDate.getData().toString(), Map.class);//转换数据类型
                List list = JSON.parseObject(Data.get("Page2").toString(), List.class, Feature.OrderedField);
                int i = 1;
                for (Object o : list) {
                    Map listDateMap = JSON.parseObject(o.toString(), Map.class);
                    Map<String, Object> map = new LinkedHashMap();

                    map.put("productCode", JSONObject.fromObject(listDateMap.get(FItemID)).get("FNumber"));//产品编号
                    map.put("productName", listDateMap.get(FItemName));//产品名称
                    map.put("chineseDescription", listDateMap.get(FEntrySelfB0164));//中文描述
                    map.put("company", JSONObject.fromObject(listDateMap.get(FUnitID)).get("FNumber"));//单位
                    map.put("salesUnitPrice", listDateMap.get(FConsignPrice));//销售单价
                    map.put("shipmentAmount", listDateMap.get(FConsignAmount));//发货金额
                    map.put("orderProductQuantity", listDateMap.get(FAuxQtyMust));//订单产品数量
                    map.put("thisShipmentQuantity", listDateMap.get(Fauxqty));//本次发货数量
                    map.put("undeliveredQuantity", listDateMap.get(FEntrySelfB0165));//未发货数
                    map.put("deliveryWarehouse", JSONObject.fromObject(listDateMap.get(FDCStockID1)).get("FNumber"));//发货仓库
                    map.put("orderProductNumber", listDateMap.get(FOrderBillNo));//订单产品编号
                    returnDate.put(apiName + i, new ArrayList<Map>() {{
                        add(map);
                    }});
                    i++;
                }
            } else {
                Map<String, Object> map = new LinkedHashMap();
                map.put("message", soSsResponseDate.getMessage());
                map.put("data", soSsResponseDate.getData());
                returnDate.put("error", new ArrayList<Map>() {{
                    add(map);
                }});
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return returnDate;
    }


    /*转换*/
    public Result changeResponse(SoSsResponseDate ResponseDate, SoSsRequestVo RequestVo) {
        Map<Object, Object> map = new HashMap<>();
        Result result = new Result();

        try {//字段转换-变化soSsRequestVo的data参数格式 为CRM规定格式
            List dataList = new ArrayList<>();
            Map data = (Map) ResponseDate.getData();
            Object data1 = data.get("DATA");
            List list = JSON.parseObject(data1.toString(), List.class, Feature.OrderedField);
            if (null == RequestVo.getIncludeDetail() || false == RequestVo.getIncludeDetail()) {
                dataList = includeDetailFalse(list);
            } else if (null != RequestVo.getIncludeDetail() && true == RequestVo.getIncludeDetail()) {
                dataList = includeDetailTrue(list);
            }
            map.put("totalNum", data.get("ROWCOUNT"));
            map.put("dataList", dataList);
            ResponseDate.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将ERP格式变换为CRM格式
        result.setMessage(ResponseDate.getMessage());
        result.setCode(ResponseDate.getStatusCode());
        result.setData(ResponseDate.getData());

        return result;
    }
}
