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.SoFarConstant;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.houseapi.HYGFThirdStationLog;
import com.yeejoin.amos.api.householdapi.face.service.IHYGFThirdStationLogService;
import com.yeejoin.amos.openapi.enums.PVProducerInfoEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component

public class SofarRequestUtil {

    private  final  String redisKey = "SOFAR_REQUEST_TOKEN";



    public static final HashMap<String, String> intoNetWorkStatus = new HashMap<String, String>() {
        {
            put("DISTRIBUTED_FULLY", "分布式全额上网");
            put("EXCESS", "分布式自发自用余电上网");
            put("OFF_GRID", "离网");
            put("BATTERY_BACKUP", "储能系统");
            put("GROUND_FULLY", "地面全额上网");
        }
    };

    public static final HashMap<String, String> alarmLevel = new HashMap<String, String>() {
        {
            put("2", "故障");
            put("1", "警告");
            put("0", "提示");

        }
    };













    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    IHYGFThirdStationLogService thirdStationLogService;

    /**
     * @return HashMap<String, Object>   发送请求前的准备 准备header信息
     * @deprecated 根据厂商编码获取厂商的hearer
     */
    public HashMap<String, String> getHeaderOfSofar() {
        HashMap<String,String> requestHeader = new HashMap<>();
        if(ObjectUtil.isNotEmpty(redisUtils.get(redisKey))){
            requestHeader.put("authorization",redisUtils.get(redisKey).toString());
            return requestHeader;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("accountName", SoFarConstant.account);
        map.put("appId",SoFarConstant.appId);
        map.put("appSecret", SoFarConstant.appSecret);
        map.put("corporationId", SoFarConstant.corporationId);
        map.put("accountType", 2);
        String body = JSON.toJSONString(map);
        String url = SoFarConstant.baseurl+SoFarConstant.tokenurl;
        String response = HttpUtil.createPost(url).body(body).execute().body();
        JSONObject jsonObject = JSON.parseObject(response);
        if(jsonObject.getString("msg").equals("success")){
            String token = jsonObject.getString("data");
            requestHeader.put("authorization",token);
            redisUtils.set(redisKey,token,5183900);
        }

        return requestHeader;
    }
    /**
     * @param apiurl            请求url
     * @param requestMethod     请求方式
     * @param requestInfo   请求参数mapper
     * @param ResultResolveRule 请求的解析
     * @param tClass            需要转换成的bean
     * @param <T>               泛型数据
     * @return List<T> list<Result>
     * @desc 根据请求参数发送http请求并且对于返回的数据进行处理
     */
    public <T> List<T> getResPonseList(String apiurl, String requestMethod, Map<String, Object> requestInfo, String ResultResolveRule, Class<T> tClass) {
        String respone = "";
        List<T> result = new ArrayList<>();
        Integer pageNo = 1;
        try {
            do {
                requestInfo.put("page", pageNo);
                String requestParmInfo = JSON.toJSONString(requestInfo);
                HashMap<String, String> headMap = getHeaderOfSofar();
                String url = SoFarConstant.baseurl + apiurl;
                respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
                //token如果失效重新获取{"code": 500,"msg": "Login status has expired","success": false}
                if(JSONObject.parseObject(respone).getInteger("code") == 500){
                    redisUtils.del(redisKey);
                    respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
                }
                JSONObject jsonObject = JSONObject.parseObject(respone);
                if(jsonObject!=null&&jsonObject.get(ResultResolveRule)!=null){
                    result.addAll(JSONArray.parseArray(fastjson.JSON.toJSONString(jsonObject.get(ResultResolveRule)), tClass));

                }
                //存储日志
                HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
                hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.SH.getCode());
                hygfThirdStationLog.setReqMethod(requestMethod);
                hygfThirdStationLog.setReqHeaders(headMap.toString());
                hygfThirdStationLog.setReqPath(url);
                hygfThirdStationLog.setReqBody(requestParmInfo);
                hygfThirdStationLog.setResBody(respone);
                thirdStationLogService.saveLog(hygfThirdStationLog);
                //处理其他页数的数据
                JSONObject responeJSON = JSONObject.parseObject(respone);
                Integer total = responeJSON.getInteger("total");
                Integer pageSize= requestInfo.get("size")==null || (Integer)requestInfo.get("size")==0? 1:(Integer)requestInfo.get("size");
                Integer responePages=(total/pageSize)+1;
                if (responePages <= pageNo){
                    break;
                } else {
                    pageNo++;
                }
            } while (true);
        } catch (Exception exception) {
            exception.printStackTrace();
            return result;
        }
        return result;
    }

