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

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.yeejoin.amos.api.householdapi.face.dto.SunlightDto;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.Sunlight;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.houseapi.HousepvapiRecordsMapper;
import fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.naming.Name;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author阳光电站采集
 * @createDate: 2024/2/29
 */
@Component
@Slf4j
public class SunlightUtil {

    public static  String dfurl="https://gateway.isolarcloud.com";
    public static  String appkey="D9A9B8A58FD193EEEFEE0C6BD4664626";
    public static  String access_key="vz47buat1ibrkf66jfiksmvm7att6sk4";
    public static  String  name="jxiop_jdxny";
    public static  String  pasword="tA9WAgmG4z:48gp";


    //场站接口
    public static  String getPowerStationList= "/openapi/getPowerStationList";
    //电站详情
    public static  String getPowerStationDetail="/openapi/getPowerStationDetail";

    //电站设备
    public static  String getDeviceList="/openapi/getDeviceList";

    //月，年
    public static  String getDevicePointsDayMonthYearDataList="/openapi/getDevicePointsDayMonthYearDataList";

   //逆变器参数
    public static  String getPVInverterRealTimeData="/openapi/getPVInverterRealTimeData";
    //告警


    public static  String getFaultAlarmInfo= "/openapi/getFaultAlarmInfo";


    public static final HashMap<String, String> intoNetWorkStatus = new HashMap<String, String>() {
        {
            put("1", "全额上网");
            put("2", ":自发自用，余电上网");
            put("3", "自发自用，无馈网");
            put("4", "离网");
        }
    };

//    public static final HashMap<String, Double> co = new HashMap<String, Double>() {
//        {
//            put("克",0.001 );
//            put("千克", );
//            put("吨", );
//            put("千吨", );
//        }
//    };
    public static final HashMap<String, Double> zj = new HashMap<String, Double>() {
        {
            put("Wp", 0.001);
            put("kWp", 1.0);
            put("MWp",1000.0 );
            put("GWp", 1000000.0);
        }
    };
    public static final HashMap<String, Double> fd = new HashMap<String, Double>() {
        {
            put("度", 1.0);
            put("千度", 1000.0);
            put("万度", 10000.0);
            put("亿度", 100000000.0);
        }
    };
    public static final HashMap<String, Double> sy = new HashMap<String, Double>() {
        {
            put("元", 1.0);
            put("万元", 10000.0);
            put("亿元", 100000000.0);
        }
    };

    public static final HashMap<String, Double> GL = new HashMap<String, Double>() {
        {
            put("W", 0.001);
            put("kW", 1.0);
            put("MW", 1000.0);
            put("GW", 1000000.0);
        }
    };


    public static final HashMap<String, String> zt= new HashMap<String, String>() {
        {
            put("1", "在线");
            put("0", "离线");
        }
    };
    
    public static final HashMap<String, String> gzzt= new HashMap<String, String>() {
        {
            put("1", "故障");
            put("2", "报警");
            put("4", "正常" );
        }
    };


    public static final HashMap<String, String> alarmLevel = new HashMap<String, String>() {
        {
            put("1", "重要");
            put("2", "次要");
            put("3", "一般");
            put("3", "轻微");
        }
    };

    public static final HashMap<String, String> alarmstatus = new HashMap<String, String>() {
        {
            put("1", "未确认");
            put("2", "待处理");
            put("3", "处理中");
            put("4", "已解决");
            put("5", "已关闭");
        }
    };


    private static final String redisKey = "YG-TOKEN";


    @Autowired
    RedisUtils redisUtils;

