package org.dromara.daping.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.daping.domain.GinlongApiEntity;
import org.dromara.daping.domain.bo.GinlongBo;
import org.dromara.daping.service.IGinlongApiService;
import org.dromara.daping.utils.GinlongApiClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RequiredArgsConstructor
@Service
public class GinlongApiServiceImpl implements IGinlongApiService {

    @Autowired
    private GinlongApiClient apiClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public GinlongApiEntity getGinlongApiEntity(){


        GinlongApiEntity apiEntity = new GinlongApiEntity();
        apiEntity.setUrl("https://api.ginlong.com:13333");
        apiEntity.setKey("1300386381676987116");
        apiEntity.setSecret("511045d99416484cb93acc2f16a5c149");

        return apiEntity;
    }


    @Override
    public String test() {
//        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GinlongApiTest.class);

        // 验证GinlongApiEntity是否正确加载
        GinlongApiEntity apiEntity = new GinlongApiEntity();
//        GinlongApiEntity apiEntity = context.getBean(GinlongApiEntity.class);
//        System.out.println("加载的配置信息："+apiEntity.toString());
//        System.out.println("url: " + apiEntity.getUrl());
//        System.out.println("key: " + apiEntity.getKey());
//        System.out.println("secret: " + apiEntity.getSecret());  // 重点检查是否为null

//        apiEntity.setUrl("https://api.ginlong.com:13333");
//        apiEntity.setKey("1300386381676987116");
//        apiEntity.setSecret("511045d99416484cb93acc2f16a5c149");

        if (apiEntity.getSecret() == null) {
            System.err.println("错误：secret未加载，请检查配置文件！");
//            context.close();
            return "";
        }

        // 调用API（原有逻辑）
//        GinlongApiClient apiClient = context.getBean(GinlongApiClient.class);
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNo", 1);
            params.put("pageSize", 100);
            params.put("nmiCode",null);
            params.put("idList",new ArrayList<>());
            String s = apiClient.callApi("/v1/api/userStationList", params,apiEntity);
            System.out.println("!!!!     " +s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            context.close();
        }
        return "";
    }

