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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.api.householdapi.constant.GoLangConstant;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.houseapi.HousepvapiRecords;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.houseapi.HYGFThirdStationLog;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.houseapi.HousepvapiRecordsMapper;
import com.yeejoin.amos.api.householdapi.face.service.IHYGFThirdStationLogService;
import com.yeejoin.amos.openapi.enums.PVProducerInfoEnum;
import fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Component
@Slf4j
public class GolangRequestUtil {

    @Autowired
    HousepvapiRecordsMapper housepvapiRecordsMapper;
    @Autowired
    IHYGFThirdStationLogService thirdStationLogService;
    /**
     * @return HashMap<String, Object>   发送请求前的准备 准备header信息
     * @deprecated 根据厂商编码获取厂商的hearer
     */
    public HashMap<String, Object> getHeaderOfGolang() {
        HashMap<String, Object> hashMap = new HashMap<>();
        HashMap<String, String> hashMaphead = new HashMap<>();
        String url = GoLangConstant.baseurl + GoLangConstant.tokenurl;
        hashMap.put("apiurl", GoLangConstant.baseurl);
        hashMaphead.put("Content-type", "application/json;charset=UTF-8");
        hashMaphead.put("Authorization", "API " + GoLangConstant.prodcerappid);
        hashMaphead.put("Content-MD5", null);
        hashMaphead.put("Date", GoLangHeaderUtils.getGMTTime());
        hashMap.put("header", hashMaphead);
        hashMap.put("appsecret", GoLangConstant.prodcerappsecret);
        return hashMap;
    }


