package com.sifang.modules.monitor.service;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.alioss.OSSClientConstants;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.monitor.dao.MonitorCollectDataDao;
import com.sifang.modules.monitor.vo.OverviewStaticDataVo;
import com.sifang.modules.monitor.vo.ThreeDaysPowerVo;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.utils.http.HttpUtils;
import com.sifang.modules.youkua.service.NhPowerStationService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;

@Service
public class MonitorCollectDataService extends BaseService {

    @Autowired
    private MonitorCollectDataDao collectDataDao;

    @Autowired
    private CustomerEntryService entryService;

    @Autowired
    private NhPowerStationService nhPowerStationService;

    /**
     * 近三天发电量
     */
    public ThreeDaysPowerVo getDataInThreeDays(String entryId) {

        ThreeDaysPowerVo vo = nhPowerStationService.getThreeDaysPower(entryId);
        return vo;
//        ThreeDaysPowerVo powerVo = new ThreeDaysPowerVo();
//        // 查询逆变器
//        List<String> nbqSnList = collectDataDao.findNbqSnByEntryId(entryId);
//        if (nbqSnList == null) {
//            return powerVo;
//        }
//        // 查询电站最早发电时间
//        Date firstGenerate = collectDataDao.findFirstGenerate(nbqSnList);
//        if (firstGenerate == null) {
//            return powerVo;
//        }
//        powerVo.setFirstGenerate(DateUtils.formatDate(firstGenerate, "yyyy-MM-dd"));
//        // 获取当前时间
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.DATE, -1);
//        String endTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd");
//        instance.add(Calendar.DATE, -2);
//        String startTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd");
//        // 获取三天发电量
//        List<Record> list = collectDataDao.findDataInThreeDays(nbqSnList, startTime, endTime);
//        for (int i = 0; i < list.size(); i++) {
//            if (i == 0) {
//                powerVo.setFirstDay(list.get(i).getStr("statDate"));
//                powerVo.setFirstDayElectric(list.get(i).getDouble("energy"));
//            } else if (i == 1) {
//                powerVo.setSecondDay(list.get(i).getStr("statDate"));
//                powerVo.setSecondDayElectric(list.get(i).getDouble("energy"));
//            } else {
//                powerVo.setThirdlyDay(list.get(i).getStr("statDate"));
//                powerVo.setThirdlyDayElectric(list.get(i).getDouble("energy"));
//            }
//        }
//        return powerVo;
    }

    public OverviewStaticDataVo overviewStaticData(String entryId) {
        // 获取电站逆变器的sn码
        OverviewStaticDataVo vo = new OverviewStaticDataVo();
        List<String> nbqSnList = collectDataDao.findNbqSnByEntryId(entryId);
        if (nbqSnList == null) {
            return vo;
        }
        Record re = collectDataDao.overviewStaticData(entryId);
        if (re == null) {
            return vo;
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        if (re.getDouble("currentGL") != null) {
            vo.setCurrentGL(df.format(re.getDouble("currentGL")));
        }
        if (re.getDouble("ZjGL") != null) {
            vo.setZjGL(df.format(re.getDouble("ZjGL")));
        }
        if (re.getDouble("currentEtd") != null) {
            vo.setCurrentEtd(df.format(re.getDouble("currentEtd")));
        }
        if (re.getDouble("totalEto") != null) {
            vo.setTotalEto(df.format(re.getDouble("totalEto")));
        }
        // 告警数据
        Record re1 = collectDataDao.stationAlarm(nbqSnList);
        vo.setAlarmDeal(Math.toIntExact(re1.getLong("alarmDeal")));
        vo.setAlarmUnDeal(Math.toIntExact(re1.getLong("alarmUnDeal")));
        // 工单统计
        Record re2 = collectDataDao.getOrderDisposeData(nbqSnList);
        vo.setOrderDeal(Math.toIntExact(re2.getLong("processed")));
        vo.setOrderUnDeal(Math.toIntExact(re2.getLong("total") - re2.getLong("processed")));
        return vo;
    }

    /**
     * 发电趋势曲线图
     */
    public Map<String, Object> powerGenerationTrends(String entryId, String type, String time) {
        logger.info(">>>>>>>>>>>>>>>powerGenerationTrends entryId:{},type:{},time:{}", entryId, type, time);
        List<String> XStr = new ArrayList<>();  //X轴
        List<Object> fdlY = new ArrayList<>();  //发电量的Y轴

        //获取电站逆变器的sn码
        List<String> snList = collectDataDao.findNbqSnByEntryId(entryId);
        int count = 0;
        if (Objects.equals("0", type)) {  //按日统计
            Record re = collectDataDao.overviewHourStatic(time, snList);
            count = 24;
            for (int i = 1; i <= count; i++) {
                String str = i + "";
                if (i < 10) {
                    str = "0" + i;
                }
                if (re != null) {
                    if (re.getDouble("h" + str) != null) {
                        fdlY.add(re.getDouble("h" + str));
                    } else {
                        fdlY.add("0");
                    }
                } else {
                    fdlY.add("0");
                }
                XStr.add(str);
            }
        } else {
            List<Record> list = new ArrayList<>();
            if (Objects.equals("1", type)) {  //按月统计
                list = collectDataDao.overviewMonthStatic(time, snList);
                count = getDaysOfMonth(time);
            } else if (Objects.equals("2", type)) {  //按年统计
                list = collectDataDao.overviewYearStatic(time, snList);
                count = 12;
            }
            Map<String, Record> map = new HashMap<>();
            for (Record res : list) {
                map.put(res.getStr("xAxis"), res);
            }
            for (int i = 1; i <= count; i++) {
                String str = i + "";
                if (i < 10) {
                    str = "0" + i;
                }
                if (map.get(str) != null) {
                    Record res = map.get(str);
                    if (res.getDouble("energy") != null) {
                        fdlY.add(res.getDouble("energy"));
                    } else {
                        fdlY.add("0");
                    }
                } else {
                    fdlY.add("0");
                }
                XStr.add(str);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("XStr", XStr);
        result.put("fdlY", fdlY);
        return result;
    }

    /**
     * 当年发电计划   实际/计划即为完成率
     */
    public Map<String, Object> currentYearGeneration(String entryId, String type) {
        logger.info(">>>>>>>>>>>>>>>currentYearGeneration entryId:{},type:{}", entryId, type);
        // X轴
        List<String> XStr = new ArrayList<>();
        // 实际发电量的Y轴
        List<Object> sjfdlY = new ArrayList<>();

        CustomerEntry entry = entryService.getById(entryId);

        //根据电站地址 ，类型 获取理论发电量
        Integer theory = collectDataDao.getTheoryEfficiency(entry.getSchemeTypeName(), entry.getProvince(), entry.getArea());
        if (theory == null || theory == 0) {
            theory = 1;
        }
        List<Object> jhfdlY = new ArrayList<>();  //计划发电量
        List<Object> ljjhwclY = new ArrayList<>();  //累计计划完成率
        //获取电站逆变器的sn码
        List<String> snList = collectDataDao.findNbqSnByEntryId(entryId);
        String time = "";
        int count = 0;
        //实际发电量
        List<Record> list = new ArrayList<>();
        Date date = new Date();
        if ("year".equals(type)) {  //按年统计
            time = DateUtils.formatDate(date, "yyyy");
            list = collectDataDao.currentYearGeneration(time, snList);
            count = 12;
            theory = theory / 12;
        } else if ("month".equals(type)) { //按月统计
            time = DateUtils.formatDate(date, "yyyy-MM");
            list = collectDataDao.currentMonthGeneration(time, snList);
            count = getDaysOfMonth(time);
            theory = theory / count;
        }
        if (theory == 0) {
            theory = 1;
        }

        Map<String, Record> map = new HashMap<>();
        for (Record res : list) {
            map.put(res.getStr("xAxis"), res);
        }

        for (int i = 1; i <= count; i++) {
            String str = i + "";
            if (i < 10) {
                str = "0" + i;
            }
            if (map.get(str) != null) {
                Record res = map.get(str);
                if (res.getInt("eto") != null) {
                    sjfdlY.add(res.getInt("eto"));
                    ljjhwclY.add(res.getInt("eto") / theory);
                } else {
                    sjfdlY.add("0");
                    ljjhwclY.add("0");
                }

            } else {
                sjfdlY.add("0");
                ljjhwclY.add("0");
            }
            XStr.add(str);

            jhfdlY.add(theory);

        }

        Map<String, Object> result = new HashMap<>();
        result.put("XStr", XStr);
        result.put("sjfdlY", sjfdlY);
        result.put("jhfdlY", jhfdlY);  //计划发电量
        result.put("ljjhwclY", ljjhwclY); //累计计划完成率
        return result;

    }

    public static int getDaysOfMonth(String dateStr) {
        LocalDate date = LocalDate.parse(dateStr + "-01");
        return date.lengthOfMonth();
    }

    public void equipmentInfoList(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> list = collectDataDao.selectEquipmentInfoList(page,map);
        Long count = collectDataDao.countEquipmentInfo(map);
        page.setData(list);
        page.setCount(count);
    }

    public Result findWeatherByCity(String city) {
        // 获取天气信息
        String host = "https://weather01.market.alicloudapi.com";
        String path = "/area-to-weather";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + OSSClientConstants.WEATHER_APP_CODE);
        Map<String, String> querys = new HashMap<>();
        querys.put("area", city);
        querys.put("need3HourForcast", "0");
        querys.put("needAlarm", "0");
        querys.put("needHourData", "0");
        querys.put("needIndex", "0");
        querys.put("needMoreDay", "0");
        try {
            HttpResponse response = HttpUtils.doGet(host, path, headers, querys);
            System.out.println(response.toString());
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("http post,statuscode: {}", statusCode);
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String result = null;
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
                return Result.success(JSONObject.parseObject(result));
            }
        } catch (Exception e) {
            logger.error("查询天气失败=========={}", e.getMessage());
        }
        return Result.fail("获取失败");
    }
}
