using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using solarApp.Model;
using static solarApp.Model.weather_model;

namespace solarApp.Service
{ 
    public class procArchiveHourly
    {
        // private readonly ILogger logger;
        private readonly ILogger logger;
        private double carbonRate;
        //public procArchiveHourly(ILogger<procArchiveHourly> logger)
        //{
        //    this.logger = logger;
        //}
        public List<PowerStation> proc_s1_site() {
            List<PowerStation> calcPowerStations = new List<PowerStation>();
            try
            {
                var DateTimeNow = DateTime.Now;
                var dateTime = DateTimeNow.AddHours(-1).ToString("yyyy-MM-dd HH");

                Root2 observation = null;

                //if (this.environment.IsDevelopment())
                //{
                //    dateTime = "2022-06-01 16";
                //}

                // logger.LogInformation("【CalcPowerStationJob】【任務開始】");

                #region step1. 找出所有電站
                // logger.LogInformation("【CalcPowerStationJob】【開始取得電站資料】");
                //var powerStations =  powerStationRepository.GetAllAsync();
                getStationSvc stationSvc = new getStationSvc();
                var powerStations = stationSvc.get_powerStation();
                // logger.LogInformation("【CalcPowerStationJob】【取得成功電站資料】");
                // logger.LogInformation("【CalcPowerStationJob】【電站資料】 - {0}", System.Text.Json.JsonSerializer.Serialize(powerStations));
                #endregion

                List<PowerStationHistory> powerStationHistoriesHour = new List<PowerStationHistory>();
                //List<PyrheliometerHistory> sensorHistoriesHour = new List<PyrheliometerHistory>();

                //List<PyrheliometerHistory> pyrheliometerHistoriesHour = new List<PyrheliometerHistory>();
                //List<PyrheliometerHistory> TempHistoriesHour = new List<PyrheliometerHistory>();
                //List<InverterHistory> inverterHistoriesHour = new List<InverterHistory>();
                
                List<SensorAvgHistory> sensorAvgHistoryHour = new List<SensorAvgHistory>();
                //List<MeterHistory> meterHistoriesHour = new List<MeterHistory>();
                List<WeatherObservation> weatherObservations = new List<WeatherObservation>();

                #region 氣象觀測(取資料)
                try
                {
                    // logger.LogInformation("【CalcPowerStationJob】【開始取得氣象觀測】");
                    var client = new HttpClient();
                    var UVUri = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0003-001?Authorization=CWB-EA24220B-DDCC-4188-84E5-AD37A0E03F80&elementName=TIME,TEMP";
                    HttpResponseMessage response = client.GetAsync(UVUri).Result;
                    String jsonUVs = response.Content.ReadAsStringAsync().Result.ToString();
                    observation = JsonConvert.DeserializeObject<Root2>(jsonUVs);
                    // logger.LogInformation("【CalcPowerStationJob】【取得成功氣象觀測】");
                }
                catch (Exception ex)
                {
                    // logger.LogError("【CalcPowerStationJob】【取得失敗氣象觀測】");
                    // logger.LogError("【{0}】{1}", "CalcPowerStationJob", ex.Message);
                    observation = null;
                }
                #endregion

                #region step2. 從電站的DB及電站編號找出該電站的控制器
                foreach (var powerStation in powerStations)
                {
                    try
                    {
                        var calcPowerStation = new PowerStation();
                        calcPowerStation.Id = powerStation.Id;
                        string calcPowerStationTime = "";

                        #region step2-1. 取得該電站的當前這小時的歷史資料
                        var table_name = String.Format("s{1}01_station", powerStation.SiteDB, powerStation.Code);
                        var full_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, table_name);
                        var exist = stationSvc.ExistTable(powerStation.SiteDB, table_name);

                        if (string.IsNullOrEmpty(exist))
                        {
                            // logger.LogError($"【CalcPowerStationJob】【查無電站[{powerStation.Code}]的s{powerStation.Code}01_station資料表】");
                        }
                        else
                        {
                            //// logger.LogInformation("【CalcPowerStationJob】【開始取得電站[{0}]在{1}的每小時歷史資料】", powerStation.Code, dateTime);
                            //var history = stationSvc.GetPowerStationHistoryPerHour(dateTime, full_table_name);
                            //// 當前用不到
                            //// var lastmoneyhistorybyhour = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 0, dateTime);

                            //if (history == null)
                            //{
                            //    // logger.LogWarning("【CalcPowerStationJob】【查無電站[{0}]在{1}的每小時歷史資料】", powerStation.Code, dateTime);
                            //}
                            //else
                            //{
                            //    // logger.LogInformation("【CalcPowerStationJob】【取得成功電站[{0}]在{1}的每小時歷史資料】", powerStation.Code, dateTime);
                            //    // logger.LogInformation("【CalcPowerStationJob】【電站[{0}]在{1}的每小時歷史資料】 - {2}", powerStation.Code, dateTime, System.Text.Json.JsonSerializer.Serialize(history));

                            //    // logger.LogInformation("【CalcPowerStationJob】【開始計算電站[{0}]在{1}的每小時歷史資料】", powerStation.Code, dateTime);
                            //    history.PowerStationId = powerStation.Id;
                            //    history.Timestamp = Convert.ToDateTime(history.Timestamp + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");

                            //    #region 計算單一電站每小時發電量、發電金額等資料

                            //    #region 發電量
                            //    //每小時發電量(直接填寫
                            //    calcPowerStation.kwh = history.KWH;
                            //    //今日發電量(直接填寫
                            //    calcPowerStation.Today_kWh = history.TodayKWh;
                            //    //總發電量(直接填寫
                            //    calcPowerStation.Total_kWh = history.TotalKWH;
                            //    #endregion

                            //    #region 發電金額

                            //    history.MONEY = history.KWH * powerStation.PowerRate;
                            //    history.TODAYMONEY = history.TodayKWh * powerStation.PowerRate;
                            //    history.TOTALMONEY = history.TotalKWH * powerStation.PowerRate;

                            //    //即時發電金額
                            //    switch (powerStation.SolarType)
                            //    {
                            //        case (int)SolarTypeEnum.SelfSold: //自建躉售  

                            //            //今日發電金額 計算方式：todaykWh * 授電費率
                            //            calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate;
                            //            //calcPowerStation.Today_Money = history.TODAYMONEY;

                            //            ////總發電金額 計算方式：totalkWh * 授電費率
                            //            calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate;
                            //            //calcPowerStation.Total_Money = history.TOTALMONEY;
                            //            break;
                            //        case (int)SolarTypeEnum.HireSold: //租建躉售 
                            //                                          //找出該電站的所有土地房屋資訊
                            //            var landBuildings = stationSvc.GetAllLandBuildingInfoByPowerStationId(powerStation.Id, powerStation.SiteDB);
                            //            var sumLeaseRate = 0.00;
                            //            var avgLeaseRate = 0.00;

                            //            foreach (var landBuilding in landBuildings)
                            //            {
                            //                sumLeaseRate += landBuilding.LeaseRate;
                            //            }

                            //            calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate * sumLeaseRate / 100;
                            //            calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate * sumLeaseRate / 100;

                            //            break;
                            //        case (int)SolarTypeEnum.SelfUse: //自建自用 


                            //            //今日發電金額 計算方式：todaykWh * 授電費率
                            //            //calcPowerStation.Today_Money = history.TODAYMONEY;
                            //            calcPowerStation.Today_Money = history.TodayKWh * powerStation.PowerRate;

                            //            //總發電金額 計算方式：totalkWh * 授電費率
                            //            //calcPowerStation.Total_Money = history.TOTALMONEY;
                            //            calcPowerStation.Total_Money = history.TotalKWH * powerStation.PowerRate;
                            //            break;
                            //    }
                            //    #endregion

                            //    #region kWh/kWp
                            //    //直接填寫
                            //    calcPowerStation.Today_kwhkwp = history.KWHKWP;
                            //    #endregion

                            //    #region PR
                            //    //直接填寫
                            //    calcPowerStation.Today_PR = history.PR;
                            //    #endregion

                            //    #region 減碳量
                            //    carbonRate = Convert.ToDouble(stationSvc.GetOneVariableByName("CarbonRate"));

                            //    history.CARBON = history.KWH * carbonRate;
                            //    history.TODAYCARBON = history.TodayKWh * carbonRate;
                            //    history.TOTALCARBON = history.TotalKWH * carbonRate;


                            //    //今日減碳量( 今日發電量 * (0.554/1000)[抓資料庫值]
                            //    //calcPowerStation.Today_Carbon = history.TODAYCARBON;
                            //    calcPowerStation.Today_Carbon = history.TodayKWh * carbonRate;

                            //    //總減碳量(總發電量 * (0.554/1000)[抓資料庫值]
                            //    //calcPowerStation.Total_Carbon = history.TotalKWH * carbonRate;
                            //    calcPowerStation.Total_Carbon = history.TotalKWH * carbonRate;

                            //    #endregion

                            //    #region 發電時間
                            //    calcPowerStation.SolarHour = history.SolarHour;
                            //    #endregion
                            //    #endregion

                            //    powerStationHistoriesHour.Add(history);

                            //    // logger.LogInformation("【CalcPowerStationJob】【計算完成電站[{0}]在{1}的每小時歷史資料】", powerStation.Code, dateTime);
                            //}

                            #region 計算單一電站每小時發電量、發電金額等資料 for calcPowerStation
                            //logger.LogInformation("【CalcPowerStationJob】【開始取得電站[{0}]在{1}的每小時歷史資料 for calcPowerStation】", powerStation.Code, dateTime);
                            //var dateTimeforPowerStation = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                            var dateTimeforPowerStation = DateTime.Now.ToString("yyyy-MM-dd");
                            var history_for_powerStation = stationSvc.GetPowerStationHistoryPerHourForPowerStation(dateTimeforPowerStation, full_table_name);

                            if (history_for_powerStation == null)
                            {
                                //logger.LogWarning("【CalcPowerStationJob】【查無電站[{0}]在{1}的每小時歷史資料 for calcPowerStation；發電量、發電金額等資料設定為0】", powerStation.Code, dateTime);
                                calcPowerStation.kwh = 0;
                                calcPowerStation.Today_kWh = 0;
                                calcPowerStation.Total_kWh = 0;
                                calcPowerStation.Today_Money = 0;
                                calcPowerStation.Total_Money = 0;
                                calcPowerStation.Today_kwhkwp = 0;
                                calcPowerStation.Today_PR = 0;
                                calcPowerStation.Today_Carbon = 0;
                                calcPowerStation.Total_Carbon = 0;
                                calcPowerStation.SolarHour = 0;
                            }
                            else
                            {
                                //logger.LogInformation("【CalcPowerStationJob】【開始計算電站[{0}]在{1}的每小時歷史資料 for calcPowerStation】", powerStation.Code, dateTime);
                                #region 發電量
                                //每小時發電量(直接填寫
                                calcPowerStation.kwh = history_for_powerStation.KWH;
                                //今日發電量(直接填寫
                                calcPowerStation.Today_kWh = history_for_powerStation.TodayKWh;
                                //總發電量(直接填寫
                                calcPowerStation.Total_kWh = history_for_powerStation.TotalKWH;
                                #endregion

                                #region 發電金額
                                history_for_powerStation.MONEY = history_for_powerStation.KWH * powerStation.PowerRate;
                                history_for_powerStation.TODAYMONEY = history_for_powerStation.TodayKWh * powerStation.PowerRate;
                                history_for_powerStation.TOTALMONEY = history_for_powerStation.TotalKWH * powerStation.PowerRate;

                                //即時發電金額
                                switch (powerStation.SolarType)
                                {
                                    case (int)SolarTypeEnum.SelfSold: //自建躉售 
                                                                      //今日發電金額 計算方式：todaykWh * 授電費率
                                        calcPowerStation.Today_Money = history_for_powerStation.TodayKWh * powerStation.PowerRate;

                                        ////總發電金額 計算方式：totalkWh * 授電費率
                                        calcPowerStation.Total_Money = history_for_powerStation.TotalKWH * powerStation.PowerRate;
                                        break;
                                    case (int)SolarTypeEnum.HireSold: //租建躉售 
                                                                      //找出該電站的所有土地房屋資訊
                                        var landBuildings = stationSvc.GetAllLandBuildingInfoByPowerStationId(powerStation.Id, powerStation.SiteDB);
                                        var sumLeaseRate = 0.00;
                                        var avgLeaseRate = 0.00;

                                        foreach (var landBuilding in landBuildings)
                                        {
                                            sumLeaseRate += landBuilding.LeaseRate;
                                        }

                                        calcPowerStation.Today_Money = history_for_powerStation.TodayKWh * powerStation.PowerRate * sumLeaseRate / 100;
                                        calcPowerStation.Total_Money = history_for_powerStation.TotalKWH * powerStation.PowerRate * sumLeaseRate / 100;

                                        break;
                                    case (int)SolarTypeEnum.SelfUse: //自建自用 

                                        //今日發電金額 計算方式：todaykWh * 授電費率
                                        calcPowerStation.Today_Money = history_for_powerStation.TodayKWh * powerStation.PowerRate;

                                        //總發電金額 計算方式：totalkWh * 授電費率
                                        calcPowerStation.Total_Money = history_for_powerStation.TotalKWH * powerStation.PowerRate;
                                        break;
                                }
                                #endregion

                                #region kWh/kWp
                                ////直接填寫
                                calcPowerStation.Today_kwhkwp = history_for_powerStation.KWHKWP;
                                #endregion

                                #region PR
                                //直接填寫
                                calcPowerStation.Today_PR = history_for_powerStation.PR;
                                #endregion

                                #region 減碳量
                                carbonRate = Convert.ToDouble(stationSvc.GetOneVariableByName("CarbonRate"));
                                history_for_powerStation.CARBON = history_for_powerStation.KWH * carbonRate;
                                history_for_powerStation.TODAYCARBON = history_for_powerStation.TodayKWh * carbonRate;
                                history_for_powerStation.TOTALCARBON = history_for_powerStation.TotalKWH * carbonRate;

                                //今日減碳量( 今日發電量 * (0.554/1000)[抓資料庫值]
                                calcPowerStation.Today_Carbon = history_for_powerStation.TodayKWh * carbonRate;

                                //總減碳量(總發電量 * (0.554/1000)[抓資料庫值]
                                calcPowerStation.Total_Carbon = history_for_powerStation.TotalKWH * carbonRate;
                                #endregion

                                #region 發電時間
                                calcPowerStation.SolarHour = history_for_powerStation.SolarHour;
                                #endregion

                                #region 取拿到資料的時間
                                calcPowerStationTime = history_for_powerStation.Timestamp;
                                #endregion
                            }
                            #endregion
                        }
                        #endregion

                        #region  step2-2. 取得該電站的當前這小時的設備歷史資料
                        var sensoravg_table_name = String.Format("s{1}01_sensoravg", powerStation.SiteDB, powerStation.Code);
                        var full_sensoravg_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, sensoravg_table_name);
                        var sensoravg_table_exist = stationSvc.ExistTable(powerStation.SiteDB, sensoravg_table_name);
                        if (string.IsNullOrEmpty(sensoravg_table_exist))
                        {
                            // logger.LogError($"【CalcPowerStationJob】【查無電站[{powerStation.Code}]的s{powerStation.Code}01_sensoravg資料表】");
                        }
                        else
                        {
                            // logger.LogInformation("【CalcPowerStationJob】【開始計算電站[{0}]在{1}的設備資訊】", powerStation.Code, dateTime);
                            PyrheliometerHistory sensorHistory = new PyrheliometerHistory();
                            sensorHistory.PowerStationId = powerStation.Id;
                            sensorHistory.Timestamp = Convert.ToDateTime(dateTime + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");

                            //1. 計算該電站sensor平均值 - 日照計(PYR)
                            try
                            {
                                // logger.LogInformation("【CalcPowerStationJob】【開始取得電站[{0}]在{1}的日照計設備資訊】", powerStation.Code, dateTime);
                                var deviceInfos =  stationSvc.GetListPyrheliometerByPowerStationId(powerStation.Id, powerStation.SiteDB);
                                // logger.LogInformation("【CalcPowerStationJob】【取得成功電站[{0}]在{1}的日照計設備資訊】", powerStation.Code, dateTime);
                                // logger.LogInformation("【CalcPowerStationJob】【電站[{0}]在{1}的日照計設備資訊】 - {2}", powerStation.Code, dateTime, System.Text.Json.JsonSerializer.Serialize(deviceInfos));

                                if (deviceInfos != null && deviceInfos.Count > 0)
                                {
                                    // logger.LogInformation("【CalcPowerStationJob】【開始計算電站[{0}]在{1}的日照計的平均值】", powerStation.Code, dateTime);
                                    var pyrheliometerHistory = stationSvc.CalcSensorHistoryPerHour(dateTime, deviceInfos, Convert.ToInt32(SensorTypeEnum.PYR));
                                    string dateTimeForCalc;
                                    if (calcPowerStationTime != "")
                                    {
                                        dateTimeForCalc = calcPowerStationTime;
                                    }
                                    else
                                    {
                                        dateTimeForCalc = dateTime;
                                    }
                                    var pyrheliometerHistory_for_calcPowerStation = stationSvc.CalcSensorHistoryPerHour(dateTimeForCalc, deviceInfos, Convert.ToInt32(SensorTypeEnum.PYR));
                                    if (pyrheliometerHistory != null)
                                    {
                                        calcPowerStation.Today_irradiance = pyrheliometerHistory.Irradiance;

                                        sensorHistory.Irradiance = pyrheliometerHistory.Irradiance;

                                        //pyrheliometerHistory.Timestamp = Convert.ToDateTime(pyrheliometerHistory.Timestamp + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");
                                        //pyrheliometerHistory.PowerStationId = powerStation.Id;
                                        //pyrheliometerHistoriesHour.Add(pyrheliometerHistory);
                                        // logger.LogInformation("【CalcPowerStationJob】【計算完成電站[{0}]在{1}的日照計的平均值】", powerStation.Code, dateTime);
                                    }
                                    else
                                    {
                                        // logger.LogWarning("【CalcPowerStationJob】【查無結果電站[{0}]在{1}的日照計的平均值】", powerStation.Code, dateTime);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                                // logger.LogError("【CalcPowerStationJob】【計算失敗電站[{0}]在{1}的日照計的平均值】", powerStation.Code, dateTime);
                                // logger.LogError("【CalcPowerStationJob】【失敗原因】- {0}", ex.Message);
                            }
                        }
                         
                        #endregion
                        
                        //結果存入集合
                        calcPowerStations.Add(calcPowerStation);
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                        // logger.LogError("【{0}】{1}", "CalcPowerStationJob", exception.Message);
                    } 
                }
                #endregion

                //if (!this.environment.IsDevelopment())
                //{

                #region step5. calcPowerStations UPDATE 到 power_station 資料表
                //List<string> power_station_properties = new List<string>()
                //{
                //    "Id",
                //    "kwh",
                //    "Today_kwh",
                //    "Total_kwh",
                //    "today_kwhkwp",
                //    "today_money",
                //    "total_money",
                //    "today_PR",
                //    "today_carbon",
                //    "total_carbon",
                //    "today_irradiance",
                //    "SolarHour",
                //    "WeathersStationId",
                //    "TodayWeatherTemp",
                //    "TodayWeather",
                //    "RateOfRain"
                //};
                List<string> power_station_properties = new List<string>()
                    {
                        "Id",
                        "kwh",
                        "Today_kwh",
                        "Total_kwh",
                        "today_kwhkwp",
                        "today_money",
                        "total_money",
                        "today_PR",
                        "today_carbon",
                        "total_carbon",
                        "today_irradiance",
                        "SolarHour"
                    };
                // logger.LogInformation("【update Power_Station 】【update Power_Station】", dateTime);
                stationSvc.UpdateList(calcPowerStations, power_station_properties);
                #endregion 
                //}

                // logger.LogInformation("【CalcPowerStationJob】【任務完成】");
            }
            catch (Exception exception)
            {
                // logger.LogError("【CalcPowerStationJob】[Exception] - {0}", exception.Message);
                if (exception.InnerException != null)
                {
                    // logger.LogError("【CalcPowerStationJob】[InnerException] - {0}", exception.InnerException.Message);
                }
            }
            return calcPowerStations;
        }

       
    }
}
