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

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

        public procInvSvc(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
            { 
                using (MySqlConnection conn = new MySqlConnection(Connection1))
                {
                    conn.Open();
                    string sql = @"
                        delete from inverter_history_15min where powerstationID = @powerStationID and  DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = @date1;
                        delete from inverter_history_hour where powerstationID = @powerStationID and  DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = @date1;
                        delete from inverter_history_day where powerstationID = @powerStationID and  DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = @date1;
                        delete from inverter_history_month where powerstationID = @powerStationID and  left(`TIMESTAMP`, 7)  =  left(@date1, 7) ;";
                    var ds = conn.Execute(sql, new { date1 = _date1, PowerStationID = _powerStationID });
                    conn.Close();
                }
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public bool archiveData(string siteID, string date1)
        { 
            bool result = false;
            try
            {
                _siteID = siteID;
                _date1 = date1;
                get_siteInfo();
                clearData();
                insert_inv(); 
                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_inv()
        {
            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);

                    #region 15 min
                    string sql = @"
                    INSERT INTO solar_master.inverter_history_15min( PowerStationId, TIMESTAMP, INVERTERID, KWH, TODAYKWH, KWHKWP) 
                    select PowerStationId, reportdate, a.inverterid, KWH, TODAYKWH, (kwh/(capacity/4)) kwpkwp from
                    (
					        select @PowerStationId PowerStationId, CONCAT(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H'), ':00:00')reportdate, inverterid, 
                                    (sum(WH)/1000) KWH, max(TODAYKWH) TODAYKWH
					         from " + _siteDB + ".s" + _siteID01 + @"_inv 
					         where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d')  = @date1  and right(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') , 2) between '00' and '10'												
                            group by  FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H') , inverterid
		                union 
				            select @PowerStationId PowerStationId, CONCAT(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H'), ':15:00')reportdate, inverterid,     
                                (sum(WH)/1000) KWH, max(TODAYKWH) TODAYKWH
					         from " + _siteDB + ".s" + _siteID01 + @"_inv 
					         where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d')  = @date1  and right(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') , 2) between '15' and '25'												
                            group by  FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H') , inverterid
		                union
				            select @PowerStationId PowerStationId, CONCAT(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H'), ':30:00')reportdate, inverterid, 
                                (sum(WH)/1000) KWH, max(TODAYKWH) TODAYKWH
					         from " + _siteDB + ".s" + _siteID01 + @"_inv 
					         where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d')  = @date1 and right(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') , 2) between '30' and '40'												
                             group by  FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H') , inverterid
		                union 
				            select @PowerStationId PowerStationId, CONCAT(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H'), ':45:00')reportdate, inverterid, 
                             (sum(WH)/1000) KWH, max(TODAYKWH) TODAYKWH
					         from " + _siteDB + ".s" + _siteID01 + @"_inv 
					         where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d') = @date1 and right(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') , 2) between '45' and '55'												
                             group by  FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H') , inverterid
                     ) a join " + _siteDB + @".inverter b on a.inverterid = b.inverterid";
                    var ds = conn.Execute(sql, new { date1 = _date1, PowerStationID = _powerStationID });
                    #endregion

                    #region hour 
                     sql = @"
                       insert into solar_master.inverter_history_hour (PowerStationId, INVERTERID, TIMESTAMP, Irradiance,  AC1V, AC1A, AC1W, AC1F, AC1WH, AC2V, AC2A, AC2W, AC2F, AC2WH, 
                          AC3V, AC3A, AC3W, AC3F, AC3WH, DC1V, DC1A, DC1W,  DC1WH, DC2V, DC2A, DC2W,  DC2WH, DC3V, DC3A, DC3W,  DC3WH, DC4V, DC4A, DC4W, DC4WH, DC5V, DC5A, DC5W, DC5WH,
                          PR, RA1, RA2, RA3, RA4, RA5, DCKW, ACKW, KWH, TODAYKWH, TOTALKWH, KWHKWP)

                        SELECT @powerstationID  powerStationID, a.INVERTERID, a.reportDate, IFNULL(Irradiance, 0), a.AC1V, a.AC1A, a.AC1W, a.AC1F, a.AC1WH, a.AC2V, a.AC2A, a.AC2W, a.AC2F, a.AC2WH, 
                         a.AC3V, a.AC3A, a.AC3W, a.AC3F, a.AC3WH, a.DC1V, a.DC1A, a.DC1W, a.DC1WH, a.DC2V, a.DC2A, a.DC2W, a.DC2WH, a.DC3V, a.DC3A, a.DC3W,
                         a.DC3WH, a.DC4V, a.DC4A, a.DC4W, a.DC4WH, a.DC5V, a.DC5A, a.DC5W, a.DC5WH, 
                         inv_pr.PR, a.RA1, a.RA2, a.RA3, a.RA4, a.RA5,  ((DC1W + DC2W + DC3W + DC4W+ DC5W) / 1000) DCKW, 	
                            ((AC1W + AC2W + AC3W) / 1000) ACKW, a.KWH, a.TODAYKWH, a.TOTALKWH,   (a.KWH / i.Capacity) AS KWHKWP 
                        from  
                        ( -- 取得該時間區間的KWH
		                       SELECT concat(FROM_UNIXTIME(a.TIMESTAMP/1000,'%Y-%m-%d %H'), ':00:00') reportDate, a.INVERTERID,
                                    AVG(a.AC1V) AS AC1V,  AVG(a.AC1A) AS AC1A,   round(SUM(a.AC1W), 5) AS AC1W, AVG(a.AC1F) AS AC1F,  SUM(a.AC1WH) AS AC1WH, AVG(a.AC2V) AS AC2V,
				                    AVG(a.AC2A) AS AC2A,  round(SUM(a.AC2W), 5) AS AC2W,   AVG(a.AC2F) AS AC2F,  SUM(a.AC2WH) AS AC2WH,AVG(a.AC3V) AS AC3V,   AVG(a.AC3A) AS AC3A,
				                    round(SUM(a.AC3W),5) AS AC3W, 	AVG(a.AC3F) AS AC3F,   SUM(a.AC3WH) AS AC3WH, AVG(a.DC1V) AS DC1V,  AVG(a.DC1A) AS DC1A,   SUM(a.DC1W) AS DC1W,
                                    SUM(a.DC1WH) AS DC1WH, AVG(a.DC2V) AS DC2V,  AVG(a.DC2A) AS DC2A,  SUM(a.DC2W) AS DC2W,  SUM(a.DC2WH) AS DC2WH, AVG(a.DC3V) AS DC3V,
                                    AVG(a.DC3A) AS DC3A,  AVG(a.DC3W) AS DC3W,   AVG(a.DC3WH) AS DC3WH,  AVG(a.DC4V) AS DC4V,  AVG(a.DC4A) AS DC4A,   SUM(a.DC4W) AS DC4W,
                                    SUM(a.DC4WH) AS DC4WH,AVG(a.DC5V) AS DC5V,   AVG(a.DC5A) AS DC5A,  SUM(a.DC5W) AS DC5W,  SUM(a.DC5WH) AS DC5WH,
                                    AVG(a.RA1) AS RA1, AVG(a.RA2) AS RA2, AVG(a.RA3) AS RA3,
                                    AVG(a.RA4) AS RA4, AVG(a.RA5) AS RA5, MAX(a.TODAYKWH) AS TODAYKWH, MAX(a.TOTALKWH) AS TOTALKWH,	(SUM(a.WH)/1000) AS KWH
		                        FROM  " + _siteDB + ".s" + _siteID01 + @"_inv a  
		                        WHERE left(FROM_UNIXTIME(a.TIMESTAMP / 1000, '%Y-%m-%d'), 10) = @date1
		                        GROUP BY left(FROM_UNIXTIME(a.TIMESTAMP/ 1000, '%Y-%m-%d %H'), 13), a.INVERTERID 		
                        ) a  
                        LEFT JOIN( -- 取得整點值PR 
		                         SELECT  concat(FROM_UNIXTIME(inv.TIMESTAMP/1000,'%Y-%m-%d %H'), ':00:00') AS reportDate, inv.INVERTERID, inv.PR  
		                         FROM " + _siteDB + ".s" + _siteID01 + @"_inv inv
		                         WHERE left(DATE_FORMAT(FROM_UNIXTIME(inv.TIMESTAMP / 1000), '%Y-%m-%d %H:%i'), 10) = @date1
					                         and right(DATE_FORMAT(FROM_UNIXTIME(inv.TIMESTAMP / 1000), '%Y-%m-%d %H:%i'), 2) = '55' 
		                         GROUP BY FROM_UNIXTIME(inv.TIMESTAMP/ 1000, '%Y-%m-%d %H'), inv.INVERTERID
                        ) inv_pr
                        ON a.reportDate = inv_pr.reportDate AND a.INVERTERID = inv_pr.INVERTERID
                        -- 取得逆變器容量 
                        LEFT JOIN " + _siteDB + @".inverter i ON a.INVERTERID = i.InverterId
                        --  取日照度 --------------------- 
                        left join (
	                        select concat(DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d %H'), ':00:00') AS reportDate, Irradiance
	                        from sensor_history_hour a
	                        where powerstationID = @powerstationID  and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = @date1
                        )irr on  a.reportDate = irr.reportDate 
                        order by a.INVERTERID, a.reportDate;";
                    int ct = conn.Execute(sql, new { date1 = _date1, PowerStationID = _powerStationID });
                    
                    #endregion hour

                    #region day 
                    sql = @"
                        INSERT INTO solar_master.inverter_history_day(PowerStationId, INVERTERID, TIMESTAMP, Irradiance,  AC1V, AC1A, AC1W, AC1F, AC1WH, AC2V, AC2A, AC2W, AC2F, AC2WH, 
                        AC3V, AC3A, AC3W, AC3F, AC3WH, DC1V, DC1A, DC1W,  DC1WH, DC2V, DC2A, DC2W,  DC2WH, DC3V, DC3A, DC3W, 
                        DC3WH, DC4V, DC4A, DC4W, DC4WH, DC5V, DC5A, DC5W, DC5WH, PR, RA1, RA2, RA3, RA4, RA5, `DCKW`, `ACKW`, KWH, TODAYKWH, TOTALKWH, KWHKWP)

                        SELECT  @powerStationID powerStationID, a.INVERTERID, concat(a.reportDate,' 00:00:00') reportDate, IFNULL(Irradiance, 0), a.AC1V, a.AC1A, a.AC1W, a.AC1F, a.AC1WH, a.AC2V, a.AC2A, a.AC2W, a.AC2F, a.AC2WH, 
                         a.AC3V, a.AC3A, a.AC3W, a.AC3F, a.AC3WH, a.DC1V, a.DC1A, a.DC1W, a.DC1WH, a.DC2V, a.DC2A, a.DC2W, a.DC2WH, a.DC3V, a.DC3A, a.DC3W,
                         a.DC3WH, a.DC4V, a.DC4A, a.DC4W, a.DC4WH, a.DC5V, a.DC5A, a.DC5W, a.DC5WH, a.PR, a.RA1, a.RA2, a.RA3, a.RA4, a.RA5,  
                         DCKW,  ACKW, a.KWH, a.TODAYKWH, a.TOTALKWH, (a.KWH / i.Capacity) AS KWHKWP 
                        from  
                        ( -- 取得該時間區間的KWH
		                        SELECT DATE_FORMAT(a.TIMESTAMP, '%Y-%m-%d') AS reportDate, a.INVERTERID,
                                AVG(a.AC1V) AS AC1V,  AVG(a.AC1A) AS AC1A,   SUM(a.AC1W) AS AC1W, AVG(a.AC1F) AS AC1F,  SUM(a.AC1WH) AS AC1WH, AVG(a.AC2V) AS AC2V,
		                        AVG(a.AC2A) AS AC2A,  SUM(a.AC2W) AS AC2W,   AVG(a.AC2F) AS AC2F, 	SUM(a.AC2WH) AS AC2WH,AVG(a.AC3V) AS AC3V,   AVG(a.AC3A) AS AC3A,
		                        SUM(a.AC3W) AS AC3W, 	AVG(a.AC3F) AS AC3F,   SUM(a.AC3WH) AS AC3WH,   AVG(a.DC1V) AS DC1V,  AVG(a.DC1A) AS DC1A,   SUM(a.DC1W) AS DC1W,
                                SUM(a.DC1WH) AS DC1WH, AVG(a.DC2V) AS DC2V,  AVG(a.DC2A) AS DC2A, SUM(a.DC2W) AS DC2W,  SUM(a.DC2WH) AS DC2WH, AVG(a.DC3V) AS DC3V,
                                AVG(a.DC3A) AS DC3A,  AVG(a.DC3W) AS DC3W,   AVG(a.DC3WH) AS DC3WH,  AVG(a.DC4V) AS DC4V,  AVG(a.DC4A) AS DC4A,   SUM(a.DC4W) AS DC4W,
                                SUM(a.DC4WH) AS DC4WH,AVG(a.DC5V) AS DC5V,   AVG(a.DC5A) AS DC5A,  SUM(a.DC5W) AS DC5W,  SUM(a.DC5WH) AS DC5WH, max(PR) AS PR,
                                AVG(a.RA1) AS RA1, AVG(a.RA2) AS RA2, AVG(a.RA3) AS RA3,  AVG(a.RA4) AS RA4, AVG(a.RA5) AS RA5, avg(DCKW) as  DCKW, avg(ACKW) as ACKW,
                                MAX(a.TODAYKWH) AS TODAYKWH, MAX(a.TOTALKWH) AS TOTALKWH, SUM(a.KWH) AS KWH
		                        FROM  solar_master.inverter_history_hour a  
		                        WHERE powerstationID = @powerstationID and DATE_FORMAT(a.TIMESTAMP, '%Y-%m-%d') =  @date1
		                        GROUP BY DATE_FORMAT(a.TIMESTAMP, '%Y-%m-%d'), a.INVERTERID 		
                        ) a  
                        LEFT JOIN " + _siteDB + @".inverter i ON a.INVERTERID = i.InverterId
                        --  取日照度 ---------------------- 
                        left join (
	                        select  DATE_FORMAT(a.TIMESTAMP, '%Y-%m-%d') AS reportDate,  Irradiance
	                        from sensor_history_day a
	                        where powerstationID = @powerstationID  and DATE_FORMAT(a.TIMESTAMP, '%Y-%m-%d') = @date1 and Irradiance <> 0  limit 1
                        )irr on  a.reportDate = irr.reportDate ;";
                    conn.Execute(sql, new { date1 = _date1, PowerStationID = _powerStationID });
                    #endregion day 

                    #region month 
                    sql = @"
                         delete from inverter_history_month where powerstationID = @powerStationID and  left(`TIMESTAMP`, 7)  =  left(@date1, 7) ;

                        INSERT INTO solar_master.inverter_history_month (PowerStationId, INVERTERID, TIMESTAMP, Irradiance,  AC1V, AC1A, AC1W, AC1F, AC1WH, AC2V, AC2A, AC2W, AC2F, AC2WH, 
                        AC3V, AC3A, AC3W, AC3F, AC3WH, DC1V, DC1A, DC1W,  DC1WH, DC2V, DC2A, DC2W,  DC2WH, DC3V, DC3A, DC3W, 
                        DC3WH, DC4V, DC4A, DC4W, DC4WH, DC5V, DC5A, DC5W, DC5WH, PR, RA1, RA2, RA3, RA4, RA5,  `DCKW`, `ACKW`, KWH, TODAYKWH, TOTALKWH, KWHKWP)

                        SELECT  @powerStationID powerStationID, a.INVERTERID, concat(a.reportDate,'-01 00:00:00') reportDate, IFNULL(Irradiance, 0), a.AC1V, a.AC1A, a.AC1W, a.AC1F, a.AC1WH, a.AC2V, a.AC2A, a.AC2W, a.AC2F, a.AC2WH, 
                         a.AC3V, a.AC3A, a.AC3W, a.AC3F, a.AC3WH, a.DC1V, a.DC1A, a.DC1W, a.DC1WH, a.DC2V, a.DC2A, a.DC2W, a.DC2WH, a.DC3V, a.DC3A, a.DC3W,
                         a.DC3WH, a.DC4V, a.DC4A, a.DC4W, a.DC4WH, a.DC5V, a.DC5A, a.DC5W, a.DC5WH, a.PR, a.RA1, a.RA2, a.RA3, a.RA4, a.RA5, DCKW, ACKW, a.KWH, a.TODAYKWH, a.TOTALKWH,
                         (a.KWH / i.Capacity) AS KWHKWP 
                        from  
                        ( -- 取得該時間區間的KWH
		                        SELECT DATE_FORMAT(a.TIMESTAMP, '%Y-%m') AS reportDate, a.INVERTERID,
                                AVG(a.AC1V) AS AC1V,  AVG(a.AC1A) AS AC1A,   SUM(a.AC1W) AS AC1W, AVG(a.AC1F) AS AC1F,  SUM(a.AC1WH) AS AC1WH, AVG(a.AC2V) AS AC2V,
		                        AVG(a.AC2A) AS AC2A,  SUM(a.AC2W) AS AC2W,   AVG(a.AC2F) AS AC2F, 	SUM(a.AC2WH) AS AC2WH,AVG(a.AC3V) AS AC3V,   AVG(a.AC3A) AS AC3A,
		                        SUM(a.AC3W) AS AC3W, 	AVG(a.AC3F) AS AC3F,   SUM(a.AC3WH) AS AC3WH,   AVG(a.DC1V) AS DC1V,  AVG(a.DC1A) AS DC1A,   SUM(a.DC1W) AS DC1W,
                                SUM(a.DC1WH) AS DC1WH, AVG(a.DC2V) AS DC2V,  AVG(a.DC2A) AS DC2A, SUM(a.DC2W) AS DC2W,  SUM(a.DC2WH) AS DC2WH, AVG(a.DC3V) AS DC3V,
                                AVG(a.DC3A) AS DC3A,  AVG(a.DC3W) AS DC3W,   AVG(a.DC3WH) AS DC3WH,  AVG(a.DC4V) AS DC4V,  AVG(a.DC4A) AS DC4A,   SUM(a.DC4W) AS DC4W,
                                SUM(a.DC4WH) AS DC4WH,AVG(a.DC5V) AS DC5V,   AVG(a.DC5A) AS DC5A,  SUM(a.DC5W) AS DC5W,  SUM(a.DC5WH) AS DC5WH, avg(PR) AS PR,
                                AVG(a.RA1) AS RA1, AVG(a.RA2) AS RA2, AVG(a.RA3) AS RA3,  AVG(a.RA4) AS RA4, AVG(a.RA5) AS RA5,  avg(DCKW) as  DCKW, avg(ACKW) as ACKW,
                                avg(a.TODAYKWH) AS TODAYKWH, MAX(a.TOTALKWH) AS TOTALKWH, SUM(a.KWH) AS KWH
		                        FROM  solar_master.inverter_history_day a  
		                        WHERE powerstationID = @powerstationID  and DATE_FORMAT(a.TIMESTAMP, '%Y-%m') =  @date1
		                        GROUP BY DATE_FORMAT(a.TIMESTAMP, '%Y-%m'), a.INVERTERID 		
                        ) a  
                        LEFT JOIN " + _siteDB + @".inverter i ON a.INVERTERID = i.InverterId
                        --  取日照度 ----------------------
                        left join (
	                        select  DATE_FORMAT(a.TIMESTAMP, '%Y-%m') AS reportDate,  Irradiance
	                        from sensor_history_month a
	                        where powerstationID = @powerstationID  and DATE_FORMAT(a.TIMESTAMP, '%Y-%m') = @date1 and Irradiance <> 0  
                        )irr on  a.reportDate = irr.reportDate ;";
                    conn.Execute(sql, new { date1 = _date1.Substring(0, 7), PowerStationID = _powerStationID });
                    #endregion month 

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