    /**
     * 获取账号下电站列表
     * @param apiEntity
     * @return
     */
    public String userStationList(GinlongApiEntity apiEntity){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNo", 1);
            params.put("pageSize", 100);
            params.put("nmiCode",null);
            params.put("idList",new ArrayList<>());
            return apiClient.callApi("/v1/api/userStationList", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取多个电站详情
     */
    public String stationDetailList(GinlongApiEntity apiEntity, List<Long> idList){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNo", 1);
            params.put("pageSize", 100);
            params.put("idList",idList);
            return apiClient.callApi("/v1/api/stationDetailList", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取所有逆变器详情
     */
    public String inverterList(GinlongApiEntity apiEntity){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNo", 1);
            params.put("pageSize", 100);
            return apiClient.callApi("/v1/api/inverterList", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取账号下设备报警列表
     */
    public String alarmList(GinlongApiEntity apiEntity){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("pageNo", 1);
            params.put("pageSize", 100);
            return apiClient.callApi("/v1/api/alarmList", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取单台逆变器某月的日数据
     */
    public String inverterMonth(GinlongApiEntity apiEntity, Long id, String date){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("money", "元");
            params.put("month", date);

            return apiClient.callApi("/v1/api/inverterMonth", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
    /**
     * 获取单台逆变器某年的月数据
     */
    public String inverterYear(GinlongApiEntity apiEntity, Long id, String date){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("money", "元");
            params.put("year", date);

            return apiClient.callApi("/v1/api/inverterYear", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取单台逆变器某日的实时数据
     */
    public String inverterDay(GinlongApiEntity apiEntity, Long id, String date){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("money", "元");
            params.put("time", date);
            params.put("timeZone", 8);

            return apiClient.callApi("/v1/api/inverterDay", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取单个电站某日的实时数据
     */
    public String stationDay(GinlongApiEntity apiEntity, Long id, String date){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("money", "CNY");
            params.put("time", date);
            return apiClient.callApi("/v1/api/stationDay", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取单个电站某月的日数据
     */
    public String stationMonth(GinlongApiEntity apiEntity, Long id, String date){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("money", "CNY");
            params.put("month", date);
            return apiClient.callApi("/v1/api/stationMonth", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
    /**
     * 获取单个电站某年的月数据
     */
    public String stationYear(GinlongApiEntity apiEntity, Long id, String date){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("money", "CNY");
            params.put("year", date);
            return apiClient.callApi("/v1/api/stationYear", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }


//    /**
//     * 获取多个电站某日的实时数据
//     */
//    public String stationDayEnergyList(GinlongApiEntity apiEntity, List<Long> idList, String date){
//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("idList", idList);
//            params.put("time", date);
//            return apiClient.callApi("/v1/api/stationDayEnergyList", params,apiEntity);
//        } catch (Exception e) {
//            throw new ServiceException(e.getMessage());
//        }
//    }
//    /**
//     * 获取多个电站的月数据
//     */
//    public String stationMonthEnergyList(GinlongApiEntity apiEntity, List<Long> idList, String date){
//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("idList", idList);
//            params.put("time", date);
//            return apiClient.callApi("/v1/api/stationMonthEnergyList", params,apiEntity);
//        } catch (Exception e) {
//            throw new ServiceException(e.getMessage());
//        }
//    }
//    /**
//     * 获取多个电站的年数据
//     */
//    public String stationYearEnergyList(GinlongApiEntity apiEntity, List<Long> idList, String date){
//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("idList", idList);
//            params.put("time", date);
//            return apiClient.callApi("/v1/api/stationYearEnergyList", params,apiEntity);
//        } catch (Exception e) {
//            throw new ServiceException(e.getMessage());
//        }
//    }





    /**
     * 获取单个电站详情
     */
    public String stationDetail(GinlongApiEntity apiEntity, Long id){
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            return apiClient.callApi("/v1/api/stationDetail", params,apiEntity);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }


    /**
     * 获取电站总览数据信息
     * @return
     */
    @Override
    public HashMap<String, Object> getPowerStationOverview() {

        HashMap<String, Object> map = new HashMap<>();
        GinlongApiEntity apiEntity = getGinlongApiEntity();

        double dayEnergy = 0.0; //今日总发电量

        List<Long> idList = new ArrayList<>();
        //使用获取账号下电站列表接口获取数据
        String s = userStationList(apiEntity);
        String s2 = inverterList(apiEntity);
        getInverterList(s2, map);
        getUserStationList(s, idList, map);

        //使用获取多个电站详情接口获取数据
        String s1 = stationDetailList(apiEntity, idList);
//        System.out.println(s1);
        getStationDetailList(s1, dayEnergy, map);


        System.out.println(map);


        return map;
    }

    private void getInverterList(String s2, HashMap<String, Object> map) {
        JSONObject jsonObject = JSONUtil.parseObj(s2);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject inverterStatusVo = data.getJSONObject("inverterStatusVo");
//        Object obj = RedisUtils.getCacheObject("health");
//        RedisUtils.getCacheObject()
//        String username = redisTemplate.get("username");
//        Double healthOld = redisTemplate.opsForValue().get("health");
        String healthOld = stringRedisTemplate.opsForValue().get("health");
        map.put("healthOld", healthOld != null ? Double.parseDouble(healthOld) : 0.0);
//        if (obj != null) {
//            double healthOld = Double.parseDouble(String.valueOf(obj));
//            // 使用 value
//            map.put("healthOld",healthOld );
//        }else {
//            map.put("healthOld",0.0 );
//
//        }
        if (inverterStatusVo.getInt("all") >0){
            double health = (double) (inverterStatusVo.getInt("all") - inverterStatusVo.getInt("fault")) /inverterStatusVo.getInt("all") * 100;//健康度
            map.put("health", health);//健康度
        }else {
            map.put("health", 0);//健康度
        }
    }
    private static void getInverterList1(String s2) {
        JSONObject jsonObject = JSONUtil.parseObj(s2);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject inverterStatusVo = data.getJSONObject("inverterStatusVo");
        if (inverterStatusVo.getInt("all") >0){
            double health = (double) (inverterStatusVo.getInt("all") - inverterStatusVo.getInt("fault")) /inverterStatusVo.getInt("all") * 100;//健康度
            RedisUtils.setCacheObject("health",health);
        }else {
            RedisUtils.setCacheObject("health",0);
        }
        RedisUtils.expire("health",86400);
    }

    /**
     * 获取逆电器数据
     * @param bo
     * @return
     */
    @Override
    public HashMap<String, Object> getInverterListOverview(GinlongBo bo) {
        HashMap<String, Object> map = new HashMap<>();
        GinlongApiEntity apiEntity = getGinlongApiEntity();
        String s = inverterList(apiEntity);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject inverterStatusVo = data.getJSONObject("inverterStatusVo");
        map.put("all",inverterStatusVo.getInt("all"));//全部
        map.put("normal",inverterStatusVo.getInt("normal"));//正常
        map.put("offline",inverterStatusVo.getInt("offline"));//离线
        map.put("fault",inverterStatusVo.getInt("fault"));//异常
        JSONObject page = data.getJSONObject("page");
        JSONArray records = page.getJSONArray("records");
        List<Long> ids = new ArrayList<>();
        if (!records.isEmpty()) {
            for (Object record : records) {
                JSONObject object = JSONUtil.parseObj(record);
                ids.add(object.getLong("id"));
            }
        }


        List<HashMap<String, Object>> hashMaps = new ArrayList<>();
        switch (bo.getType()) {
            case 1:
                String s1 = inverterDay(apiEntity, ids.getFirst(), bo.getDate());
                JSONObject jsonObject1 = JSONUtil.parseObj(s1);
                JSONArray data1 = jsonObject1.getJSONArray("data");
                int a = 0;
                for (int i = 0; i < 12; i++) {
                    double count = 0.0;
                    HashMap<String, Object> map1 = new HashMap<>();
                    String time = i*2+2<10?"0"+i*2+2:(i*2+2)+"";
                    map1.put("time", i*2<10?"0"+i*2+":00":i*2+":00");
                    if (data1 != null && !data1.isEmpty()){
                        for (int x = a; x < data1.size(); x++) {
                            Object obj = data1.get(x); // 通过索引获取元素
                            JSONObject object = JSONUtil.parseObj(obj);
                            if (object.getStr("time").substring(0, 2).compareTo(time) >0){
                                break;
                            }
                            count += object.getDouble("pac");
                            a++;
                        }
                        map1.put("content", count);
                        hashMaps.add(map1);
                        continue;
                    }else {
                        map1.put("content", 0);
                    }
                    hashMaps.add(map1);
                }
                System.out.println(hashMaps);
                break;
            case 2:
                String s2 = inverterMonth(apiEntity, ids.getFirst(), bo.getDate());
                JSONObject jsonObject2 = JSONUtil.parseObj(s2);
                JSONArray data2 = jsonObject2.getJSONArray("data");
                if (data2 != null && !data2.isEmpty()){
                    for (Object obj : data2) {
                        HashMap<String, Object> map2 = new HashMap<>();
                        JSONObject object = JSONUtil.parseObj(obj);
                        map2.put("time", object.getStr("dateStr"));
                        map2.put("content", object.get("energy"));
                        hashMaps.add(map2);
                    }
                }else {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
                    YearMonth yearMonth = YearMonth.parse(bo.getDate(), formatter);

                    int year = yearMonth.getYear();  // 2025
                    int monthValue = yearMonth.getMonthValue();
                    int day = LocalDate.of(year, monthValue, 1).lengthOfMonth();
                    String month = monthValue<10?"0"+monthValue:monthValue+"";
                    for (int i = 1; i <= day; i++){
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("time", i<10?month+"-0"+i:month+"-"+i);
                        map1.put("content", 0);
                        hashMaps.add(map1);
                    }
                }
                break;
            case 3:
                String s3 = inverterYear(apiEntity, ids.getFirst(), bo.getDate());
                JSONObject jsonObject3 = JSONUtil.parseObj(s3);
                JSONArray data3 = jsonObject3.getJSONArray("data");
                System.out.println(data3);
                if (data3 != null && !data3.isEmpty()) {
                    for (Object obj : data3) {
                        HashMap<String, Object> map3 = new HashMap<>();
                        JSONObject object = JSONUtil.parseObj(obj);
                        map3.put("time", object.getStr("dateStr"));
                        map3.put("content", object.get("energy"));
                        hashMaps.add(map3);
                    }
                }else {
                    for (int i = 1; i <= 12; i++){
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("time", i<10?bo.getDate()+"-0"+i:bo.getDate()+"-"+i);
                        map1.put("content", 0);
                        hashMaps.add(map1);
                    }
                }
                break;
            default:
                break;
        }
        map.put("data",hashMaps);
        System.out.println(map);
        return map;
    }

    /**
     * 能源收益分析
     * @param bo
     * @return
     */
    @Override
    public HashMap<String, Object> getStationMonthOverview(GinlongBo bo) {
        HashMap<String, Object> map = new HashMap<>();
        GinlongApiEntity apiEntity = getGinlongApiEntity();
        List<Long> idList = new ArrayList<>();
        //使用获取账号下电站列表接口获取数据
        String s = userStationList(apiEntity);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject page = data.getJSONObject("page");
        JSONArray records = page.getJSONArray("records");
        if (!records.isEmpty()){
            for (Object record : records) {
                JSONObject object = JSONUtil.parseObj(record);
                idList.add(object.getLong("id"));
            }
        }
        List<HashMap<String, Object>> hashMaps = new ArrayList<>();
        switch (bo.getType()){
            case 1:
//                String s1 = stationDay(apiEntity, idList.getFirst(), bo.getDate());
//                System.out.println(s1);
//                JSONObject jsonObject1 = JSONUtil.parseObj(s1);
//                JSONArray data1 = jsonObject1.getJSONArray("data");
//                int a = 0;
//                for (int i = 0; i < 12; i++) {
//                    double count = 0.0;
//                    HashMap<String, Object> map1 = new HashMap<>();
//                    String time = i * 2 + 2 < 10 ? "0" + i * 2 + 2 : (i * 2 + 2) + "";
//                    map1.put("time", i * 2 < 10 ? "0" + i * 2 + ":00" : i * 2 + ":00");
//                    if (data1 != null && !data1.isEmpty()) {
//                        for (int x = a; x < data1.size(); x++) {
//                            Object obj = data1.get(x); // 通过索引获取元素
//                            JSONObject object = JSONUtil.parseObj(obj);
//                            if (object.getStr("timeStr").substring(0, 2).compareTo(time) > 0) {
//                                break;
//                            }
//                            count += object.getDouble("power");
//                            a++;
//                        }
//                        map1.put("content", count);
//
//                        hashMaps.add(map1);
//                        continue;
//                    } else {
//                        map1.put("content", 0);
//                    }
//                    hashMaps.add(map1);
//                }
//                int y = 0;
//                for (Long id : idList) {
//                    String s1 = stationDay(apiEntity, id, bo.getDate());
//                    System.out.println(s1);
//                    JSONObject jsonObject1 = JSONUtil.parseObj(s1);
//                    JSONArray data1 = jsonObject1.getJSONArray("data");
//                    int a = 0;
//                    for (int i = 0; i < 12; i++) {
//                        double count = 0.0;
//                        HashMap<String, Object> map1 = new HashMap<>();
//                        String time = i*2+2<10?"0"+i*2+2:(i*2+2)+"";
//                        if (y == 0){
//                            map1.put("time", i*2<10?"0"+i*2+":00":i*2+":00");
//                        }
//                        if (data1 != null && !data1.isEmpty()){
//                            for (int x = a; x < data1.size(); x++) {
//                                Object obj = data1.get(x); // 通过索引获取元素
//                                JSONObject object = JSONUtil.parseObj(obj);
//                                if (object.getStr("timeStr").substring(0, 2).compareTo(time) >0){
//                                    break;
//                                }
//                                count += object.getDouble("power");
//                                a++;
//                            }
//                            map1.put("content", y == 0 ?  count: (hashMaps.get(y).get(time) == null) ? 0.0 : (Double) hashMaps.get(y).get(time) + count);
//
//                            hashMaps.add(map1);
//                            continue;
//                        }else {
//                            map1.put("content", y == 0 ?  0: (hashMaps.get(y).get(time) == null) ? 0.0 : (Double) hashMaps.get(y).get(time) + 0);
//                        }
//                        hashMaps.add(map1);
//                    }
//                    y++;
//                }
                break;
            case 2:
                String s2 = stationMonth(apiEntity, idList.getFirst(), bo.getDate());
                JSONObject jsonObject2 = JSONUtil.parseObj(s2);
                JSONArray data2 = jsonObject2.getJSONArray("data");

                if (data2 != null && !data2.isEmpty()){
                    for (Object obj : data2) {
                        HashMap<String, Object> map1 = new HashMap<>();
                        JSONObject object = JSONUtil.parseObj(obj);
                        map1.put("time", object.getStr("dateStr"));
                        map1.put("content", object.get("money"));
                        hashMaps.add(map1);
                    }
                }else {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
                    YearMonth yearMonth = YearMonth.parse(bo.getDate(), formatter);

                    int year = yearMonth.getYear();  // 2025
                    int monthValue = yearMonth.getMonthValue();
                    int day = LocalDate.of(year, monthValue, 1).lengthOfMonth();
                    String month = monthValue<10?"0"+monthValue:monthValue+"";
                    for (int i = 1; i <= day; i++){
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("time", i<10?month+"-0"+i:month+"-"+i);
                        map1.put("content", 0);
                        hashMaps.add(map1);
                    }
                }
                break;

            case 3:
                String s3 = stationYear(apiEntity, idList.getFirst(), bo.getDate());
                JSONObject jsonObject3 = JSONUtil.parseObj(s3);
                JSONArray data3 = jsonObject3.getJSONArray("data");
                System.out.println(data3);
                if (data3 != null && !data3.isEmpty()) {
                    for (Object obj : data3) {
                        HashMap<String, Object> map3 = new HashMap<>();
                        JSONObject object = JSONUtil.parseObj(obj);
                        map3.put("time", object.getStr("dateStr").substring(0, 7));
                        map3.put("content", object.get("money"));
                        hashMaps.add(map3);
                    }
                }else {
                    for (int i = 1; i <= 12; i++){
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("time", i<10?bo.getDate()+"-0"+i:bo.getDate()+"-"+i);
                        map1.put("content", 0);
                        hashMaps.add(map1);
                    }
                }
                break;

            default:
                break;
        }

        map.put("data",hashMaps);

        String s2 = stationDetail(apiEntity, idList.getFirst());
        JSONObject jsonObject2 = JSONUtil.parseObj(s2);
        JSONObject data2 = jsonObject2.getJSONObject("data");
        map.put("allInCome",data2.get("allInCome"));//累计收益
        map.put("monthInCome",data2.get("monthInCome"));//本月收益
        map.put("yearInCome",data2.get("yearInCome"));//本年收益
        map.put("price",data2.get("price"));//每度电收益

        System.out.println(map);
        return map;
    }

    /**
     * 查询全部设备报警信息
     * @return
     */
    @Override
    public List<HashMap<String, Object>> getAlarmListOverview() {
        List<HashMap<String, Object>> list = new ArrayList<>();
        GinlongApiEntity apiEntity = getGinlongApiEntity();
        String s = alarmList(apiEntity);
        System.out.println(s);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray records = data.getJSONArray("records");
        for (Object record : records) {
            HashMap<String, Object> map = new HashMap<>();
            JSONObject obj = JSONUtil.parseObj(record);
            map.put("stationName", obj.get("stationName"));//电站名称
            map.put("alarmLevel", obj.get("alarmLevel")); // 报警等级：1 = 提示，2 = 一般，3 = 紧急
            map.put("alarmBeginTime", obj.get("alarmBeginTime")); //报警开始时间
            map.put("alarmMsg", obj.get("alarmMsg")); //报警内容
            map.put("advice", obj.get("advice")); //报警处理建议
            map.put("state", obj.get("state")); //报警状态：0 = 未处理，1 = 已处理，2 = 已恢复
            if ("1".equals(obj.getStr("state")) || "2".equals(obj.getStr("state"))){
                continue;
            }
            list.add(map);
        }
        return list;
//        return list.stream().filter(map -> {
//            Object statusObj = map.get("state");
//            if (statusObj instanceof Integer) {
//                int status = (Integer) statusObj;
//                return status == 1 || status == 2;
//            }
//            return false;
//        }).collect(Collectors.toList());
    }

    private void getStationDetailList(String s1, double dayEnergy, HashMap<String, Object> map) {
        JSONObject jsonObject = JSONUtil.parseObj(s1);
        String dayEnergyOld = stringRedisTemplate.opsForValue().get("dayEnergy");
        map.put("dayEnergyOld", dayEnergyOld != null ? Double.parseDouble(dayEnergyOld) : 0.0);
        String powerStationAvoidedCo2Old = stringRedisTemplate.opsForValue().get("powerStationAvoidedCo2");
        map.put("powerStationAvoidedCo2Old", powerStationAvoidedCo2Old != null ? Double.parseDouble(powerStationAvoidedCo2Old) : 0.0);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray records = data.getJSONArray("records");
        double powerStationAvoidedCo2 = 0.0;
        for (Object record : records) {
            JSONObject object = JSONUtil.parseObj(record);
            dayEnergy += object.getDouble("dayEnergy");
            powerStationAvoidedCo2 += object.getDouble("powerStationAvoidedCo2");
        }
        map.put("dayEnergy", dayEnergy);//今日总发电量
        map.put("powerStationAvoidedCo2", powerStationAvoidedCo2);//碳排放量
    }
    private static void getStationDetailList1(String s1, double dayEnergy) {
        JSONObject jsonObject = JSONUtil.parseObj(s1);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray records = data.getJSONArray("records");
        double powerStationAvoidedCo2 = 0.0;
        for (Object record : records) {
            JSONObject object = JSONUtil.parseObj(record);
            dayEnergy += object.getDouble("dayEnergy");
            powerStationAvoidedCo2 += object.getDouble("powerStationAvoidedCo2");
        }
        RedisUtils.setCacheObject("dayEnergy",dayEnergy);//今日总发电量
        RedisUtils.setCacheObject("powerStationAvoidedCo2",powerStationAvoidedCo2);//碳排放量

        RedisUtils.expire("dayEnergy",86400);
        RedisUtils.expire("powerStationAvoidedCo2",86400);

    }

    private void getUserStationList(String s, List<Long> idList, HashMap<String, Object> map) {
        JSONObject jsonObject = JSONUtil.parseObj(s);
        double capacity = 0.0; // 总装机容量
        int module = 0;//光伏板数量
        double generateElectricity = 0.0;//发电效率
        double batteryTodayDischargeEnergy = 0.0;//放电效率
        double batteryTodayChargeEnergy = 0.0;//充电效率
        String capacityOld = stringRedisTemplate.opsForValue().get("capacity");
        map.put("capacityOld", capacityOld != null ? Double.parseDouble(capacityOld) : 0.0);
        String moduleOld = stringRedisTemplate.opsForValue().get("module");
        map.put("moduleOld", moduleOld != null ? Double.parseDouble(moduleOld) : 0.0);
        String generateElectricityOld = stringRedisTemplate.opsForValue().get("generateElectricity");
        map.put("generateElectricityOld", generateElectricityOld != null ? Double.parseDouble(generateElectricityOld) : 0.0);
        String operatingRateOld = stringRedisTemplate.opsForValue().get("operatingRate");
        map.put("operatingRateOld", operatingRateOld != null ? Double.parseDouble(operatingRateOld) : 0.0);

        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject stationStatusVo = data.getJSONObject("stationStatusVo");
        if (stationStatusVo.getInt("all") >0){
            JSONObject page = data.getJSONObject("page");
            JSONArray records = page.getJSONArray("records");
            int all = stationStatusVo.getInt("all");//全部电站
            if (!records.isEmpty()){
                for (Object record : records) {
                    JSONObject object = JSONUtil.parseObj(record);
                    capacity += object.getDouble("capacity");
                    batteryTodayDischargeEnergy += object.getDouble("batteryTodayDischargeEnergy");
                    batteryTodayChargeEnergy += object.getDouble("batteryTodayChargeEnergy");
                    module += object.getInt("module");
                    idList.add(object.getLong("id"));

                }
            }
            if (batteryTodayDischargeEnergy >0){
                generateElectricity = (1-(batteryTodayChargeEnergy/batteryTodayDischargeEnergy))*100;
            }else {
                generateElectricity = 0;
            }
            map.put("operatingRate", all);//电站总数
        }else {
            map.put("operatingRate", 0.0);//运行率
        }
        map.put("capacity", capacity);//总装机容量
        map.put("module", module);//光伏板数量
        map.put("generateElectricity", generateElectricity);//发电效率
    }

    private static void getUserStationList1(String s, List<Long> idList) {
        JSONObject jsonObject = JSONUtil.parseObj(s);
        double capacity = 0.0; // 总装机容量
        int module = 0;//光伏板数量
        double generateElectricity = 0.0;//发电效率
        double batteryTodayDischargeEnergy = 0.0;//放电效率
        double batteryTodayChargeEnergy = 0.0;//充电效率
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject stationStatusVo = data.getJSONObject("stationStatusVo");
        if (stationStatusVo.getInt("all") >0){
            JSONObject page = data.getJSONObject("page");
            JSONArray records = page.getJSONArray("records");
            int all = stationStatusVo.getInt("all");//全部电站
            int normal = stationStatusVo.getInt("normal");//正常电站

            if (!records.isEmpty()){
                for (Object record : records) {
                    JSONObject object = JSONUtil.parseObj(record);
                    capacity += object.getDouble("capacity");
                    batteryTodayDischargeEnergy += object.getDouble("batteryTodayDischargeEnergy");
                    batteryTodayChargeEnergy += object.getDouble("batteryTodayChargeEnergy");
                    module += object.getInt("module");
                    idList.add(object.getLong("id"));

                }
            }
            if (batteryTodayDischargeEnergy >0){
                generateElectricity = (1-(batteryTodayChargeEnergy/batteryTodayDischargeEnergy))*100;
            }else {
                generateElectricity = 0;
            }
            RedisUtils.setCacheObject("operatingRate",all);
        }else {
            RedisUtils.setCacheObject("operatingRate",0);
        }
        RedisUtils.setCacheObject("capacity",capacity);//总装机容量
        RedisUtils.setCacheObject("module",module);//光伏板数量
        RedisUtils.setCacheObject("generateElectricity",generateElectricity);//发电效率
        RedisUtils.expire("capacity",86400);
        RedisUtils.expire("module",86400);
        RedisUtils.expire("generateElectricity",86400);
    }

//    @Scheduled(cron = "0 59 23 * * ?")
    @Scheduled(initialDelay = 5000)
    public void redisSetData(){
        GinlongApiEntity apiEntity = getGinlongApiEntity();

        double dayEnergy = 0.0; //今日总发电量

        List<Long> idList = new ArrayList<>();
        String s = userStationList(apiEntity);
        String s2 = inverterList(apiEntity);
        getInverterList1(s2);
        getUserStationList1(s, idList);

        //使用获取多个电站详情接口获取数据
        String s1 = stationDetailList(apiEntity, idList);
//        System.out.println(s1);
        getStationDetailList1(s1, dayEnergy);
    }
}