    /*
    *
    * 登录获取token
    * */
    public   String getSunlightToken(){
        String token=null;
        try {
            Object o = redisUtils.get(redisKey);
            if(o != null) {
                return o.toString();
            }


            //请求头
            HttpRequest request = HttpUtil.createPost(dfurl+"/openapi/login");
            request.header("Content-Type", "application/json;charset=UTF-8");
            request.header("sys_code", "901");
            request.header("x-access-key", access_key);
            //请求body
            Map<String, String> param = new HashMap();
            param.put("appkey", appkey);
            param.put("user_account", name);
            param.put("user_password", pasword);
            Gson gson = new Gson();
            String body = gson.toJson(param);
            request.body(body);
            HttpResponse execute = request.execute();
            if (!execute.isOk()) {
                log.error("请求token失败,body={},execute={}", execute.body(), execute);
                throw new RuntimeException(execute.body());
            }
            String res = UnicodeUtil.toString(execute.body());
            JSONObject jsonObject = JSONUtil.parseObj(res, true);

            if (!jsonObject.get("result_msg").toString().equals("success")){
                log.error("请求失败,code={},result={}", jsonObject.get("result_msg"), jsonObject);

                throw new RuntimeException("请求失败！");
            }
            JSONObject resultData = JSONUtil.parseObj(jsonObject.get("result_data"), true);
            if (!resultData.get("login_state").toString().equals("1")) {
                log.error("获取token失败,code={},msg={},result={}", resultData.get("login_state"), resultData.get("msg"), resultData);
                throw new RuntimeException("获取token失败,code=" +  resultData.get("login_state") + ",msg=" + resultData.get("msg"));
            }
            redisUtils.set(redisKey,resultData.get("token").toString(),14400 );
            return resultData.get("token").toString();
        } catch (Exception e) {
            log.error("requestToken失败,msg={}", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取全部的数据
     * @param url
     * @param bodyparam
     * @return
     */
    public JSONObject getDataList(String url, Map<String, Object> bodyparam){
        JSONObject resultData = new JSONObject();
        JSONArray pageList = new JSONArray();
        Integer pageNo = 1;
        try {
            do {
                bodyparam.put("curPage", pageNo);
                //请求头
                HttpRequest request = HttpUtil.createPost(dfurl+url);
                request.header("Content-Type", "application/json;charset=UTF-8");
                request.header("sys_code", "901");
                request.header("x-access-key", access_key);
                //请求body
                bodyparam.put("appkey", appkey);
                bodyparam.put("token", this.getSunlightToken());

                Gson gson = new Gson();
                String body = gson.toJson(bodyparam);
                request.body(body);
                HttpResponse execute = request.execute();
                if (!execute.isOk()) {
                    throw new RuntimeException(execute.body());
                }
                String res = UnicodeUtil.toString(execute.body());

                JSONObject jsonObject = JSONUtil.parseObj(res, true);
                resultData = JSONUtil.parseObj(jsonObject.get("result_data"), true);
                if(resultData!=null && resultData.get("pageList")!=null){
                    pageList.addAll(JSONArray.parseArray(JSON.toJSONString(resultData.get("pageList"))));
                    resultData.putOpt("pageList",pageList);
                }
                //处理其他页数的数据
                Integer rowCount = resultData.getInt("rowCount");
                Integer pageSize= bodyparam.get("size")==null || (Integer)bodyparam.get("size")==0? 1:(Integer)bodyparam.get("size");
                Integer responePages=(rowCount/pageSize)+1;
                if (responePages == pageNo){
                    break;
                } else {
                    pageNo++;
                }
            } while (true);
        } catch (Exception e) {
            log.error("失败,msg["+e.getMessage()+"]", e);
            return resultData;
        }
        return resultData;

    }


    //获取接口数据

    public    JSONObject getdata(String url,Map<String, Object> bodyparam ){
        String data=null;

        try {
            //请求头
            HttpRequest request = HttpUtil.createPost(dfurl+url);
            request.header("Content-Type", "application/json;charset=UTF-8");
            request.header("sys_code", "901");
            request.header("x-access-key", access_key);
            //请求body
            bodyparam.put("appkey", appkey);
            bodyparam.put("token", this.getSunlightToken());

            Gson gson = new Gson();
            String body = gson.toJson(bodyparam);
            request.body(body);
            HttpResponse execute = request.execute();
            if (!execute.isOk()) {
                throw new RuntimeException(execute.body());
            }
            String res = UnicodeUtil.toString(execute.body());

            JSONObject jsonObject = JSONUtil.parseObj(res, true);
            JSONObject resultData = JSONUtil.parseObj(jsonObject.get("result_data"), true);


            return resultData;
        } catch (Exception e) {
            log.error("失败,msg["+e.getMessage()+"]", e);
            return new JSONObject();
        }


    }

}
