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.SoSsSalesInvoiceService;
import com.santos.iost.utils.JsonUtil;
import com.santos.iost.utils.StringUtil;
import com.santos.iost.vo.SoSsRequestVo;
import com.santos.iost.vo.SoSsRequestVo2;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

//开票
@Service
public class SoSsSalesInvoiceServiceImpl implements SoSsSalesInvoiceService {
    @Autowired
    SoSsDao soSsDao;

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

    /**
     * K3金蝶方请求字段
     */
    String FCustID = "FCustID";//购货单位
    String FCustID_FNDName ="FCustID_FNDName";//
    String FCustID_DSPName = "FCustID_DSPName";
    //    String SJKPRQ80 = "SJKPRQ80";//实际开票日期
    String Fdate = "Fdate";//日期
    String FBillNo = "FBillNo";//FBillNo
    String FHeadSelfI0471 = "FHeadSelfI0471";//出库单编号
    String FEmpID = "FEmpID";//业务员

    /**
     * K3金蝶方请求字段-明细字段
     */
    String FItemID = "FItemID";//产品代码
    String Fauxqty = "Fauxqty";//数量
    String FAuxPriceDiscount = "FAuxPriceDiscount";//实际含税单价
    String FAllAmount = "FAllAmount";//价税合计
    String FOrderBillNo="FOrderBillNo";//订单单号
    String FOrderEntryID ="FOrderEntryID";//订单分录

    public SoSsSalesInvoiceServiceImpl() {
        this.Url = "/K3API/Sales_Invoice_VAT/GetList";//拼接用请求地址-（http://127.0.0.1/K3API/Material/GetList?token=${token}）
        this.includeDetailUrl = "/K3API/Sales_Invoice_VAT/GetDetail";
        this.fields = "FEmpID,FCustID,SJKPRQ80,FHeadSelfI0471";//需要查询出的字段
    }

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

    @Override
    public Result getDataById(SoSsRequestVo2 soSsRequestVo) {
        String s = new String();
        Map map = new HashMap();
        Map Data = new LinkedHashMap();
        Data.put("Top", 1);//返回行数
        Data.put("PageSize", 1);//每页行数
        Data.put("PageIndex", 1);//第几页
        Data.put("Filter", "FBillNo = '" + soSsRequestVo.getDataId() + "'");//过滤条件
        Data.put("OrderBy", "[FBillNo] asc");//排序规则
        Data.put("SelectPage", "1");//表体索引，文档默认为2
        Data.put("Fields", fields);//查询字段
        map.put("Data", Data);
        try {
            s = soSsDao.requestK3Api(Url, JsonUtil.Mapjson(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(s);
        SoSsResponseDate soSsResponseDate = JSON.parseObject(s, SoSsResponseDate.class, Feature.OrderedField);//转换数据类型
        Result result = changeResponse2(soSsResponseDate, soSsRequestVo);//转换返回的数据格式
        return result;
    }


    /*转换请求参数*/
    public Map changeGeta(SoSsRequestVo soSsRequestVo) {
        Map paramsMap = new HashMap();
        Map Data = new LinkedHashMap();
        Data.put("Top", soSsRequestVo.getLimit() * soSsRequestVo.getOffset());//返回行数
        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 + "] >= '" + "2021-08-01 00:00:00" + "' and [" + Fdate + "] < '" + "2021-12-31 00:00:00" + "'";
        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("customerId",listDateMap.get(FCustID_FNDName).toString());//客户编号
            masterFieldVal.put("customerName", listDateMap.get(FCustID_DSPName));//客户名称
            masterFieldVal.put("billingDate", listDateMap.get(Fdate));//开票日期
            //            masterFieldVal.put("billingDate", listDateMap.get(Fdate));//开票日期
            masterFieldVal.put("invoiceNumber", listDateMap.get(FBillNo));//发票号码
            masterFieldVal.put("shipmentNo", listDateMap.get(FHeadSelfI0471));//发货单号
            masterFieldVal.put("personCharge", listDateMap.get(FEmpID+"_FNDName"));//业务员

            masterField.put("objAPIName", apiName);
            masterField.put("masterFieldVal", masterFieldVal);
            masterField.put("detailFieldVals", new HashMap<>());
            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<>();
            Object personCharge=new Object();
            masterFieldVal.put("customerId",listDateMap.get(FCustID_FNDName).toString());//客户编号
            masterFieldVal.put("customerName", listDateMap.get(FCustID_DSPName));//客户名称
            masterFieldVal.put("billingDate", listDateMap.get(Fdate));//开票日期
            //            masterFieldVal.put("billingDate", listDateMap.get(Fdate));//开票日期
            masterFieldVal.put("invoiceNumber", listDateMap.get(FBillNo));//发票号码
            masterFieldVal.put("shipmentNo", listDateMap.get(FHeadSelfI0471));//发货单号
            personCharge = listDateMap.get(FEmpID + "_FNDName");
            masterFieldVal.put("personCharge", personCharge);//业务员

            masterField.put("objAPIName", apiName);
            masterField.put("masterFieldVal", masterFieldVal);
            masterField.put("detailFieldVals", getDetail(listDateMap.get(FBillNo).toString(),personCharge));
            dataList.add(masterField);
        }
        return dataList;
    }

    Map getDetail(String code,Object personCharge) {//获取明细并且转换为需要的格式
        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);//转换数据类型
                JSONObject fromObject = JSONObject.fromObject(soSsResponseDate.getData().toString());//转换数据类型
                List list = JSON.parseObject(fromObject.get("Page2").toString(), List.class, Feature.OrderedField);

                List<Map> mapList = new ArrayList<>();
                for (Object o : list) {
                    Map listDateMap = JSON.parseObject(o.toString(), Map.class);
                    Map<String, Object> map = new LinkedHashMap();
//                    map.put("ERPSystemNumber",code);//主体唯一
                    map.put("ERPUniCode", listDateMap.get("FDetailID2"));//子体唯一
                    map.put("productCode", JSONObject.fromObject(listDateMap.get(FItemID)).get("FNumber"));//产品编码
                    map.put("productId", JSONObject.fromObject(listDateMap.get(FItemID)).get("FNumber").toString());//产品编号
                    map.put("quantity", listDateMap.get(Fauxqty));//数量
                    map.put("salesUnitPrice", listDateMap.get(FAuxPriceDiscount));//销售单价
                    map.put("thisInvoicingSubtotal", listDateMap.get(FAllAmount));//本次开票小计
                    map.put("saleOrderId",listDateMap.get(FOrderBillNo).toString());//销售订单编号
                    map.put("orderProductId",listDateMap.get(FOrderEntryID).toString());//订单产品编号
                    map.put("personCharge",personCharge);//业务员
                    mapList.add(map);
                }
                returnDate.put("InvoiceDetail", mapList);
            } 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", list.size());
            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;
    }

