package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jxiop.api.util.Constants;
import com.yeejoin.amos.boot.module.jxiop.api.util.HttpRequestUtil;
import com.yeejoin.amos.boot.module.jxiop.biz.service.EnergyAccessService;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.EnergyAccessMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EnergyAccessServiceImpl implements EnergyAccessService {

    @Autowired
    private HttpRequestUtil httpRequestUtil;

    @Autowired
    EnergyAccessMapper energyAccessMapper;

    private final Logger logger = LoggerFactory.getLogger(EnergyAccessServiceImpl.class);

	@Value("${budun.baseurl:http://iiet-jepcc.powerchina.cn:8088/screen_api}")
	private String budunBaseURL;
    
    @Override
    public Page<Map<String, Object>> getInstalledCapacity(String current, String pageSize, String code, String sourceStationId, String tp) {

        if (StringUtils.isEmpty(tp)) {
            logger.error("参数tp不能为空");
            throw new RuntimeException("参数tp不能为空");
        }
        List<Map<String, Object>> returnList;
        if ("1".equals(tp)) {
            returnList = energyAccessMapper.getStationInfo(code);
            logger.info("获取并网容量接口查询本地返回结果：{}", returnList.toString());
        } else {
            //改为部盾接口
            StringBuilder requestUrl = new StringBuilder(budunBaseURL).append("?").append(Constants.get_station_actual_installed_capacity);
            if (StringUtils.isNotEmpty(code)) {
                requestUrl.append("&code=").append(code);
            }

            if (StringUtils.isNotEmpty(sourceStationId)) {
                requestUrl.append("&source_station_id=").append(sourceStationId);
            }

            if (StringUtils.isNotEmpty(tp)) {
                requestUrl.append("&tp=").append(tp);
            }
            JSONObject data = httpRequestUtil.getResPonse(requestUrl.toString(), Constants.REQUEST_GET, "",
                    Constants.resovleRule_data);
            returnList = JSONArray.parseObject(data.getJSONArray("data").toJSONString(), new TypeReference<List<Map<String, Object>>>() {});
            logger.info("获取并网容量接口调用对端返回结果：{}", returnList.toString());
        }
        Page<Map<String, Object>> pageIPage;
        returnList.forEach(jsonObject -> {
            String actualInstalledCapacity;
            if ("1".equals(tp)) {
                actualInstalledCapacity = String.valueOf(jsonObject.get("installed_capacity"));
            }else{
                actualInstalledCapacity = String.valueOf(jsonObject.get("actual_installed_capacity"));
            }

            if (StringUtils.isNotEmpty(actualInstalledCapacity)) {
                BigDecimal bd = new BigDecimal(actualInstalledCapacity);
                jsonObject.put("actual_installed_capacity", bd.setScale(4, BigDecimal.ROUND_HALF_UP));
            }
        });
        int newCurrent = Integer.parseInt(current);
        int newPageSize = Integer.parseInt(pageSize);
        if (StringUtils.isBlank(pageSize) || StringUtils.isBlank(pageSize)) {
            pageIPage = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageIPage = new Page<>(newCurrent, newPageSize);
        }

        if (CollectionUtils.isEmpty(returnList)) {
            return pageIPage;
        }

        pageIPage.setTotal(returnList.size());
        int endIndex = newCurrent * newPageSize;
        if (returnList.size() > endIndex) {
            pageIPage.setRecords(returnList.subList(((newCurrent - 1) * newPageSize), endIndex));
        } else {
            pageIPage.setRecords(returnList.subList(((newCurrent - 1) * newPageSize), returnList.size()));
        }
        logger.info("获取并网容量接口最终返回结果：{}", pageIPage.getRecords());
        return pageIPage;
    }

    @Override
    public Page<Map<String, Object>> getQuotaCompleteInfo(String current, String pageSize, String code, String sourceStationId, String tp) {
        //改为部盾接口
//        StringBuilder requestUrl = new StringBuilder(budunBaseURL).append("?").append(Constants.get_quota_complate_info);
//        LocalDate currentDate = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String formattedDate = currentDate.format(formatter);
//        requestUrl.append("&reporting_data=").append(formattedDate);
//        if (StringUtils.isNotEmpty(code)) {
//            requestUrl.append("&code=").append(code);
//        }
//
//        if (StringUtils.isNotEmpty(sourceStationId)) {
//            requestUrl.append("&source_station_id=").append(sourceStationId);
//        }
//
//        if (StringUtils.isNotEmpty(tp)) {
//            requestUrl.append("&tp=").append(tp);
//        }
//
//        JSONObject data = httpRequestUtil.getResPonse(requestUrl.toString(), Constants.REQUEST_GET, "",
//                Constants.resovleRule_data);
//
//        List<Map<String, Object>> returnList = JSONArray.parseObject(data.getJSONArray("data").toJSONString(), new TypeReference<List<Map<String, Object>>>() {});
//        logger.info("获取片区指标完成情况调用对端返回结果：{}", returnList.toString());
//        List<Map<String, Object>> finalList = new ArrayList<>();
//
//        //tp=1，代表是根据片区查询，需要根据本地查询的结果数据取交集
//        if ("1".equals(tp)) {
//            List<Map<String, Object>> currentList = energyAccessMapper.getStationInfo(code);
//            logger.info("获取片区指标完成情况查询本地返回结果：{}", currentList.toString());
//            if(!CollectionUtils.isEmpty(currentList)){
//                finalList = currentList.stream().map(e1 ->
//                        returnList.stream()
//                                .filter(e2 -> e1.get("station_name").equals(e2.get("station_name")))
//                                .findFirst()
//                                .map(e2 -> {
//                                    e1.put("name", String.valueOf(e2.get("station_name")));
//                                    e1.put("quota", String.valueOf(e2.get("quota")));
//                                    e1.put("generating_capacity", e2.get("generating_capacity"));
//                                    e1.put("rate", String.valueOf(e2.get("rate")));
//                                    return e1;
//                                }).orElseGet(() -> {
//                                    e1.put("name", e1.get("station_name"));
//                                    e1.put("quota", "0");
//                                    e1.put("generating_capacity", "0");
//                                    e1.put("rate", "0");
//                                    return e1;
//                                })
//                ).collect(Collectors.toList());
//            }
//        } else {
//            finalList.addAll(returnList);
//        }
//
//        //rate的值去掉百分号，名称字段名统一用name代替
        Page<Map<String, Object>> pageIPage;
        int newCurrent = Integer.parseInt(current);
        int newPageSize = Integer.parseInt(pageSize);
        if (StringUtils.isBlank(pageSize) || StringUtils.isBlank(pageSize)) {
            pageIPage = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageIPage = new Page<>(newCurrent, newPageSize);
        }
//        if (CollectionUtils.isEmpty(finalList)) {
//            return pageIPage;
//        }
//        finalList.forEach(result -> {
//            String oldName = "";
//            String rate = String.valueOf(result.get("rate"));
//            String newRate = "";
//            if (StringUtils.isNotEmpty(rate)) {
//                newRate = rate.replace("%", "");
//                BigDecimal bd = new BigDecimal(newRate);
//                result.put("rate", bd.setScale(4, BigDecimal.ROUND_HALF_UP));
//            }
//
//            String quota = String.valueOf(result.get("quota"));
//            if (StringUtils.isNotEmpty(quota)) {
//                BigDecimal bd = new BigDecimal(quota);
//                result.put("quota", bd.setScale(4, BigDecimal.ROUND_HALF_UP));
//            }
//
//            String generatingCapacity = String.valueOf(result.get("generating_capacity"));
//            if (StringUtils.isNotEmpty(generatingCapacity)) {
//                BigDecimal bd = new BigDecimal(generatingCapacity);
//                result.put("generating_capacity", bd.setScale(4, BigDecimal.ROUND_HALF_UP));
//            }
//
//            result.put("seriesData", StringUtils.isNotEmpty(newRate) ? Arrays.asList(new BigDecimal(newRate).setScale(4, BigDecimal.ROUND_HALF_UP)) : 0D);
//            result.put("axisData", Arrays.asList("RATE"));
//            if ("1".equals(tp)) {
//                oldName = String.valueOf(result.get("station_name"));
//                result.remove("station_name");
//            } else {
//                oldName = String.valueOf(result.get("area_name"));
//                result.remove("area_name");
//            }
//            result.put("name", oldName);
//
//        });
//        pageIPage.setTotal(returnList.size());
//        int endIndex = newCurrent * newPageSize;
//        if (finalList.size() > endIndex) {
//            pageIPage.setRecords(finalList.subList(((newCurrent - 1) * newPageSize), endIndex));
//        } else {
//            pageIPage.setRecords(finalList.subList(((newCurrent - 1) * newPageSize), finalList.size()));
//        }

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        list.add(map1);map1.put("name","华中");map1.put("quota","70176.2775");map1.put("generating_capacity","184655.0970");
        map1.put("rate","38");
        map1.put("seriesData", Arrays.asList(38));
        map1.put("axisData", Arrays.asList("RATE"));
        Map<String,Object> map2 = new HashMap<>();
        list.add(map2);map2.put("name","华北");map2.put("quota","9226.2276");map2.put("generating_capacity","26298.4790");map2.put("rate","35");
        map2.put("seriesData", Arrays.asList(35));
        map2.put("axisData", Arrays.asList("RATE"));
        Map<String,Object> map3 = new HashMap<>();
        list.add(map3);map3.put("name","华南");map3.put("quota","107538.7704");map3.put("generating_capacity","237895.8");map3.put("rate","45");
        map3.put("seriesData", Arrays.asList(45));
        map3.put("axisData", Arrays.asList("RATE"));
        Map<String,Object> map4 = new HashMap<>();
        list.add(map4);map4.put("name","西北");map4.put("quota","70938.3183");map4.put("generating_capacity","166396.2206");map4.put("rate","43");
        map4.put("seriesData", Arrays.asList(43));
        map4.put("axisData", Arrays.asList("RATE"));
        Map<String,Object> map5 = new HashMap<>();
        list.add(map5);map5.put("name","东北");map5.put("quota","283.5364");map5.put("generating_capacity","453.774");map5.put("rate","62");
        map5.put("seriesData", Arrays.asList(62));
        map5.put("axisData", Arrays.asList("RATE"));
        Map<String,Object> map6 = new HashMap<>();
        list.add(map6);map6.put("name","西南");map6.put("quota","15103.0166");map6.put("generating_capacity","44968.3077");map6.put("rate","34");
        map6.put("seriesData", Arrays.asList(34));
        map6.put("axisData", Arrays.asList("RATE"));
        Map<String,Object> map7 = new HashMap<>();
        list.add(map7);map7.put("name","分布式");map7.put("quota","2455.2157");map7.put("generating_capacity","5426.2654");map7.put("rate","45");
        map7.put("seriesData", Arrays.asList(45));
        map7.put("axisData", Arrays.asList("RATE"));
        pageIPage.setTotal(list.size());
        pageIPage.setRecords(list);
        logger.info("获取片区指标完成情况最终返回结果：{}", pageIPage.getRecords());
        return pageIPage;
    }
}
