package com.yeejoin.amos.api.householdapi.Utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.api.householdapi.constant.GoodWeConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Component
public class GoodWeRequestUtil {
    private  final  String redisKey = "GOODWE_REQUEST_TOKEN";

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @return HashMap<String, Object>   发送请求前的准备 准备header信息
     * @deprecated 根据厂商编码获取厂商的hearer
     */
    public HashMap<String, String> getHeaderOfGoodWE() {
        HashMap<String,String> requestHeader = new HashMap<>();
        if(ObjectUtil.isNotEmpty(redisUtils.get(redisKey))){
            requestHeader.put("token",redisUtils.get(redisKey).toString());
            return requestHeader;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        String url = GoodWeConstant.baseurl+GoodWeConstant.tokenurl;
        Map<String,String> params = new HashMap<>();
        params.put("account",GoodWeConstant.account);
        params.put("pwd",GoodWeConstant.password);
        String requestParams = JSON.toJSONString(params);
        String respone = HttpUtil.createPost(url).headerMap(null, false).
                body(requestParams).execute().body();
        JSONObject jsonObject = JSON.parseObject(respone);
        if(jsonObject.getString("code").equals("0")){
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            String token = jsonObject1.getString("token");
            hashMap.put("token",token);
            redisUtils.set(redisKey,token,jsonObject1.getLong("expired")-10);
        }
        return hashMap;
    }

    /**
     * @param apiurl            请求url
     * @param requestMethod     请求方式
     * @param requestParmInfo   请求参数mapper
     * @param ResultResolveRule 请求的解析
     * @param tClass            需要转换成的bean
     * @param <T>               泛型数据
     * @return List<T> list<Result>
     * @desc 根据请求参数发送http请求并且对于返回的数据进行处理
     */
    public <T> List<T> getResPonse(String apiurl, String requestMethod, String requestParmInfo, String ResultResolveRule, Class<T> tClass) {
        String respone = "";
        String params = "";
        JSONArray jsonArray = null;
        List<T> result = new ArrayList<>();
        try {
            HashMap<String, String> headMap = getHeaderOfGoodWE();
            String url = GoodWeConstant.baseurl + apiurl;
            respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
            jsonArray = handlerResponseByResultResolverule(ResultResolveRule, respone);
            if (!ObjectUtils.isEmpty(jsonArray)) {
                result = JSONArray.parseArray(jsonArray.toJSONString(), tClass);
            }
        } catch (Exception exception) {
            return result;
        }
        return result;
    }

    /**
     * @param resultResovle 请求返回的解析规则 来源与数据库
     * @param response      请求返回的字符串
     * @return 解析后的数据
     * @desc 根据解析规则解析请求返回数据
     */
    public JSONArray handlerResponseByResultResolverule(String resultResovle, String response) {
        JSONObject jsonObject = JSONObject.parseObject(response);
        JSONArray jsonArray = new JSONArray();
        if (ObjectUtil.isNotEmpty(resultResovle)) {
            String[] rules = resultResovle.split(",");
            if (rules.length > 0) {
                for (int i = 0; i < rules.length; i++) {
                    try {
                        jsonObject = (JSONObject) jsonObject.get(rules[i]);
                        if (jsonObject == null) {
                            jsonArray = (JSONArray) jsonObject.get(rules[i]);
                        }
                    } catch (Exception exception) {
                        jsonArray = (JSONArray) jsonObject.get(rules[i]);
                    }
                }
            }
//            if (jsonArray.size() == 0) {
//                jsonArray.add(jsonObject);
//            }
        }
        return jsonArray;
    }

    public String sendRequest(String requestMethod, String url, String params, HashMap<String, String> headMap) {
        String respone = "";
        if (requestMethod.equals("POST")) {
            respone = HttpUtil.createPost(url).headerMap(headMap, false).
                    body(params).execute().body();
        }
        if (requestMethod.equals("GET")) {
            respone = HttpUtil.createGet(url).headerMap(headMap, true).
                    body(params).execute().body();
        }
        return respone;
    }


    /**
     * @param pageSizeResovle
     * @param response
     * @return
     * @desc 根据分页规则 获取分页数
     */
    public Integer getPagesize(String pageSizeResovle, String response) {
        Integer pageSize = 0;
        String[] rules = pageSizeResovle.split(",");
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (rules.length > 0) {
            for (int i = 0; i < rules.length - 1; i++) {
                jsonObject = (JSONObject) jsonObject.get(rules[i]);
            }
        }
        pageSize = (Integer) jsonObject.get(rules[rules.length - 1]);
        return pageSize;
    }
}