    /*转换*/
    public Result changeResponse2(SoSsResponseDate ResponseDate, SoSsRequestVo2 RequestVo) {
        Map<Object, Object> masterField = new LinkedHashMap<>();
        Result result = new Result();
        try {//字段转换-变化soSsRequestVo的data参数格式 为CRM规定格式
            Map data = (Map) ResponseDate.getData();
            Object data1 = data.get("DATA");
            List list = JSON.parseObject(data1.toString(), List.class, Feature.OrderedField);
//            masterField.put("objAPIName", apiName);
//            masterField.put("masterFieldVal", new HashMap<>());
//            masterField.put("detailFieldVals", new HashMap<>());
            for (Object o : list) {
                Map map = new HashMap<>();
                Map listDateMap = JSON.parseObject(o.toString(), Map.class, Feature.OrderedField);
                Map masterFieldVal = new LinkedHashMap<>();
                Object personCharge=new Object();
                masterFieldVal.put("customerId",listDateMap.get(FCustID_FNDName));//客户编号
                masterFieldVal.put("customerName", listDateMap.get(FCustID_DSPName));//客户名称
                masterFieldVal.put("billingDate", listDateMap.get(Fdate));//开票日期
                //            masterFieldVal.put("billingDate", listDateMap.get(Fdate));//开票日期
                masterFieldVal.put("invoiceNumber", listDateMap.get(FBillNo));//发票号码
                masterFieldVal.put("shipmentNo", listDateMap.get(FHeadSelfI0471));//发货单号
                personCharge = listDateMap.get(FEmpID + "_FNDName");
                masterFieldVal.put("personCharge", personCharge);//业务员

                if (null == RequestVo.getIncludeDetail() || false == RequestVo.getIncludeDetail()) {
                } else if (null != RequestVo.getIncludeDetail() && true == RequestVo.getIncludeDetail()) {
                    map = getDetail(listDateMap.get(FBillNo).toString(),personCharge);
                }
                masterField.put("objAPIName", apiName);
                masterField.put("masterFieldVal", masterFieldVal);
                masterField.put("detailFieldVals", map);
            }
            ResponseDate.setData(masterField);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

        return result;
    }
}
