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()));
        }
        logger.info("获取片区指标完成情况最终返回结果：{}", pageIPage.getRecords());
        return pageIPage;
    }
}
