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


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESMoonPowerGeneration;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.CommonMapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EarningsForecastImpl {

    @Autowired
    private CommonServiceImpl commonService;
    @Autowired
    private CommonMapper commonMapper;
    @Value("${forecast.url}")
    private String forecastUrl;
    @Autowired
    private StationBasicMapper stationBasicMapper;
    //收益 时间曲线图数据组装
    public Object earningsForecastSJQXT (Long stationId, String type){

        List<String> beforeMonth = DateUtils.getBeforeCurrentMonth(-10, false);
        List<String> afterMonth = DateUtils.getBeforeCurrentMonth(3, true);

        List<Map<String, String>> list = beforeMonth.stream()
                .map(month -> MapBuilder.<String,String>create().put ("MonthYear", month).build())
                .collect(Collectors.toList());
        List<Map<String, String>> lastThreeMonth = afterMonth.stream()
                .map(month -> MapBuilder.<String,String>create().put ("MonthYear", month).build())
                .collect(Collectors.toList());

        Map<String, List<String>> queryCondtion1 = new HashMap<>();
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        if (type.equals("FDZ")){

            queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
        }else {
            queryCondtion1.put(CommonConstans.QueryStringGateWayId,Arrays.asList(stationBasic.getBoosterGatewayId()));
        }

        List<Map<String, String>> objects = new ArrayList<>();
        TreeMap<String, String> months= new TreeMap<>();
        list.forEach(e->{
            Map<String, String> likeQueryCondtion = new HashMap<>();
            likeQueryCondtion.put("id.keyword",e.get("MonthYear")+"*");
            objects.add(likeQueryCondtion);
            String key = e.get("MonthYear").split("-")[1];
            months.put(String.valueOf(Integer.parseInt(key)),e.get("MonthYear"));
        });

        TreeMap<String, Double> map = commonService.getListDataByCondtionsSum(queryCondtion1,objects, ESMoonPowerGeneration.class,null);
     if (null == map || map.isEmpty() ){
         return null;
     }
        TreeMap<String, String> carbonDioxide = new TreeMap<>();
        TreeMap<String, String>  standardCoal = new TreeMap<>();
        TreeMap<String, String>  toner = new TreeMap<>();
        TreeMap<String, String>  sulfurDioxide = new TreeMap<>();

        //计算历史月发电量的收益
        map.keySet().forEach(e->{
            carbonDioxide.put(months.get(e), String.format("%.3f",map.get(e) * CommonConstans.carbonDioxide));
            standardCoal.put(months.get(e),String.format("%.3f",map.get(e) * CommonConstans.standardCoal));
            toner.put(months.get(e),String.format("%.3f",map.get(e) * CommonConstans.toner));
            sulfurDioxide.put(months.get(e),String.format("%.3f",map.get(e) * CommonConstans.sulfurDioxide));
        });



        List<TreeMap<String,List<List<String>>>> resultList = new ArrayList<>();
        TreeMap<String,List<List<String>>> Co2Map = new TreeMap();
        TreeMap<String,List<List<String>>> standardCoalMap = new TreeMap();
        TreeMap<String,List<List<String>>> tonerMap = new TreeMap();
        TreeMap<String,List<List<String>>> sulfurDioxideMap = new TreeMap();
        TreeMap<String,List<List<String>>> Co2ForecastMap = new TreeMap();
        TreeMap<String,List<List<String>>> standardCoalForecastMap = new TreeMap();
        TreeMap<String,List<List<String>>> tonerForecastMap = new TreeMap();
        TreeMap<String,List<List<String>>> sulfurDioxideForecastMap = new TreeMap();

        //组装历史数据折线图数据
        List<List<String>> Co2List = this.buildResultData(carbonDioxide);
        Co2Map.put("data",Co2List);
        List<List<String>> standardCoalList = this.buildResultData(standardCoal);
        standardCoalMap.put("data",standardCoalList);
        List<List<String>> tonerList = this.buildResultData(toner);
        tonerMap.put("data",tonerList);
        List<List<String>> sulfurDioxideList = this.buildResultData(sulfurDioxide);
        sulfurDioxideMap.put("data",sulfurDioxideList);



        //查询预测收益接口
        JSONObject carbonDioxideData = getResponse("二氧化碳减排量", carbonDioxide.values().stream().collect(Collectors.toList()));
        JSONObject standardCoalData = getResponse("标准煤减排量", standardCoal.values().stream().collect(Collectors.toList()));
        JSONObject tonerData = getResponse("炭粉尘减排量", toner.values().stream().collect(Collectors.toList()));
        JSONObject sulfurDioxideData = getResponse("二氧化硫减排量", sulfurDioxide.values().stream().collect(Collectors.toList()));

        //将预测返回的数据组装成组件需要的格式
        List<List<String>> carbonDioxideList = this.buildData(lastThreeMonth, carbonDioxideData, Co2List);
        Co2ForecastMap.put("data",carbonDioxideList);
        List<List<String>> standardCoalLists = this.buildData(lastThreeMonth, standardCoalData, standardCoalList);
        standardCoalForecastMap.put("data",standardCoalLists);
        List<List<String>> tonerLists = this.buildData(lastThreeMonth, tonerData, tonerList);
        tonerForecastMap.put("data",tonerLists);
        List<List<String>> sulfurDioxideLists = this.buildData(lastThreeMonth, sulfurDioxideData, sulfurDioxideList);
        sulfurDioxideForecastMap .put("data",sulfurDioxideLists);

        resultList.add(Co2Map);
        resultList.add(standardCoalMap);
        resultList.add(tonerMap);
        resultList.add(sulfurDioxideMap);
        resultList.add(Co2ForecastMap);
        resultList.add(standardCoalForecastMap);
        resultList.add(tonerForecastMap);
        resultList.add(sulfurDioxideForecastMap);

        return resultList;

    }

//收益 折线图数据组装
    public Object earningsForecastZXT (Long stationId, String type){
        List<String> beforeMonth = DateUtils.getBeforeCurrentMonth(-10, false);
        List<String> afterMonth = DateUtils.getBeforeCurrentMonth(3, true);
        List<Map<String, String>> list = beforeMonth.stream()
                .map(month -> MapBuilder.<String,String>create().put ("MonthYear", month).build())
                .collect(Collectors.toList());
        List<Map<String, String>> lastThreeMonth = afterMonth.stream()
                .map(month -> MapBuilder.<String,String>create().put ("MonthYear", month).build())
                .collect(Collectors.toList());
        Map<String, List<String>> queryCondtion1 = new HashMap<>();
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        if (type.equals("FDZ")){

            queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
        }else {
            queryCondtion1.put(CommonConstans.QueryStringGateWayId,Arrays.asList(stationBasic.getBoosterGatewayId()));
        }

        List<Map<String, String>> objects = new ArrayList<>();
        TreeMap<String, String> months= new TreeMap<>();
        list.forEach(e->{
            Map<String, String> likeQueryCondtion = new HashMap<>();
            likeQueryCondtion.put("id.keyword",e.get("MonthYear")+"*");
            objects.add(likeQueryCondtion);
            String key = e.get("MonthYear").split("-")[1];
            months.put(String.valueOf(Integer.parseInt(key)),e.get("MonthYear"));
        });

        TreeMap<String, Double> map = commonService.getListDataByCondtionsSum(queryCondtion1,objects, ESMoonPowerGeneration.class,null);
        if (null == map || map.isEmpty() ){
            return null;
        }
        TreeMap<String, String> carbonDioxide = new TreeMap<>();
        TreeMap<String, String>  standardCoal = new TreeMap<>();
        TreeMap<String, String>  toner = new TreeMap<>();
        TreeMap<String, String>  sulfurDioxide = new TreeMap<>();

        //计算历史月发电量的收益
        map.keySet().forEach(e->{
            carbonDioxide.put(months.get(e), String.format("%.3f",map.get(e) * CommonConstans.carbonDioxide));
            standardCoal.put(months.get(e),String.format("%.3f",map.get(e) * CommonConstans.standardCoal));
            toner.put(months.get(e),String.format("%.3f",map.get(e) * CommonConstans.toner));
            sulfurDioxide.put(months.get(e),String.format("%.3f",map.get(e) * CommonConstans.sulfurDioxide));
        });

        //查询预测收益接口
        JSONObject carbonDioxideData = getResponse("二氧化碳减排量", carbonDioxide.values().stream().collect(Collectors.toList()));
        JSONObject standardCoalData = getResponse("标准煤减排量", standardCoal.values().stream().collect(Collectors.toList()));
        JSONObject tonerData = getResponse("炭粉尘减排量", toner.values().stream().collect(Collectors.toList()));
        JSONObject sulfurDioxideData = getResponse("二氧化硫减排量", sulfurDioxide.values().stream().collect(Collectors.toList()));


        Map<String, Object> carbonDioxideMap = this.buildDataNew(carbonDioxideData);
        Map<String, Object> standardCoalMap = this.buildDataNew(standardCoalData);
        Map<String, Object> tonerDataMap = this.buildDataNew(tonerData);
        Map<String, Object> sulfurDioxideMap = this.buildDataNew(sulfurDioxideData);

        List<Map<String, Object>> dataList = new ArrayList<>();
        dataList.add(MapBuilder.<String, Object>create().put("data",carbonDioxide.values()).build());
        dataList.add(MapBuilder.<String, Object>create().put("data",standardCoal.values()).build());
        dataList.add(MapBuilder.<String, Object>create().put("data",toner.values()).build());
        dataList.add( MapBuilder.<String, Object>create().put("data",sulfurDioxide.values()).build());
        dataList.add(carbonDioxideMap);
        dataList.add(standardCoalMap);
        dataList.add(tonerDataMap);
        dataList.add(sulfurDioxideMap);

        List<String> axisData = new ArrayList<>();
        lastThreeMonth.forEach(e->{
            axisData.add(e.get("MonthYear")) ;
        });

        List<String> data = new ArrayList<>(carbonDioxide.keySet());
        data.addAll(axisData);

     return    MapBuilder.<String, Object>create().put("axisData",data).put("seriesData",dataList).build();

    }


    List<List<String>> buildResultData( TreeMap<String, String> map){
        List<List<String>> lists = new ArrayList<>();
        map.keySet().forEach(e->{
            List<String> list = Arrays.asList(e, String.valueOf(map.get(e)));
            lists.add(list);
        });

        return lists;
    }


    String  buildParams(String name, List<String> values){

        HashMap<Object, Object> requestParams = new HashMap<>();
        HashMap<Object, Object> valueLabel = new HashMap<>();
        HashMap<Object, Object> value = new HashMap<>();
        value.put("值",values);
        valueLabel.put(name,value);
        value.put("名称",name);
        HashMap<Object, Object> params = new HashMap<>();
        HashMap<Object, Object> basic = new HashMap<>();
        HashMap<Object, Object> dispPrecision = new HashMap<>();
        dispPrecision.put("disp_precision",3);
        params.put("config",dispPrecision);
        basic.put("data",name);
        basic.put("seasonal_length",values.size()/2);
        basic.put("model_type","additive");
        basic.put("model_component_type","seasonal_only");
        basic.put("is_generate_forecast",true);
        basic.put("forecast_number","3");
        params.put("basic",basic);
        requestParams.put("params",params);
        requestParams.put("dataset",valueLabel);
        return JSON.toJSONString(requestParams);

    }

    JSONObject  getResponse(String name, List<String> values){
        String requestParam=buildParams(name,values);
        Map<String, String> hashMaphead = new HashMap<>();
        hashMaphead.put("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        String respone = HttpUtil.createPost(forecastUrl).headerMap(hashMaphead, false).
                body(requestParam).execute().body();
        return JSONObject.parseObject(respone);
    }

    List<List<String>>   buildData(List<Map<String, String>> data,JSONObject obj,List<List<String>> lists ){

        List<List<String>> newList = new ArrayList<>();
        newList.addAll(lists);
        JSONObject dataObject = obj.getJSONObject("data");
        // 从data对象中提取forecast和history数组
        JSONArray forecastArray = dataObject.getJSONArray("forecast");
        for (int i = 0; i < forecastArray.size(); i++) {
            List<String> list = Arrays.asList(data.get(i).get("MonthYear"),forecastArray.getString(i));
            newList.add(list);
        }
        return newList;
    }

         Map<String, Object>  buildDataNew(JSONObject forecastObj){
             JSONObject dataObject = forecastObj.getJSONObject("data");
             // 从data对象中提取forecast和history数组
             JSONArray forecastArray = dataObject.getJSONArray("forecast");
             JSONArray historyArray = dataObject.getJSONArray("history");
             forecastArray.addAll(historyArray);

        return MapBuilder.<String,Object>create().put("data",forecastArray).build();
         }





}
