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

import com.alibaba.fastjson.JSONObject;
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 org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class EnergyAccessServiceImpl implements EnergyAccessService {

    @Autowired
    private HttpRequestUtil httpRequestUtil;

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

    @Override
    public Page<Map<String, Object>> getInstalledCapacity(String current, String pageSize, String code, String sourceStationId, String tp) {
        //改为部盾接口
        StringBuilder requestUrl = new StringBuilder(Constants.BASE_URL).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);

        List returnList = data.getJSONArray("data");
        logger.info("获取并网容量接口调用对端返回结果：{}",returnList.toString());
        Page<Map<String, Object>> pageIPage;
        returnList.forEach(result -> {
            JSONObject jsonObject = (JSONObject) result;
            String actualInstalledCapacity = jsonObject.getString("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(Constants.BASE_URL).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 returnList = data.getJSONArray("data");
        logger.info("获取片区指标完成情况调用对端返回结果：{}",returnList.toString());
        //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(returnList)) {
            return pageIPage;
        }
        returnList.forEach(result -> {
            String oldName = "";
            JSONObject jsonObject = (JSONObject) result;
            String rate = jsonObject.getString("rate");
            String newRate = "";
            if (StringUtils.isNotEmpty(rate)) {
                newRate = rate.replace("%", "");
                BigDecimal bd = new BigDecimal(newRate);
                jsonObject.put("rate", bd.setScale(4,BigDecimal.ROUND_HALF_UP));
            }

            String quota = jsonObject.getString("quota");
            if (StringUtils.isNotEmpty(quota)) {
                BigDecimal bd = new BigDecimal(quota);
                jsonObject.put("quota", bd.setScale(4,BigDecimal.ROUND_HALF_UP));
            }

            String generatingCapacity = jsonObject.getString("generating_capacity");
            if (StringUtils.isNotEmpty(generatingCapacity)) {
                BigDecimal bd = new BigDecimal(generatingCapacity);
                jsonObject.put("generating_capacity", bd.setScale(4,BigDecimal.ROUND_HALF_UP));
            }

            jsonObject.put("seriesData", StringUtils.isNotEmpty(newRate) ? Arrays.asList(new BigDecimal(newRate).setScale(4,BigDecimal.ROUND_HALF_UP)) : 0D);
            jsonObject.put("axisData", Arrays.asList("RATE"));
            if ("1".equals(tp)) {
                oldName = jsonObject.getString("station_name");
                jsonObject.remove("station_name");
            } else {
                oldName = jsonObject.getString("area_name");
                jsonObject.remove("area_name");
            }
            jsonObject.put("name", oldName);

        });
        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;
    }
}
