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.SoSsCustomerService;
import com.santos.iost.utils.JsonUtil;
import com.santos.iost.vo.SoSsCreateVo;
import com.santos.iost.vo.SoSsRequestVo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SoSsCustomerServiceImpl implements SoSsCustomerService {

    @Autowired
    SoSsDao soSsDao;

    String Url;
    String setUrl;//拼接用请求地址-（http://127.0.0.1/K3API/Material/GetList?token=${token}）
    String setData;
    String fields;//需要查询出的字段
    /**
     * 请求字段
     */
    String FNumber = "FNumber";//代码
    String FName = "FName";//名称
    String FAddress = "FAddress";//地址
    String FRegionID = "FRegionID";//区域
    String FContact = "FContact";//联系人
    String FPhone = "FPhone";//联系人电话
    String Femployee = "Femployee";//专营业务员


    public SoSsCustomerServiceImpl() {
        this.Url="/K3API/Customer/GetList";
        this.setUrl = "/K3API/Customer/Save";//拼接用请求地址-（http://127.0.0.1/K3API/Material/GetList?token=${token}）
        this.fields ="FNumber,FName,FRegionID,Femployee,FContact,FPhone,FAddress";
        this.setData = "{\n" +
//                "    \"F_109\": {\n" +
//                "      \"FID\": \"003\"\n" +
//                "      \"FName\": \"重要客户\"\n" +
//                "    },\n" +
                "    \"FIsCreditMgr\": false,\n" +
                "    \"FlastRPAmount\": 0,\n" +
                "    \"FlastTradeAmount\": 0,\n" +
                "    \"FmaxDealAmount\": 0,\n" +
                "    \"FminForeReceiveRate\": 0,\n" +
                "    \"FminReserverate\": 0,\n" +
                "    \"FSaleMode\": {\n" +
                "      \"FID\": \"SIN\",\n" +
                "      \"FName\": \"内销\"\n" +
                "    },\n" +
                "    \"FStatus\": {\n" +
                "      \"FID\": \"ZT01\",\n" +
                "      \"FName\": \"使用\"\n" +
                "    },\n" +
                "    \"FValueAddRate\": 0\n" +
                "  }";

    }

    @Override
    public Result setData(SoSsCreateVo soSsRequestVo) throws Exception {
        Map map = JSON.parseObject(setData, Map.class, Feature.OrderedField);//固定格式

        Map params = new HashMap<>();
        Map<Object, Object> Data = new LinkedHashMap<>();
        Map masterFieldVal = soSsRequestVo.getMasterFieldVal();
//        Map masterFieldVal = new HashMap();
        Data.putAll(map);
        Data.put(FNumber, masterFieldVal.get("ERPNumber"));
        Data.put(FName, masterFieldVal.get("customerName"));
        Data.put(FAddress, masterFieldVal.get("detailedAddress"));
        Data.put(FRegionID, new HashMap() {{
            put("FID", masterFieldVal.get("customerLevel"));
//            put("FName", masterFieldVal.get("customerLevel"));
        }});//二级结构
        Data.put(FContact, masterFieldVal.get("contacts"));
        Data.put(FPhone, masterFieldVal.get("phone"));
        Data.put(Femployee, new HashMap() {{
//            put("FName", masterFieldVal.get("personCharge"));
            put("FNumber", masterFieldVal.get("personCharge"));
        }});//二级结构
        params.put("Data", Data);
        String s = soSsDao.setK3Api(Url, JsonUtil.Mapjson(params));

        SoSsResponseDate soSsResponseDate = JSON.parseObject(s, SoSsResponseDate.class, Feature.OrderedField);
        Result result = changeResponse(soSsResponseDate);//
        return result;
    }

    @Override
    public Result getDataById(SoSsRequestVo2 soSsRequestVo) {
        String s = new String();
        Map map = new HashMap();
        Map Data = new LinkedHashMap();

        Data.put("PageSize", 1);//每页行数
        Data.put("PageIndex", 1);//第几页
        Data.put("Filter", "FNumber = '" + soSsRequestVo.getDataId() + "'");//过滤条件
        Data.put("Fields", fields);//查询字段
        map.put("Data", Data);
        try {
            s = soSsDao.requestK3Api(Url, JsonUtil.Mapjson(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        SoSsResponseDate soSsResponseDate = JSON.parseObject(s, SoSsResponseDate.class, Feature.OrderedField);//转换数据类型

        Result result = changeResponse2(soSsResponseDate, soSsRequestVo);//转换返回的数据格式

        return result;
    }

    /*转换*/
    public Result changeResponse(SoSsResponseDate soSsRequestVo) {
        Map<Object, Object> map = new HashMap<>();
        Result result = new Result();
        try {//字段转换-变化soSsRequestVo的data参数格式 为CRM规定格式
            List data = (List) soSsRequestVo.getData();
            Object o = data.get(0);
            Map dataMap = JSON.parseObject(o.toString(), Map.class);
            Boolean fStatus = Boolean.parseBoolean(dataMap.get("FStatus").toString());
            if (fStatus.equals(true)) {

                map.put("objAPIName", apiName);
                map.put("masterDataId", dataMap.get(FNumber));
                map.put("detailDataIds",new HashMap<>());
                soSsRequestVo.setData(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //将ERP格式变换为CRM格式
        result.setMessage(soSsRequestVo.getMessage());
        result.setCode(soSsRequestVo.getStatusCode());
        result.setData(soSsRequestVo.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");
            System.out.println(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<>();

                masterFieldVal.put("ERPNumber", listDateMap.get(FNumber));//
                masterFieldVal.put("customerName", listDateMap.get(FName));//
                masterFieldVal.put("detailedAddress", listDateMap.get(FAddress));//
                masterFieldVal.put("customerLevel", listDateMap.get(FRegionID+"_FID"));//
                masterFieldVal.put("contacts", listDateMap.get(FContact));//
                masterFieldVal.put("phone", listDateMap.get(FPhone));//
                masterFieldVal.put("personCharge", listDateMap.get(Femployee+"_FNumber"));//

//                if (null == RequestVo.getIncludeDetail() || false == RequestVo.getIncludeDetail()) {
//                } else if (null != RequestVo.getIncludeDetail() && true == RequestVo.getIncludeDetail()) {
//                    map = getDetail(listDateMap.get(FBillNo).toString());
//                }
                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;
    }
}
