using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SolarPower.Models;
using SolarPower.Models.PowerStation;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SolarPower.Controllers
{
    public class DataBackFillController : MyBaseController<DataBackFillController>
    {
        private readonly IPowerStationRepository powerStationRepository;
        private double carbonRate;

        private enum tableType
        {
            hour = 0,
            day = 1,
            month = 2
        }

        public DataBackFillController(IPowerStationRepository powerStationRepository) : base()
        {
            this.powerStationRepository = powerStationRepository;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<ApiResult<string>> BackFillHistory()
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            var dateTimeFormat = "yyyy-MM-dd";

            try
            {
                var targetDay = 1; //預計範圍天數

                //var now = DateTime.Now;
                var now = new DateTime(2021, 7, 26);
                var endDate = now.AddDays(-1);
                var endDateStr = endDate.ToString(dateTimeFormat);
                //var startDate = endDate.AddDays(-1 * targetDay);
                var startDate = now.AddDays(-1 * targetDay);
                var startDateStr = startDate.ToString(dateTimeFormat);

                #region step1. 找出所有電站
                var powerStations = await powerStationRepository.GetAllAsync();
                #endregion

                //電站歷史資料
                List<PowerStationHistory> powerStationHistoriesHour = new List<PowerStationHistory>();
                List<PyrheliometerHistory> pyrheliometerHistoriesHour = new List<PyrheliometerHistory>();
                List<PyrheliometerHistory> TempHistoriesHour = new List<PyrheliometerHistory>();

                List<PowerStationHistoryDay> powerStationHistoryDays = new List<PowerStationHistoryDay>();
                List<PowerStationHistoryMonth> insertPowerStationHistoryMonths = new List<PowerStationHistoryMonth>();
                List<PyrheliometerHistory> pyrheliometerHistoryDays = new List<PyrheliometerHistory>();
                List<PyrheliometerHistory> insertPyrheliometerHistoryMonths = new List<PyrheliometerHistory>();
                List<string> pyrheliometer_history_day_month_properties = new List<string>()
                {
                    "PowerStationId",
                    "Timestamp",
                    "Irradiance",
                    "Temperature"
                };

                //逆變器歷史資料
                List<InverterHistory> inverterHistoriesHour = new List<InverterHistory>();
                List<InverterHistory> inverterHistorDays = new List<InverterHistory>();
                List<InverterHistory> insertInverterHistoryMonths = new List<InverterHistory>();
                List<string> inverter_history_properties = new List<string>()
                {
                    "PowerStationId",
                    "INVERTERID",
                    "TIMESTAMP",
                    "Irradiance",
                    "AC1V",
                    "AC1A",
                    "AC1W",
                    "AC1F",
                    "AC1WH",
                    "AC2V",
                    "AC2A",
                    "AC2W",
                    "AC2F",
                    "AC2WH",
                    "AC3V",
                    "AC3A",
                    "AC3W",
                    "AC3F",
                    "AC3WH",
                    "DC1V",
                    "DC1A",
                    "DC1W",
                    "DC1KW",
                    "DC1WH",
                    "DC2V",
                    "DC2A",
                    "DC2W",
                    "DC2KW",
                    "DC2WH",
                    "DC3V",
                    "DC3A",
                    "DC3W",
                    "DC3KW",
                    "DC3WH",
                    "DC4V",
                    "DC4A",
                    "DC4W",
                    "DC4KW",
                    "DC4WH",
                    "DC5V",
                    "DC5A",
                    "DC5W",
                    "DC5KW",
                    "DC5WH",
                    "PR",
                    "RA1",
                    "RA2",
                    "RA3",
                    "RA4",
                    "RA5",
                    "DCKW",
                    "ACKW",
                    "KWH",
                    "TODAYKWH",
                    "TOTALKWH",
                    "KWHKWP",
                };

                //5分鐘Sensor平均歷史資料
                List<SensorAvgHistory> sensorAvgHistoryHour = new List<SensorAvgHistory>();
                List<SensorAvgHistory> sensorAvgHistoryDays = new List<SensorAvgHistory>();
                List<SensorAvgHistory> insertSensorAvgHistoryMonths = new List<SensorAvgHistory>();

                //#region step2. 每小時歷史資料回填
                //for (var i = 0; i < targetDay; i++)
                //{
                //    var currentDateStr = startDate.AddDays(i).ToString(dateTimeFormat);
                //    var temp_start_time = DateTime.Now;
                //    for (var j = 0; j < 24; j++)
                //    {
                //        var time = string.Format("{0}", j.ToString().PadLeft(2, '0'));

                //        var all_time = string.Format("{0} {1}", currentDateStr, time);

                //        var count = 0;
                //        foreach (var powerStation in powerStations)
                //        {
                //            if (count > 0)
                //            {
                //                break;
                //            }

                //            #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 = await powerStationRepository.ExistTable(powerStation.SiteDB, table_name);

                //            if (!string.IsNullOrEmpty(exist))
                //            {
                //                #region step2-1-1. 電站歷史資料
                //                var history = await powerStationRepository.GetPowerStationHistoryPerHour(all_time, full_table_name);
                //                var lastmoneyhistorybyhour = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 0, all_time);

                //                if (history != null)
                //                {
                //                    history.PowerStationId = powerStation.Id;
                //                    history.Timestamp = Convert.ToDateTime(history.Timestamp + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");

                //                    carbonRate = Convert.ToDouble(await powerStationRepository.GetOneVariableByName("CarbonRate"));

                //                    history.CARBON = history.KWH * carbonRate;
                //                    history.TODAYCARBON = lastmoneyhistorybyhour.TODAYCARBON + history.KWH * carbonRate;
                //                    history.TOTALCARBON = lastmoneyhistorybyhour.TOTALCARBON + history.KWH * carbonRate;
                //                    history.TODAYMONEY = lastmoneyhistorybyhour.TODAYMONEY + history.KWH * powerStation.PowerRate;
                //                    history.TOTALMONEY = lastmoneyhistorybyhour.TOTALMONEY + history.KWH * powerStation.PowerRate;

                //                    powerStationHistoriesHour.Add(history);
                //                }
                //                #endregion

                //                #region step2-1-2. 取得該電站的當前這小時的日照度歷史資料
                //                //step2-1-2 1. 找出該電站所有日照計設備(包含共享
                //                var deviceInfos = await powerStationRepository.GetListPyrheliometerByPowerStationId(powerStation.Id, powerStation.SiteDB);
                //                if (deviceInfos != null)
                //                {
                //                    //step2-1-2 2. 計算該電站所有日照計設的每小時的平均在依照日照計數量平均
                //                    var pyrheliometerHistory = await powerStationRepository.GetPyrheliometerHistoryPerHour(all_time, deviceInfos, 0);

                //                    if (pyrheliometerHistory != null)
                //                    {
                //                        pyrheliometerHistory.Timestamp = Convert.ToDateTime(pyrheliometerHistory.Timestamp + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");
                //                        pyrheliometerHistory.PowerStationId = powerStation.Id;
                //                        pyrheliometerHistoriesHour.Add(pyrheliometerHistory);
                //                    }
                //                }
                //                #endregion

                //                #region step2-1-3. 取得該電站的當前這小時的溫度計歷史資料
                //                //step2-1-3 1. 找出該電站所有溫度計設備(包含共享
                //                var tempdeviceInfos = await powerStationRepository.GetListTempByPowerStationId(powerStation.Id, powerStation.SiteDB);
                //                if (tempdeviceInfos != null)
                //                {
                //                    //step2-1-3 2. 計算該電站所有溫度計設的每小時的平均在依照溫度計數量平均
                //                    var tempHistory = await powerStationRepository.GetPyrheliometerHistoryPerHour(all_time, tempdeviceInfos, 1);
                //                    if (tempHistory != null)
                //                    {
                //                        tempHistory.Timestamp = Convert.ToDateTime(tempHistory.Timestamp + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");
                //                        tempHistory.PowerStationId = powerStation.Id;
                //                        TempHistoriesHour.Add(tempHistory);
                //                    }
                //                }
                //                #endregion
                //            }
                //            #endregion

                //            #region step2-2. 逆變器歷史資料彙整(每小時)
                //            var controllers = await powerStationRepository.GetAllDeviceControllerId(powerStation.Id, powerStation.SiteDB);
                //            var inverters = await powerStationRepository.InverterTable(controllers, powerStation.SiteDB);
                //            var inverterIds = inverters.Where(x => x.Enabled == 1 && x.Status != 0).Select(x => x.InverterId).ToList();

                //            var inverter_table_name = String.Format("s{0}01_inv", powerStation.Code);
                //            var full_inverter_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, inverter_table_name);
                //            var exist_inverter_table = await powerStationRepository.ExistTable(powerStation.SiteDB, inverter_table_name);

                //            if (!string.IsNullOrEmpty(exist_inverter_table))
                //            {
                //                inverterHistoriesHour = await powerStationRepository.CalcInverterHisyortHourData(all_time, powerStation.SiteDB, full_inverter_table_name, inverterIds);
                //                //取得日照計要找的欄位資訊
                //                var pyrheliometer = await powerStationRepository.GetFirstPyrheliometerInfo(powerStation.Id, powerStation.SiteDB);
                //                var pyrheliometerValue = await powerStationRepository.GetFirstPyrheliometerValue(all_time, pyrheliometer.DBName, pyrheliometer.TableName, pyrheliometer.ColName);
                //                foreach (var inverterHistory in inverterHistoriesHour)
                //                {
                //                    inverterHistory.Irradiance = pyrheliometerValue;
                //                    inverterHistory.DC1KW = inverterHistory.DC1W / 1000;
                //                    inverterHistory.DC2KW = inverterHistory.DC2W / 1000;
                //                    inverterHistory.DC3KW = inverterHistory.DC3W / 1000;
                //                    inverterHistory.DC4KW = inverterHistory.DC4W / 1000;
                //                    inverterHistory.DC5KW = inverterHistory.DC5W / 1000;

                //                    inverterHistory.DCKW = (inverterHistory.DC1W + inverterHistory.DC2W + inverterHistory.DC3W + inverterHistory.DC4W + inverterHistory.DC5W) / 1000;
                //                    inverterHistory.ACKW = (inverterHistory.AC1W + inverterHistory.AC2W + inverterHistory.AC3W) / 1000;

                //                    inverterHistory.TIMESTAMP = Convert.ToDateTime(inverterHistory.TIMESTAMP + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");
                //                    inverterHistory.PowerStationId = powerStation.Id;
                //                }
                //            }
                //            #endregion

                //            #region step2-3. 計算該電站所有sensoravg
                //            var seneoravg_table_name = String.Format("s{0}01_sensoravg", powerStation.Code);
                //            var full_seneoravg_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, seneoravg_table_name);
                //            var exist_seneoravg_table = await powerStationRepository.ExistTable(powerStation.SiteDB, seneoravg_table_name);
                //            if (!string.IsNullOrEmpty(exist_seneoravg_table))
                //            {
                //                var sensorAvgHistory = await powerStationRepository.CalcSensorAvgHistory(all_time, full_seneoravg_table_name);

                //                if (sensorAvgHistory != null)
                //                {
                //                    sensorAvgHistory.PowerStationId = powerStation.Id;
                //                    sensorAvgHistory.TIMESTAMP = Convert.ToDateTime(sensorAvgHistory.TIMESTAMP + ":00:00").ToString("yyyy-MM-dd HH:mm:ss");

                //                    sensorAvgHistoryHour.Add(sensorAvgHistory);
                //                }
                //            }
                //            #endregion
                //            count++;
                //        }
                //    }
                //    var temp_end_time = DateTime.Now;

                //    var runtime = temp_end_time.Subtract(temp_start_time).TotalSeconds;
                //    Logger.LogInformation("單一天執行小時回填運行時間{0}", runtime.ToString());
                //}

                //#region 刪除後新增該時間區間的電站歷史紀錄(小時資料表)
                //List<string> history_properties = new List<string>()
                //{
                //    "PowerStationId",
                //    "TIMESTAMP",
                //    "SITEID",
                //    "SITETYPE",
                //    "KWH",
                //    "TODAYKWH",
                //    "TOTALKWH",
                //    "KWHKWP",
                //    "PR",
                //    "MP",
                //    "SolarHour",
                //    "MONEY",
                //    "CARBON",
                //    "TODAYMONEY",
                //    "TOTALMONEY",
                //    "TODAYCARBON",
                //    "TOTALCARBON"
                //};
                //await powerStationRepository.AddAfterPurgePowerStationHistoryHour(startDateStr, endDateStr, powerStationHistoriesHour, history_properties);
                //#endregion

                //#region 刪除後新增該時間區間的日照溫度歷史紀錄(小時資料表)
                //List<string> pyrheliometer_history_properties = new List<string>()
                //{
                //    "PowerStationId",
                //    "TIMESTAMP",
                //    "Irradiance"
                //};
                //await powerStationRepository.AddAfterPurgePyrheliometerHistory(startDateStr, endDateStr, (byte)tableType.hour, pyrheliometerHistoriesHour, pyrheliometer_history_properties);

                //List<string> Temp_history_properties = new List<string>()
                //{
                //    "PowerStationId",
                //    "TIMESTAMP",
                //    "Temperature"
                //};
                //await powerStationRepository.AddTempHistory(TempHistoriesHour, Temp_history_properties);
                //#endregion

                //#region 刪除後新增該時間區間的逆變器歷史紀錄(小時資料表)

                //await powerStationRepository.AddAfterPurgeInverterHistory(startDateStr, endDateStr, (byte)tableType.hour, inverterHistoriesHour, inverter_history_properties);
                //#endregion

                //#region 刪除後新增該時間區間的SensorAvg歷史紀錄(小時資料表)
                //List<string> sensoravg_history_properties = new List<string>()
                //{
                //    "PowerStationId",
                //    "TIMESTAMP",
                //    "SENSORAVG01",
                //    "SENSORAVG02",
                //    "SENSORAVG03",
                //    "SENSORAVG04",
                //    "SENSORAVG05",
                //    "SENSORAVG06",
                //    "SENSORAVG07",
                //    "SENSORAVG08",
                //    "SENSORAVG09",
                //    "SENSORAVG10",
                //    "SENSORAVG11",
                //    "SENSORAVG12",
                //    "SENSORAVG13",
                //    "SENSORAVG14",
                //    "SENSORAVG15",
                //    "SENSORAVG16",
                //    "SENSORAVG17",
                //    "SENSORAVG18",
                //    "SENSORAVG19",
                //    "SENSORAVG20",
                //    "SENSORAVG21",
                //    "SENSORAVG22",
                //    "SENSORAVG23",
                //    "SENSORAVG24",
                //    "SENSORAVG25",
                //    "SENSORAVG26",
                //    "SENSORAVG27",
                //    "SENSORAVG28",
                //    "SENSORAVG29",
                //    "SENSORAVG30",
                //    "SENSORAVG31",
                //    "SENSORAVG32",
                //    "SENSORAVG33",
                //    "SENSORAVG34",
                //    "SENSORAVG35",
                //    "SENSORAVG36",
                //    "SENSORAVG37",
                //    "SENSORAVG38",
                //    "SENSORAVG39",
                //    "SENSORAVG40",
                //    "SENSORAVG41",
                //    "SENSORAVG42",
                //    "SENSORAVG43",
                //    "SENSORAVG44",
                //    "SENSORAVG45",
                //    "SENSORAVG46",
                //    "SENSORAVG47",
                //    "SENSORAVG48",
                //    "SENSORAVG49",
                //    "SENSORAVG50",
                //};
                //await powerStationRepository.AddAfterPurgeSensorAvgHistory(startDateStr, endDateStr, (byte)tableType.hour, sensorAvgHistoryHour, sensoravg_history_properties);
                //#endregion

                //#endregion

                //#region step3. 每天歷史資料回填
                //for (var i = 0; i < targetDay; i++)
                //{
                //    var currentDateStr = startDate.AddDays(i).ToString(dateTimeFormat);
                //    var temp_start_time = DateTime.Now;

                //    var count = 0;
                //    foreach (var powerStation in powerStations)
                //    {
                //        if (count > 0)
                //        {
                //            break;
                //        }

                //        #region step3-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 = await powerStationRepository.ExistTable(powerStation.SiteDB, table_name);
                //        if (!string.IsNullOrEmpty(exist))
                //        {
                //            var historyDay = await powerStationRepository.GetLastOnePowerStationHistoryByDay(currentDateStr, full_table_name);
                //            var moneyandcarbon = await powerStationRepository.GetMoneyAndCarbonWithHistoryHour(powerStation.Id, currentDateStr, 1);
                //            var lastmoneyhistory = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 1, "");
                //            if (historyDay != null)
                //            {
                //                historyDay.PowerStationId = powerStation.Id;
                //                historyDay.CARBON = moneyandcarbon.CARBON;
                //                historyDay.MONEY = moneyandcarbon.MONEY;
                //                //historyDay.TODAYCARBON = lastmoneyhistory.TODAYCARBON;
                //                //historyDay.TODAYMONEY = lastmoneyhistory.TODAYMONEY ;
                //                historyDay.TOTALCARBON = lastmoneyhistory.TOTALCARBON + moneyandcarbon.CARBON;
                //                historyDay.TOTALMONEY = lastmoneyhistory.TOTALMONEY + moneyandcarbon.MONEY;

                //                //日期轉換
                //                historyDay.Timestamp = Convert.ToDateTime(historyDay.Timestamp + ":00:00").ToString("yyyy-MM-dd");
                //                powerStationHistoryDays.Add(historyDay);
                //            }
                //        }
                //        #endregion

                //        #region step3-2. 電站日照計溫度歷史資料彙整(每天)
                //        var pyrheliometerHistorDay = await powerStationRepository.CalcPyrheliometerHistoryDayDataByPowerStationId(currentDateStr, powerStation.Id);
                //        if (pyrheliometerHistorDay != null)
                //        {
                //            pyrheliometerHistoryDays.Add(pyrheliometerHistorDay);
                //        }
                //        #endregion

                //        #region step3-3. 逆變器歷史資料彙整(每天)
                //        var inverterHistoriesDay = await powerStationRepository.CalcInverterHistoryDayDataByPowerStationId(currentDateStr, powerStation.SiteDB, powerStation.Id);
                //        if (inverterHistoriesDay != null)
                //        {
                //            foreach (var inverterHistoryDay in inverterHistoriesDay)
                //            {
                //                inverterHistoryDay.DC1KW = inverterHistoryDay.DC1W / 1000;
                //                inverterHistoryDay.DC2KW = inverterHistoryDay.DC2W / 1000;
                //                inverterHistoryDay.DC3KW = inverterHistoryDay.DC3W / 1000;
                //                inverterHistoryDay.DC4KW = inverterHistoryDay.DC4W / 1000;
                //                inverterHistoryDay.DC5KW = inverterHistoryDay.DC5W / 1000;

                //                inverterHistoryDay.DCKW = (inverterHistoryDay.DC1W + inverterHistoryDay.DC2W + inverterHistoryDay.DC3W + inverterHistoryDay.DC4W + inverterHistoryDay.DC5W) / 1000;
                //                inverterHistoryDay.ACKW = (inverterHistoryDay.AC1W + inverterHistoryDay.AC2W + inverterHistoryDay.AC3W) / 1000;

                //                inverterHistorDays.Add(inverterHistoryDay);
                //            }
                //        }
                //        #endregion

                //        #region step3-4. 計算該電站所有sensoravg(每天)
                //        var sensorAvgHistoryDay = await powerStationRepository.CalcSensorAvgDayDataByPowerStationId(currentDateStr, powerStation.Id);
                //        if (sensorAvgHistoryDay != null)
                //        {
                //            sensorAvgHistoryDays.Add(sensorAvgHistoryDay);
                //        }
                //        #endregion
                //        count++;
                //    }

                //    var temp_end_time = DateTime.Now;

                //    var runtime = temp_end_time.Subtract(temp_start_time).TotalSeconds;
                //    Logger.LogInformation("單一天執行天回填運行時間{0}", runtime.ToString());
                //}

                //#region 刪除後新增該時間區間的電站歷史紀錄(天資料表)
                //List<string> history_properties_day = new List<string>()
                //{
                //    "PowerStationId",
                //    "TIMESTAMP",
                //    "SITEID",
                //    "SITETYPE",
                //    "TODAYKWH",
                //    "TOTALKWH",
                //    "KWHKWP",
                //    "PR",
                //    "MP",
                //    "SolarHour",
                //    "MONEY",
                //    "CARBON",
                //    "TOTALMONEY",
                //    "TOTALCARBON"
                //};
                //await powerStationRepository.AddAfterPurgePowerStationHistoryDay(startDateStr, endDateStr, powerStationHistoryDays, history_properties_day);
                //#endregion

                //#region 刪除後新增該時間區間的日照溫度歷史紀錄(天資料表)
                //await powerStationRepository.AddAfterPurgePyrheliometerHistory(startDateStr, endDateStr, (byte)tableType.day, pyrheliometerHistoryDays, pyrheliometer_history_day_month_properties);
                //#endregion

                //#region 刪除後新增該時間區間的逆變器歷史紀錄(天資料表)
                //await powerStationRepository.AddAfterPurgeInverterHistory(startDateStr, endDateStr, (byte)tableType.day, inverterHistorDays, inverter_history_properties);
                //#endregion

                //#region 刪除後新增該時間區間的SensorAvg歷史紀錄(天資料表)
                //await powerStationRepository.AddAfterPurgeSensorAvgHistory(startDateStr, endDateStr, (byte)tableType.day, sensorAvgHistoryDays, sensoravg_history_properties);
                //#endregion

                //#endregion

                //#region step4. 每月歷史資料回填
                //var tempMonth = "";
                //for (var i = 0; i < targetDay; i++)
                //{
                //    var currentDateStr = startDate.AddDays(i).ToString("yyyy-MM");
                //    if (string.Compare(tempMonth, currentDateStr) == 0)
                //    {
                //        continue;
                //    }
                //    tempMonth = currentDateStr;

                //    foreach (var powerStation in powerStations)
                //    {
                //        #region step4-1. 電站歷史資料彙整(每月)
                //        var historyMonth = await powerStationRepository.ClacPowerStationHistoryMonthDataByPowerStationId(powerStation.Id, currentDateStr);
                //        var moneyandcarbonMon = await powerStationRepository.GetMoneyAndCarbonWithHistoryHour(powerStation.Id, currentDateStr, 0);
                //        var lastmoneyhistorymonth = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 2, "");
                //        if (historyMonth != null)
                //        {
                //            historyMonth.Timestamp = Convert.ToDateTime(historyMonth.Timestamp).ToString("yyyy-MM-dd");
                //            historyMonth.MONEY = moneyandcarbonMon.MONEY;
                //            historyMonth.CARBON = moneyandcarbonMon.CARBON;
                //            historyMonth.TOTALCARBON = lastmoneyhistorymonth.TOTALCARBON + moneyandcarbonMon.CARBON;
                //            historyMonth.TOTALMONEY = lastmoneyhistorymonth.TOTALMONEY + moneyandcarbonMon.MONEY;

                //            insertPowerStationHistoryMonths.Add(historyMonth);
                //        }
                //        #endregion

                //        #region step4-2. 電站日照計溫度歷史資料彙整(每月)
                //        var pyrheliometerHistoryMonth = await powerStationRepository.CalcPyrheliometerHistoryMonthDataByPowerStationId(currentDateStr, powerStation.Id);
                //        if (pyrheliometerHistoryMonth != null)
                //        {
                //            pyrheliometerHistoryMonth.Timestamp = Convert.ToDateTime(pyrheliometerHistoryMonth.Timestamp).ToString("yyyy-MM-dd");
                //            insertPyrheliometerHistoryMonths.Add(pyrheliometerHistoryMonth);
                //        }
                //        #endregion

                //        #region step4-3. 逆變器歷史資料彙整(每月)
                //        var inverterHistoriesMonth = await powerStationRepository.CalcInverterHistoryMonthDataByPowerStationId(currentDateStr, powerStation.SiteDB, powerStation.Id);
                //        if (inverterHistoriesMonth.Count > 0)
                //        {
                //            foreach (var inverterHistoryMonth in inverterHistoriesMonth)
                //            {
                //                inverterHistoryMonth.DC1KW = inverterHistoryMonth.DC1W / 1000;
                //                inverterHistoryMonth.DC2KW = inverterHistoryMonth.DC2W / 1000;
                //                inverterHistoryMonth.DC3KW = inverterHistoryMonth.DC3W / 1000;
                //                inverterHistoryMonth.DC4KW = inverterHistoryMonth.DC4W / 1000;
                //                inverterHistoryMonth.DC5KW = inverterHistoryMonth.DC5W / 1000;

                //                inverterHistoryMonth.DCKW = (inverterHistoryMonth.DC1W + inverterHistoryMonth.DC2W + inverterHistoryMonth.DC3W + inverterHistoryMonth.DC4W + inverterHistoryMonth.DC5W) / 1000;
                //                inverterHistoryMonth.ACKW = (inverterHistoryMonth.AC1W + inverterHistoryMonth.AC2W + inverterHistoryMonth.AC3W) / 1000;

                //                inverterHistoryMonth.TIMESTAMP = Convert.ToDateTime(inverterHistoryMonth.TIMESTAMP).ToString("yyyy-MM-dd");
                //                insertInverterHistoryMonths.Add(inverterHistoryMonth);
                //            }
                //        }
                //        #endregion

                //        #region step4-4. 計算該電站所有sensoravg(每月)
                //        var sensorAvgHistoryMonth = await powerStationRepository.CalcSensorAvgHistoryMonthDataByPowerStationId(currentDateStr, powerStation.Id);
                //        if (sensorAvgHistoryMonth != null)
                //        {
                //            sensorAvgHistoryMonth.TIMESTAMP = Convert.ToDateTime(sensorAvgHistoryMonth.TIMESTAMP).ToString("yyyy-MM-dd");
                //            insertSensorAvgHistoryMonths.Add(sensorAvgHistoryMonth);
                //        }
                //        #endregion
                //    }
                //}

                //#region 刪除後新增該時間區間的電站歷史紀錄(月資料表)
                //List<string> history_properties_month = new List<string>()
                //{
                //    "PowerStationId",
                //    "TIMESTAMP",
                //    "SITEID",
                //    "SITETYPE",
                //    "MonthKWh",
                //    "TOTALKWH",
                //    "KWHKWP",
                //    "PR",
                //    "MP",
                //    "SolarHour",
                //    "MONEY",
                //    "CARBON",
                //    "TOTALMONEY",
                //    "TOTALCARBON"
                //};
                //await powerStationRepository.AddAfterPurgePowerStationHistoryMonth(startDateStr, endDateStr, insertPowerStationHistoryMonths, history_properties_month);
                //#endregion

                //#region 刪除後新增該時間區間的日照溫度歷史紀錄(月資料表)
                //await powerStationRepository.AddAfterPurgePyrheliometerHistory(startDateStr, endDateStr, (byte)tableType.month, insertPyrheliometerHistoryMonths, pyrheliometer_history_day_month_properties);
                //#endregion

                //#region 刪除後新增該時間區間的逆變器歷史紀錄(月資料表)
                //await powerStationRepository.AddAfterPurgeInverterHistory(startDateStr, endDateStr, (byte)tableType.month, insertInverterHistoryMonths, inverter_history_properties);
                //#endregion

                //#region 刪除後新增該時間區間的SensorAvg歷史紀錄(月資料表)
                //await powerStationRepository.AddAfterPurgeSensorAvgHistory(startDateStr, endDateStr, (byte)tableType.month, insertSensorAvgHistoryMonths, sensoravg_history_properties);
                //#endregion

                //#endregion

                //#region step5. 每15分鐘逆變器歷史資料回填

                //var calcInverter15mins = new List<InverterHistory>();
                //for (var i = 0; i < targetDay; i++)
                //{
                //    var currentDateStr = startDate.AddDays(i).ToString("yyyy-MM-dd");

                //    var temp_start_time = DateTime.Now;

                //    for (var j = 0; j < 24; j++)
                //    {
                //        var time = string.Format("{0}", j.ToString().PadLeft(2, '0'));
                //        var min_interval = new List<string>() { "02", "17", "32", "47" };

                //        for (var k = 0; k < min_interval.Count(); k++)
                //        {
                //            if(i == 0 && j == 0 && k== 0)
                //            {   //第一迴圈是跑開始日期的昨天最後一筆，故不執行
                //                continue;
                //            }

                //            var all_time = string.Format("{0} {1}:{2}", currentDateStr, time, min_interval[k]);
                //            var count = 0;
                //            foreach (var powerStation in powerStations)
                //            {
                //                if (count > 0)
                //                {
                //                    break;
                //                }

                //                var controllers = await powerStationRepository.GetAllDeviceControllerId(powerStation.Id, powerStation.SiteDB);
                //                var inverters = await powerStationRepository.InverterTable(controllers, powerStation.SiteDB);
                //                var inverterIds = inverters.Where(x => x.Enabled == 1 && x.Status != 0).Select(x => x.InverterId).ToList();

                //                var table_name = String.Format("s{1}01_inv", powerStation.SiteDB, powerStation.Code);
                //                var full_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, table_name);
                //                var exist = await powerStationRepository.ExistTable(powerStation.SiteDB, table_name);

                //                if (!string.IsNullOrEmpty(exist))
                //                {
                //                    var calcInverter15min = await powerStationRepository.CalcInverterHisyort15minData(all_time, powerStation.SiteDB, full_table_name, inverterIds);
                //                    if (calcInverter15min.Count() > 0)
                //                    {
                //                        foreach (var inverterHistory in calcInverter15min)
                //                        {
                //                            inverterHistory.TIMESTAMP = Convert.ToDateTime(inverterHistory.TIMESTAMP + ":00").ToString("yyyy-MM-dd HH:mm:ss");
                //                            inverterHistory.PowerStationId = powerStation.Id;

                //                            calcInverter15mins.Add(inverterHistory);
                //                        }
                //                    }
                //                }

                //                count++;
                //            }
                //        }
                //    }

                //    var temp_end_time = DateTime.Now;

                //    var runtime = temp_end_time.Subtract(temp_start_time).TotalSeconds;
                //    Logger.LogInformation("單一天執行15回填運行時間{0}", runtime.ToString());
                //}

                ////需再針對最後一天的最後一個時段補上資料
                //var last_all_time = string.Format("{0} {1}", endDate.AddDays(1).ToString(dateTimeFormat), "00:02");
                //foreach (var powerStation in powerStations)
                //{
                //    var controllers = await powerStationRepository.GetAllDeviceControllerId(powerStation.Id, powerStation.SiteDB);
                //    var inverters = await powerStationRepository.InverterTable(controllers, powerStation.SiteDB);
                //    var inverterIds = inverters.Where(x => x.Enabled == 1 && x.Status != 0).Select(x => x.InverterId).ToList();

                //    var table_name = String.Format("s{1}01_inv", powerStation.SiteDB, powerStation.Code);
                //    var full_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, table_name);
                //    var exist = await powerStationRepository.ExistTable(powerStation.SiteDB, table_name);

                //    if (!string.IsNullOrEmpty(exist))
                //    {
                //        var calcInverter15min = await powerStationRepository.CalcInverterHisyort15minData(last_all_time, powerStation.SiteDB, full_table_name, inverterIds);
                //        if (calcInverter15min.Count() > 0)
                //        {
                //            foreach (var inverterHistory in calcInverter15min)
                //            {
                //                inverterHistory.TIMESTAMP = Convert.ToDateTime(inverterHistory.TIMESTAMP + ":00").ToString("yyyy-MM-dd HH:mm:ss");
                //                inverterHistory.PowerStationId = powerStation.Id;

                //                calcInverter15mins.Add(inverterHistory);
                //            }
                //        }
                //    }
                //}

                //List<string> inverter_history_15min_properties = new List<string>()
                //        {
                //            "PowerStationId",
                //            "INVERTERID",
                //            "TIMESTAMP",
                //            "KWH",
                //            "TODAYKWH",
                //            "KWHKWP",
                //        };

                //await powerStationRepository.AddAfterPurgeInverterHistory15min(startDateStr, endDateStr, calcInverter15mins, inverter_history_15min_properties);
                //#endregion

                var calcInverter15mins = new List<InverterHistory>();
                //抓出inverter row data
                for (var i = 0; i < targetDay; i++)
                {
                    var currentDateStr = startDate.AddDays(i).ToString("yyyy-MM-dd");

                    var count = 0;
                    foreach (var powerStation in powerStations)
                    {
                        if (count > 0)
                        {
                            break;
                        }

                        var controllers = await powerStationRepository.GetAllDeviceControllerId(powerStation.Id, powerStation.SiteDB);
                        var inverters = await powerStationRepository.InverterTable(controllers, powerStation.SiteDB);
                        var inverterIds = inverters.Where(x => x.Enabled == 1 && x.Status != 0).Select(x => x.InverterId).ToList();

                        var table_name = String.Format("s{1}01_inv", powerStation.SiteDB, powerStation.Code);
                        var full_table_name = String.Format("`{0}`.`{1}`", powerStation.SiteDB, table_name);
                        var exist = await powerStationRepository.ExistTable(powerStation.SiteDB, table_name);

                        if (!string.IsNullOrEmpty(exist))
                        {
                            var inverter_row_data = await powerStationRepository.GetAllInverterRowData(currentDateStr, full_table_name);
                        }
                    }
                }

                apiResult.Code = "0000";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            apiResult.Msg = errorCode.GetString(apiResult.Code);
            return apiResult;
        }
    }
}
