package com.santos.iost.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.santos.iost.Exception.SoSsRequestException;
import com.santos.iost.dao.SoSsDao;
import com.santos.iost.dto.Result;
import com.santos.iost.dto.SoSsResponseDate;
import com.santos.iost.service.SoSsMaterialService;
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 jdk.nashorn.internal.codegen.CompilerConstants;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

//客户
@Service
public class SoSsMaterialServiceImpl implements SoSsMaterialService {
    @Autowired
    SoSsDao soSsDao;

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

    /**
     * 请求字段
     */
    String FNumber = "FNumber";
    String FName = "FName";
    String F_101 = "F_101";
    String FSalePrice = "FSalePrice";
    String FUnitID = "FUnitID";
    String FUnitID_FName = "FUnitID_FName";
    String FUnitID_FNumber = "FUnitID_FNumber";
    String F_116_FName = "F_116_FName";
    String F_116_FNumber = "F_116_FNumber";
    String F_117 = "F_117";
    String F_117_FName = "F_117_FName";
    String F_117_FNumber = "F_117_FNumber";

    public SoSsMaterialServiceImpl() {
        this.Url = "/K3API/Material/GetList";//拼接用请求地址-（http://127.0.0.1/K3API/Material/GetList?token=${token}）
        this.fields = "FNumber,FName,F_101,FUnitID,FSalePrice,F_116,F_117";//需要查询出的字段
    }

    @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);//

        return result;
    }

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

        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);//

        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", "");//过滤条件
        }
        Data.put("OrderBy", "FNumber asc");//排序规则
        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;
    }

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

        try {//字段转换-变化soSsRequestVo的data参数格式 为CRM规定格式
            List dataList = new ArrayList<>();
            Map data = (Map) soSsRequestVo.getData();
            Object data1 = data.get("Data");
            List list = JSON.parseObject(data1.toString(), List.class, Feature.OrderedField);
            for (Object o : list) {
                Map listDateMap = JSON.parseObject(o.toString(), Map.class, Feature.OrderedField);
                Map masterField = new LinkedHashMap<>();
                Map masterFieldVal = new LinkedHashMap<>();
                masterFieldVal.put("productCode", listDateMap.get(FNumber));//产品编码
                masterFieldVal.put("productName", listDateMap.get(FName));//产品名称
                masterFieldVal.put("remarks", listDateMap.get(F_101));//备注
                masterFieldVal.put("company", listDateMap.get(FUnitID_FName));//单位
                masterFieldVal.put("standardPrice", listDateMap.get(FSalePrice));//标准价格
                masterFieldVal.put("classification", listDateMap.get(F_116_FNumber));//分类
                masterFieldVal.put("subspecies", listDateMap.get(F_117_FName));//子种类

                masterField.put("objAPIName", apiName);
                masterField.put("masterFieldVal", masterFieldVal);
                masterField.put("detailFieldVals",new HashMap<>());
                dataList.add(masterField);
            }
            map.put("totalNum", list.size());
            map.put("dataList", dataList);
            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 soSsRequestVo) {
        Map<Object, Object> map = new LinkedHashMap<>();
        Result result = new Result();

        try {//字段转换-变化soSsRequestVo的data参数格式 为CRM规定格式
            Map data = (Map) soSsRequestVo.getData();
            Object data1 = data.get("Data");
            List list = JSON.parseObject(data1.toString(), List.class, Feature.OrderedField);
//            map.put("objAPIName", apiName);
//            map.put("masterFieldVal", new HashMap<>());
//            map.put("detailFieldVals", new HashMap<>());
            for (Object o : list) {
                Map listDateMap = JSON.parseObject(o.toString(), Map.class, Feature.OrderedField);
                Map masterFieldVal = new LinkedHashMap<>();
                masterFieldVal.put("productCode", listDateMap.get(FNumber));//产品编码
                masterFieldVal.put("productName", listDateMap.get(FName));//产品名称
                masterFieldVal.put("remarks", listDateMap.get(F_101));//备注
                masterFieldVal.put("company", listDateMap.get(FUnitID_FName));//单位
                masterFieldVal.put("standardPrice", listDateMap.get(FSalePrice));//标准价格
                masterFieldVal.put("classification", listDateMap.get(F_116_FNumber));//分类
                masterFieldVal.put("subspecies", listDateMap.get(F_117_FName));//子种类
                map.put("objAPIName", apiName);
                map.put("masterFieldVal", masterFieldVal);
                map.put("detailFieldVals",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;
    }
}
