using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using Dapper;
using solarApp.Model;
using System.Configuration;

namespace solarApp.Service
{
    public class procStationSvc
    {
        string Connection1 = string.Empty;

        public procStationSvc(string Connection_parame = null)
        {
            if (!string.IsNullOrEmpty(Connection_parame))
            {
                Connection1 = Connection_parame;
            }
            else
            {
                Connection1 = ConfigurationManager.ConnectionStrings["mySql"].ConnectionString;
            }
        }

        public string _siteID { get; set; }
        public string _siteDB { get; set; }
        public string _siteID01 { get; set; }
        public string _date1 { get; set; }
        //public string _date2 { get; set; }
        public string _powerStationID { get; set; }


        public bool clearData()
        {
            bool result = false;
            try
            {
                #region 取得 PowerStationID
                using (MySqlConnection conn = new MySqlConnection(Connection1))
                {
                    conn.Open();
                    string sql = @" select id as PowerStationID from solar_master.power_station where `code` = @siteID";
                    var ds = conn.Query<string>(sql, new { siteID = _siteID }).AsList<string>();
                    _powerStationID = (ds.Count > 0) ? ds[0].ToString() : "0";
                    conn.Close();
                }
                #endregion

                using (MySqlConnection conn = new MySqlConnection(Connection1))
                {
                    conn.Open();
                    string sql = @" 
                        delete from power_station_history_hour where powerstationID = @powerStationID and  DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = @date1;
                        delete from power_station_history_day where powerstationID = @powerStationID and  DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = @date1;
                        delete from power_station_history_month where powerstationID = @powerStationID and  left(`TIMESTAMP`, 7)  =  left(@date1, 7) ;";
                    //var ds = conn.Execute(sql, new { date1 = _date1, powerStationID = _powerStationID });
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandTimeout = 720;
                    cmd.Parameters.AddWithValue("@date1", _date1);
                    cmd.Parameters.AddWithValue("@powerStationID", _powerStationID);
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();

                    conn.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public bool archiveData(string siteID, string date1)
        {

            bool result = false;
            _siteID = siteID;
            _date1 = date1;
            try
            { 
                get_siteInfo();
                clearData();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            try
            { 
                insert_station();
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public bool get_siteInfo()
        {
            bool result = false;
            try
            {
                using (MySqlConnection conn = new MySqlConnection(Connection1))
                {
                    conn.Open();
                    #region 取得 PowerStationID               
                    string sql = @" select id , `code` siteID,  siteDB, `name` siteName 
                                    from solar_master.power_station where `code` = @siteID";
                    var ds = conn.Query<station_list>(sql, new { siteID = _siteID }).AsList<station_list>();
                    foreach (var item in ds)
                    {
                        _powerStationID = item.id;
                        _siteDB = item.SiteDB;
                        _siteID01 = item.SiteID + "01";
                    }
                    #endregion
                    conn.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
        bool insert_station()
        {
            procArchiveLog arclog = new procArchiveLog();
            DateTime dt_start = DateTime.Now;
            bool result = false;
            try
            {
                using (MySqlConnection conn = new MySqlConnection(Connection1))
                {
                    conn.Open();
                    string ss = @"SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY,',''));";
                    conn.Execute(ss);

                    string sql = @" select id as PowerStationID from solar_master.power_station where `code` = @siteID";
                    var ds = conn.Query<string>(sql, new { siteID = _siteID }).AsList<string>();
                    _powerStationID = (ds.Count > 0) ? ds[0].ToString() : "0";

                    #region hour -- solar_type 計費類別：0 自建、1 租建、2自建   ------------ 1 租建計算方式 後再再補上 

                    //select b.id PowerStationId, a.reportdate, b.siteID, a.siteType, a.KWH, a.TODAYKWH, a.TOTALKWH, a.KWHKWP, a.PR, a.MP, a.SOLARHOUR,
                    //     (KWH * PowerRate)   MONEY, (a.TODAYKWH * PowerRate) TODAYMONEY, (a.TOTALKWH * PowerRate) TOTALMONEY, 
                    //     (KWH * CarbonRate) CARBON, (a.TODAYKWH * CarbonRate) TODAYCARBON, round((a.TOTALKWH * CarbonRate), 4) TOTALCARBON
                    //    from
                    //    (
                    //                select siteid, siteType, concat(FROM_UNIXTIME(`TIMESTAMP`/ 1000, '%Y-%m-%d %H'), ':00:00') reportdate,
                    //                      round((sum(KWH)), 4) KWH, round((max(TODAYKWH)), 4) TODAYKWH, round((max(TOTALKWH)), 4) TOTALKWH, round((max(KWHKWP)), 4) KWHKWP,
                    //                      round((max(PR)), 4) PR, 0 as MP, round((max(SOLARHOUR)), 4) SOLARHOUR

                    //                from " + _siteDB + ".s" + _siteID01 + @"_station

                    //                where FROM_UNIXTIME(`TIMESTAMP`/ 1000, '%Y-%m-%d') = @date1

                    //                group by  siteid, FROM_UNIXTIME(`TIMESTAMP`/ 1000, '%Y-%m-%d %H')
                    //    )a join
                    //    (
                    //            select id, `code` siteID, PowerRate, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType
                    //            from solar_master.power_station
                    //            where `code` = @siteID
                    //    ) b on a.siteID = b.siteID

                    sql = @"insert into solar_master.power_station_history_hour(PowerStationId, `TIMESTAMP`, SITEID, SITETYPE, KWH, TODAYKWH, TOTALKWH, KWHKWP, PR, MP, SOLARHOUR, MONEY, TODAYMONEY, TOTALMONEY, CARBON, TODAYCARBON, TOTALCARBON)  

                            select b.id PowerStationId, concat(FROM_UNIXTIME(`TIMESTAMP`/1000, '%Y-%m-%d %H'), ':00:00') reportdate, a.siteid, a.siteType,   
			                            a.KWH, TODAYKWH, TOTALKWH, KWHKWP , PR, MP, a.SOLARHOUR , 
                                        /* CASE 
										    WHEN b.SolarType = 1 THEN a.KWH * PowerRate * c.LeaseRate
										    ELSE a.KWH * PowerRate
										END MONEY,
										CASE 
										    WHEN b.SolarType = 1 THEN a.TODAYKWH * PowerRate * c.LeaseRate
										    ELSE a.TODAYKWH * PowerRate
										END TODAYMONEY,
			                            CASE 
											WHEN b.SolarType = 1 THEN a.TOTALKWH * PowerRate * c.LeaseRate
											ELSE a.TOTALKWH * PowerRate
										END TOTALMONEY,*/
	                                 (a.KWH * PowerRate) MONEY,
                                     (a.TODAYKWH * PowerRate) TODAYMONEY,
                                     (a.TOTALKWH * PowerRate) TOTALMONEY,
	                            (a.KWH * CarbonRate) CARBON, (a.TODAYKWH * CarbonRate) TODAYCARBON, round((a.TOTALKWH * CarbonRate), 3) TOTALCARBON
			                from " + _siteDB + ".s" + _siteID01 + @"_station  a join 
			                    (select id, `code` siteID, PowerRate, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType
				                    from solar_master.power_station where `code` =  @siteID	
		                        ) b on a.siteID = b.siteID
                            LEFT JOIN (
                                SELECT 
                                    SUM(lb.LeaseRate) LeaseRate,
                                    ps.Code siteID FROM " + _siteDB + @".land_building lb 
                                LEFT JOIN solar_master.power_station ps ON lb.PowerStationId = ps.Id
                                WHERE ps.Code = @siteID
                                GROUP BY lb.PowerStationId
                            ) c ON a.siteID = c.siteID
			                where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d') = @date1 and a.SITEID =  @siteID ";
                    //int ct = conn.Execute(sql, new { date1 = _date1, siteID = _siteID });
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandTimeout = 720;
                    cmd.Parameters.AddWithValue("@date1", _date1);
                    cmd.Parameters.AddWithValue("@siteID", _siteID);
                    cmd.CommandText = sql;
                    int rowCT = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    DateTime dt_start2 = DateTime.Now;
                    TimeSpan duration = DateTime.Now - dt_start2;
                    arclog.insert_log(_powerStationID, "station step1", duration.TotalSeconds, "power_station_history_hour", "insert station hour", "0", "", rowCT.ToString(), conn, cmd);

                    #endregion hour

                    //#region 取累計日照量
                    //sql = $@"select a.TableName, a.ColName from solar_com0002.device a  where `type` = 'TPY' and a.Deleted = 0 and a.`status` = 1 ";
                    //#endregion

                    #region day PR = (累計發電量/裝置容量)*1000/累計日照量


                    sql = @" INSERT INTO solar_master.power_station_history_day( PowerStationId, `TIMESTAMP`, SITEID, SITETYPE, TODAYKWH, TOTALKWH, KWHKWP, 
                                    PR, MP, SOLARHOUR, MONEY, TOTALMONEY, CARBON, TOTALCARBON) 

                                    select b.id PowerStationId, a.reportdate, b.siteID, a.siteType, a.TODAYKWH, a.TOTALKWH, a.KWHKWP, 
                                    a1.PR, -- (todayKWH/Capacity)*1000/b.IrrDay as PR, -- PR 計算
                                    a.MP, a.SOLARHOUR,	                               
                                    (a.TODAYKWH * PowerRate) MONEY,
                                    (a.TOTALKWH * PowerRate) TOTALMONEY, 
	                                    (KWH * CarbonRate) CARBON, round((a.TOTALKWH * CarbonRate), 4) TOTALCARBON
                                    from 
                                    (
			                              select concat(DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d'), ' 00:00:00') reportdate, siteid, siteType, round((sum(KWH)), 6) KWH,
			                                     round((max(TODAYKWH)), 6) TODAYKWH, round((max(TOTALKWH)), 6) TOTALKWH, round((max(KWHKWP)), 6) KWHKWP, 
			                                     # round((avg(PR)), 6) PR,  
                                                 round((max(MP)), 6) as MP, round((max(SOLARHOUR)), 6) SOLARHOUR
			                               from solar_master.power_station_history_hour a  
			                               where SITEID = @siteID	 and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d') = @date1
			                               group by  a.siteid, DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d')
                                    )a  join 
                                    (
					                            select id,  SITEID, round(PR, 4) PR
					                            from solar_master.power_station_history_hour a  
			                                    where SITEID = @siteID	 and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d') =  @date1
					                            order by 1 desc limit 1
		                            )a1 on a.siteID = a1.siteID  join 
                                    ( 
		                                select a.id, `code` siteID, PowerRate, GeneratingCapacity Capacity, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType, IrrDay
		                                from solar_master.power_station a join sensor_history_day b on a.id = b.PowerStationID
		                                where `code` =  @siteID and left(`TIMESTAMP`, 10) = @date1
                                    ) b on a.siteID = b.siteID  ";
         //           sql = @" INSERT INTO solar_master.power_station_history_day( PowerStationId, `TIMESTAMP`, SITEID, SITETYPE, TODAYKWH, TOTALKWH, KWHKWP, 
         //                           PR, MP, SOLARHOUR, MONEY, TOTALMONEY, CARBON, TOTALCARBON) 

         //                           select b.id PowerStationId, a.reportdate, b.siteID, a.siteType, a.TODAYKWH, a.TOTALKWH, a.KWHKWP, a1.PR, a.MP, a.SOLARHOUR,
	        //                        /*CASE 
									//	WHEN b.SolarType = 1 THEN a.KWH * PowerRate * c.LeaseRate
									//	ELSE a.KWH * PowerRate
									//END MONEY,
         //                           CASE
									//	WHEN b.SolarType = 1 THEN a.TOTALKWH * PowerRate * c.LeaseRate
									//	ELSE a.TOTALKWH * PowerRate
									//END TOTALMONEY,*/
         //                           (a.TODAYKWH * PowerRate) MONEY,
         //                           (a.TOTALKWH * PowerRate) TOTALMONEY, 
	        //                            (KWH * CarbonRate) CARBON, round((a.TOTALKWH * CarbonRate), 4) TOTALCARBON
         //                           from 
         //                           (
			      //                        select concat(DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d'), ' 00:00:00') reportdate, siteid, siteType, round((sum(KWH)), 6) KWH,
			      //                               round((max(TODAYKWH)), 6) TODAYKWH, round((max(TOTALKWH)), 6) TOTALKWH, round((max(KWHKWP)), 6) KWHKWP, 
			      //                               #round((max(PR)), 6) PR,  
         //                                        round((max(MP)), 6) as MP, round((max(SOLARHOUR)), 6) SOLARHOUR
			      //                         from solar_master.power_station_history_hour a  
			      //                         where SITEID = @siteID	 and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d') = @date1
			      //                         group by  a.siteid, DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d')
         //                           )a join 
		       //                     (
					    //                        select id,  SITEID, round(PR, 4) PR
					    //                        from solar_master.power_station_history_hour a  
			      //                              where SITEID = @siteID	 and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d') =  @date1
					    //                        order by 1 desc limit 1
		       //                     )a1 on a.siteID = a1.siteID  join 
         //                           ( 
		       //                             select id, `code` siteID, PowerRate, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType
		       //                             from solar_master.power_station
		       //                             where `code` =  @siteID
         //                           ) b on a.siteID = b.siteID 
         //                           LEFT JOIN (
         //                               SELECT 
         //                                   SUM(lb.LeaseRate) LeaseRate,
         //                                   ps.Code siteID FROM " + _siteDB + @".land_building lb 
         //                               LEFT JOIN solar_master.power_station ps ON lb.PowerStationId = ps.Id
         //                               WHERE ps.Code = @siteID
         //                               GROUP BY lb.PowerStationId
         //                           ) c ON a.siteID = c.siteID";
                    // conn.Execute(sql, new { date1 = _date1, siteID = _siteID });
                    cmd.Parameters.AddWithValue("@date1", _date1);
                    cmd.Parameters.AddWithValue("@siteID", _siteID);
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    #endregion day 

                    #region month 
                    sql = @"                        
                        INSERT INTO solar_master.power_station_history_month(PowerStationId, `TIMESTAMP`,  SITEID, SITETYPE, monthKwh , TOTALKWH, KWHKWP,
                                    PR, MP, SOLARHOUR, MONEY, TOTALMONEY, CARBON, TOTALCARBON)

                                    select b.id PowerStationId, a.reportdate, b.siteID, a.siteType, TODAYKWH as monthKwh , a.TOTALKWH, a.KWHKWP, a.PR, a.MP, a.SOLARHOUR,
	                                /*CASE 
										WHEN b.SolarType = 1 THEN a.TODAYKWH * c.LeaseRate
										ELSE a.TODAYKWH * PowerRate
									END MONEY,
                                    CASE
										WHEN b.SolarType = 1 THEN a.TOTALKWH * c.LeaseRate
										ELSE a.TOTALKWH * PowerRate
									END TOTALMONEY,*/
                                    (TODAYKWH * PowerRate) MONEY,
                                    (a.TOTALKWH * PowerRate) TOTALMONEY, 
	                                    (TODAYKWH * CarbonRate) CARBON, round((a.TOTALKWH * CarbonRate), 4) TOTALCARBON
                                    from
                                    (
                                          select concat(DATE_FORMAT(`TIMESTAMP`,'%Y-%m'), '-01 00:00:00') reportdate, siteid, siteType,  
                                                 round((sum(TODAYKWH)), 6) TODAYKWH, round((max(TOTALKWH)), 6) TOTALKWH, round((avg(KWHKWP)), 6) KWHKWP,
                                                 round((avg(PR)), 6) PR, round((avg(MP)), 6) as MP, round((avg(SOLARHOUR)), 6) SOLARHOUR
                                           from solar_master.power_station_history_day a
                                           where SITEID = @siteID    and DATE_FORMAT(a.`TIMESTAMP`, '%Y-%m') = @date1
                                           group by  a.siteid, DATE_FORMAT(`TIMESTAMP`, '%Y-%m')
                                    )a join
                                    (  
                                            select id, `code` siteID, PowerRate, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType
                                            from solar_master.power_station
                                            where `code` = @siteID
                                    ) b on a.siteID = b.siteID
                                    LEFT JOIN (
                                        SELECT 
                                            SUM(lb.LeaseRate) LeaseRate,
                                            ps.Code siteID FROM " + _siteDB + @".land_building lb 
                                        LEFT JOIN solar_master.power_station ps ON lb.PowerStationId = ps.Id
                                        WHERE ps.Code = @siteID
                                        GROUP BY lb.PowerStationId
                                    ) c ON a.siteID = c.siteID";
                    //conn.Execute(sql, new { date1 = _date1.Substring(0, 7), siteID = _siteID, powerStationID = _powerStationID });
                    cmd.Parameters.AddWithValue("@date1", _date1.Substring(0, 7));
                    cmd.Parameters.AddWithValue("@siteID", _siteID);
                    cmd.Parameters.AddWithValue("@powerStationID", _powerStationID);
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();

                    #endregion month 

                    conn.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        bool update_powerStationPerHour(string table_name) {
            //WeathersStationId, TodayWeatherTemp, TodayWeather, RateOfRain
            try
            {
                using (MySqlConnection conn = new MySqlConnection(Connection1))
                {
                    conn.Open();

                    string sql = $@"
                    SELECT 
                        DATE_FORMAT(FROM_UNIXTIME(timestamp / 1000), '%Y-%m-%d %H') AS TIMESTAMP,
                        SITEID,  SiteType, KWH, TodayKWh, TotalKWH, KWHKWP, PR, MP,  SolarHour
                    FROM {table_name} WHERE DATE_FORMAT(FROM_UNIXTIME(timestamp / 1000), '%Y-%m-%d %H') = @DateTime ";
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            } 
            //result = await conn.QueryFirstOrDefaultAsync<PowerStationHistory>(sql, new { DateTime = dateTime });

            //string col = $@"select  Id, kwh, Today_kwh, Total_kwh, today_kwhkwp, today_money, total_money, today_PR, today_carbon, total_carbon, today_irradiance, SolarHour";
            return true;
        }
    }
}