    /**
     * 这个方法是为了查出全部的数据
     * @param apiurl            请求url
     * @param requestMethod     请求方式
     * @param requestInfo       请求信息
     * @param ResultResolveRule 请求的解析
     * @param tClass            需要转换成的bean
     * @param <T>               泛型数据
     * @return List<T> list<Result>
     * @desc 根据请求参数发送http请求并且对于返回的数据进行处理
     */
    public <T> List<T> getResPonseList(String apiurl, String requestMethod, HashMap<String, Object> requestInfo, String ResultResolveRule, Class<T> tClass) {
        String respone = "";
        String params = "";
        JSONArray jsonArray = null;
        List<T> result = new ArrayList<>();
        Integer pageNo = 1;
        String url ="";
        HashMap<String, String> headMap = new HashMap<>();
        String requestParmInfo ="";
        try {
            do {
                requestInfo.put("pageNo", pageNo);
                requestParmInfo = JSON.toJSONString(requestInfo);
                HashMap<String, Object> producerInfo = getHeaderOfGolang();
                String baseurl = (String) producerInfo.get("apiurl");
                headMap= (HashMap<String, String>) producerInfo.get("header");
                String orginalAuthorization = headMap.get("Authorization") + ":";
                url = baseurl + apiurl;
                String appsecret = (String) producerInfo.get("appsecret");
                JLYHeaderMapHandler(params, headMap, orginalAuthorization, appsecret, apiurl);
                respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
                jsonArray = handlerResponseByResultResolverule(ResultResolveRule, respone);
                if (!ObjectUtils.isEmpty(jsonArray)) {
                    result.addAll(JSONArray.parseArray(jsonArray.toJSONString(), tClass));
                }
                //存储日志
                HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
                hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.JLY.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);
                JSONObject data = responeJSON.getJSONObject("data");
                Integer responePages = 0;
                if (data.containsKey("pages")){
                    responePages = data.getInteger("pages");
                } else {
                    JSONObject page = data.getJSONObject("page");
                    responePages = page.getInteger("pages");
                }
                if (responePages <= pageNo){
                    break;
                } else {
                    pageNo++;
                }
            }while (true);
        } catch (Exception exception) {
            log.error(exception.getMessage(),exception);
            //存储日志
            HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
            hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.JLY.getCode());
            hygfThirdStationLog.setReqMethod(requestMethod);
            hygfThirdStationLog.setReqHeaders(headMap.toString());
            hygfThirdStationLog.setReqPath(url);
            hygfThirdStationLog.setReqBody(requestParmInfo);
            hygfThirdStationLog.setResBody(respone);
            thirdStationLogService.saveLog(hygfThirdStationLog);
            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 = "";
        String params = "";
        JSONArray jsonArray = null;
        List<T> result = new ArrayList<>();
        String url ="";
        HashMap<String, String> headMap = new HashMap<>();
        try {
            HashMap<String, Object> producerInfo = getHeaderOfGolang();
            String baseurl = (String) producerInfo.get("apiurl");
            headMap = (HashMap<String, String>) producerInfo.get("header");
            String orginalAuthorization = headMap.get("Authorization") + ":";
            url = baseurl + apiurl;
            String appsecret = (String) producerInfo.get("appsecret");
            JLYHeaderMapHandler(params, headMap, orginalAuthorization, appsecret, apiurl);
            respone = sendRequest(requestMethod, url, requestParmInfo, headMap);
            jsonArray = handlerResponseByResultResolverule(ResultResolveRule, respone);
            if (!ObjectUtils.isEmpty(jsonArray)) {
                result = JSONArray.parseArray(jsonArray.toJSONString(), tClass);
            }
            //存储日志
            HYGFThirdStationLog hygfThirdStationLog = new HYGFThirdStationLog();
            hygfThirdStationLog.setThirdCode(PVProducerInfoEnum.JLY.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.JLY.getCode());
            hygfThirdStationLog.setReqMethod(requestMethod);
            hygfThirdStationLog.setReqHeaders(headMap.toString());
            hygfThirdStationLog.setReqPath(url);
            hygfThirdStationLog.setReqBody(requestParmInfo);
            hygfThirdStationLog.setResBody(respone);
            thirdStationLogService.saveLog(hygfThirdStationLog);
            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) {
        HousepvapiRecords housepvapiRecords = new HousepvapiRecords();
        housepvapiRecords.setRecDate(new Date());
        housepvapiRecords.setRequestUrl(url);
        housepvapiRecords.setRequestMothed(requestMethod);
        housepvapiRecords.setRequestHeaders(JSONObject.toJSONString(headMap));
        housepvapiRecords.setRequestParams(params);
        housepvapiRecords.setThridCode(PVProducerInfoEnum.JLY.getCode());
        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();
        }
        housepvapiRecords.setResponse(respone);
       // housepvapiRecordsMapper.insert(housepvapiRecords);
        //log.info("锦浪云数据请求详情："+JSONObject.toJSONString(housepvapiRecords));
        return respone;
    }

    /***
     *
     * @param params 参数字符窜
     * @param headMap header头
     * @param orginalAuthorization 原始的orginalAuthorization
     * @param appsecret  appsecret
     * @desc 锦浪云请求参数及head头处理
     */
    public void JLYHeaderMapHandler(String params, HashMap<String, String> headMap, String orginalAuthorization, String appsecret, String apiurl) {
        String contentMD5 = GoLangHeaderUtils.getDigest(params);
        headMap.put("Date", GoLangHeaderUtils.getGMTTime());
        String param = "POST" + "\n" + contentMD5 + "\n" + "application/json" + "\n" + headMap.get("Date") + "\n" + apiurl;
        String sign = "";
        try {
            sign = GoLangHeaderUtils.HmacSHA1Encrypt(param, appsecret);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        headMap.put("Content-MD5", contentMD5);
        headMap.put("Authorization", orginalAuthorization + sign);
    }

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

    public Long convertDate(Long input){
        Long result = 0L;
        Date date = DateUtil.date(input);
        result = DateUtil.parse( DateUtil.format(date, DatePattern.NORM_DATETIME_PATTERN)).getTime();
        return result;
    }

    public String getInverterState(String currentState,Long updateTime){
      String state = "在线";
      if(Integer.valueOf(currentState)>1004){
        state = "报警";
      }
      if((System.currentTimeMillis()-updateTime)>1800000 ){
          state="离线";
      }
      return state;
    }
}