    /**
     * @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 = "";
        List<T> result = new ArrayList<>();
        String url ="";
        HashMap<String, String> headMap = new HashMap<>();
        try {
             headMap = getHeaderOfSofar();
             url = SoFarConstant.baseurl + apiurl;
            respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
            JSONObject jsonObject = JSONObject.parseObject(respone);
            if(jsonObject!=null&&jsonObject.get(ResultResolveRule)!=null){
                result = JSONArray.parseArray(fastjson.JSON.toJSONString(jsonObject.get(ResultResolveRule)), tClass);

            }
            //存储日志
            HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
            hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.SH.getCode());
            hygfThirdStationLog.setReqMethod(requestMethod);
            hygfThirdStationLog.setReqHeaders(headMap.toString());
            hygfThirdStationLog.setReqPath(url);
            hygfThirdStationLog.setReqBody(requestParmInfo);
            hygfThirdStationLog.setResBody(respone);
            thirdStationLogService.saveLog(hygfThirdStationLog);
        } catch (Exception exception) {
            exception.printStackTrace();
            //存储日志
            HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
            hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.SH.getCode());
            hygfThirdStationLog.setReqMethod(requestMethod);
            hygfThirdStationLog.setReqHeaders(headMap.toString());
            hygfThirdStationLog.setReqPath(url);
            hygfThirdStationLog.setReqBody(requestParmInfo);
            hygfThirdStationLog.setResBody(respone);
            thirdStationLogService.saveLog(hygfThirdStationLog);
            return result;
        }
        return result;
    }


    public JSONObject getResPonseobj(String apiurl, String requestMethod, String requestParmInfo, String ResultResolveRule) {
        String respone = "";
        JSONObject jsonObject = null;
        String url ="";
        HashMap<String, String> headMap = new HashMap<>();
        try {
            headMap = getHeaderOfSofar();
            url = SoFarConstant.baseurl + apiurl;
            respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
            if(respone!=null&&JSONObject.parseObject(respone).get(ResultResolveRule)!=null&&ResultResolveRule!=null){
                jsonObject = JSONObject.parseObject(JSONObject.parseObject(respone).get(ResultResolveRule).toString());
            }else{
                 jsonObject = JSONObject.parseObject(respone);
            }
            //存储日志
            HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
            hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.SH.getCode());
            hygfThirdStationLog.setReqMethod(requestMethod);
            hygfThirdStationLog.setReqHeaders(headMap.toString());
            hygfThirdStationLog.setReqPath(url);
            hygfThirdStationLog.setReqBody(requestParmInfo);
            hygfThirdStationLog.setResBody(respone);
            thirdStationLogService.saveLog(hygfThirdStationLog);
        } catch (Exception exception) {
            //存储日志
            HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
            hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.SH.getCode());
            hygfThirdStationLog.setReqMethod(requestMethod);
            hygfThirdStationLog.setReqHeaders(headMap.toString());
            hygfThirdStationLog.setReqPath(url);
            hygfThirdStationLog.setReqBody(requestParmInfo);
            hygfThirdStationLog.setResBody(respone);
            thirdStationLogService.saveLog(hygfThirdStationLog);
            exception.printStackTrace();
        }
        return jsonObject;
    }


    /**
     * @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;
    }
}
