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 get_inv_svc
    {
        string Connection1 = ConfigurationManager.ConnectionStrings["mySql"].ConnectionString;
        /// <summary>
        /// inverter 原始資料 - 5 min
        /// </summary>
        /// <param name="reportDate"></param>
        /// <param name="invID"></param>
        /// <returns></returns>
        public List<raw_inv> Get_rawInv(string reportDate, string invID, string siteDB, string siteID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                //string sql = @"select ID, TIMESTAMP, SITEID, SITETYPE, CONTROLLERID, INVERTERID, SN, AC1V, AC1A, AC1W, AC1F, AC1WH, AC2V, AC2A, AC2W, AC2F, AC2WH, AC3V, AC3A, AC3W, AC3F, AC3WH, ACRUNTIME, DC1V, DC1A, DC1W, DC1WH, DC2V, DC2A, DC2W, DC2WH, DC3V, DC3A, DC3W, DC3WH, DC4V, DC4A, DC4W, DC4WH, DC5V, DC5A, DC5W, DC5WH, DCRUNTIME, WH, TODAYKWH, TOTALKWH, PR, RA1, RA2, RA3, RA4, RA5 
                //               from solar_com0002.s02202000101_inv order by id desc limit 100; ";
                string sql = @"select id , FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') reportdate, inverterid, WH, round(TODAYKWH, 2) TODAYKWH, round(TOTALKWH, 2) TOTALKWH, round(PR, 2) PR, RA1 
                                from " + siteDB + ".s" + siteID + @"_inv  where left(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') , 10) = '" + reportDate + "' and inverterid = '" + invID + "'";

                //List<raw_inv> ds = conn.Query<raw_inv>(sql, new { kind = kind }).ToList();
                List<raw_inv> ds =  conn.Query<raw_inv>(sql).AsList<raw_inv>();
                conn.Close();
                return ds;
            }
        }
        /// <summary>
        /// 每小時平均值 inverter 原始資料 - hour
        /// </summary>
        /// <param name="reportDate"></param>
        /// <param name="invID"></param>
        /// <returns></returns>
        public List<raw_inv_hour> get_Inv_rawAvg(string reportDate, string invID, string siteDB, string siteID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                //string sql = @"select left(reportdate, 13)reportdate, inverterid, round((sum(WH)/1000), 2) KWH, round(max(TODAYKWH), 2) TODAYKWH,
                //        round(max(TOTALKWH), 2) TOTALKWH, round(max(PR), 2) PR, count(*) count
                //               from v_inv_temp where left(reportdate, 10) = '" + reportDate + "' and inverterid = '" + invID + "' " +
                //               "group by  left(reportdate, 13), inverterid";  //round(avg(PR), 2) PR,
                string sql = @"		 
    select  FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H')reportdate, inverterid ,round((sum(WH)/1000), 2) KWH,
           round(max(TODAYKWH), 2) TODAYKWH, round(max(TOTALKWH), 2) TOTALKWH, round(max(PR), 2) PR, count(*) count
    from " + siteDB + ".s" + siteID + @"_inv  
    where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d')  = '" + reportDate + "' and inverterid = '" + invID + @"'
             group by  FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H'), inverterid
	order by 1; ";

//select a.reportdate, a.inverterid, a.KWH, b.TODAYKWH, b.TOTALKWH, b.PR, a.count from 
//	                        (
//			                        select  left(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') , 13)reportdate, inverterid 
//					                        ,round((sum(WH)/1000), 2) KWH,   count(*) count
//			                        from " + siteDB + ".s" + siteID + @"_inv  
//			                        where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d')  = '" + reportDate + "' and inverterid = '" + invID + @"'
//                                    group by  left(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i'), 13), inverterid
//	                        )a join (
//			                        select   FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i') reportdate, round(TODAYKWH, 2) TODAYKWH, round(TOTALKWH, 2) TOTALKWH, inverterid, round(PR, 2) PR
//			                        from " + siteDB + ".s" + siteID + @"_inv    
//			                        where FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d') =  '" + reportDate + @"'  and right(FROM_UNIXTIME(`TIMESTAMP`/1000,'%Y-%m-%d %H:%i'), 2) = '55' and inverterid = '" + invID + @"'			
//	                        )b on a.reportdate = left(b.reportdate, 13) and a.inverterid = b.inverterid ";
                List<raw_inv_hour> ds = conn.Query<raw_inv_hour>(sql).AsList<raw_inv_hour>();
                conn.Close();
                return ds;
            }
        }


        public List<web_inv_15min> get_web_Inv_15min(string reportDate, string invID, string siteID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                string sql = @"select `code` siteID, DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d %H:%i') reportdate, inverterid, a.KWH, a.TODAYKWH, round(a.kwhkwp, 3) kwhkwp
                                from inverter_history_15min a join power_station b on a.powerstationID = b.id
                                where left(`TIMESTAMP`, 10) = '" + reportDate + "' and inverterid = '" + invID + @"' and `code` = @siteID
                                order by cast(reportdate as datetime)"; 
                List<web_inv_15min> ds = conn.Query<web_inv_15min>(sql, new { siteID = siteID }).AsList<web_inv_15min>();
                conn.Close();
                return ds;
            }
        }
        /// <summary>
        /// web 呈現值 每小時平均值 inverter - hour
        /// </summary>
        /// <param name="reportDate"></param>
        /// <param name="invID"></param>
        /// <returns></returns>
        public List<web_inv_hour> get_web_Inv_hour(string reportDate, string invID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                //string sql = @"select DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d %H:%i') reportdate, inverterid, KWH, TODAYKWH, TOTALKWH, round(PR, 2) PR
                //               from inverter_history_hour where left(`TIMESTAMP`, 10) = '" + reportDate + "' and inverterid = '" + invID + "' ";

                string sql = @"select DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d %H:%i') reportdate, inverterid, KWH, TODAYKWH, TOTALKWH, round(PR, 2) PR
                               from inverter_history_hour where crdDate = '" + reportDate + "' and inverterid = '" + invID + "' ";
                List<web_inv_hour> ds = conn.Query<web_inv_hour>(sql).AsList<web_inv_hour>();
                conn.Close();
                return ds;
            }
        }

        public List<web_inv_hour> get_web_Inv_day(string date1, string date2, string invID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                //string sql = @"select DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') reportdate, inverterid, round(KWH, 2) KWH, round(TODAYKWH, 2) TODAYKWH, round(TOTALKWH, 2) TOTALKWH, round(PR, 2) PR
                //               from inverter_history_day where left(`TIMESTAMP`, 10) between '" + date1 + "' and '"+ date2 +"' and inverterid = '" + invID + "' ";
                string sql = @"
select DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d') reportdate, a.inverterid, round(a.KWH, 2) KWH, round(a.TODAYKWH, 2) TODAYKWH, 
			 round(a.TOTALKWH, 2) TOTALKWH, round(a.PR, 2) PR, count
from inverter_history_day a left join (
			select DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') reportdate, inverterid, count(*) count
			from inverter_history_hour
			where crdDate between '" + date1 + "' and '" + date2 + @"' and inverterid =  '" + invID + @"'

            group by DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d'), inverterid
) b on a.inverterid = b.inverterid and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d')  = b.reportdate
where crdDate between '" + date1 + "' and '" + date2 + "' and a.inverterid =  '" + invID + "' order by 1";
                List<web_inv_hour> ds = conn.Query<web_inv_hour>(sql).AsList<web_inv_hour>();
                conn.Close();
                return ds;
            }
        }

        public List<web_inv_hour> get_web_Inv_month(string date1, string date2, string invID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                string sql = @"select DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') reportdate, inverterid, KWH, TODAYKWH, TOTALKWH, round(PR, 2) PR
                               from inverter_history_month where left(`TIMESTAMP`, 7) between '" + date1 + "' and '" + date2 + "' and inverterid = '" + invID + "' ";
                List<web_inv_hour> ds = conn.Query<web_inv_hour>(sql).AsList<web_inv_hour>();
                conn.Close();
                return ds;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="reportDate"></param>
        /// <param name="invID"></param>
        /// <returns></returns>
        public List<web_inv_list> get_Inv_list(string siteDB, string siteID)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                string sql = @"select dbname, inverterid from v_company_inv where dbname = @siteDB and left(inverterid, 9) = @siteID";
                List<web_inv_list> ds = conn.Query<web_inv_list>(sql, new { siteDB = siteDB, siteID = siteID }).AsList<web_inv_list>();
                conn.Close();
                return ds;
            }
        }

        /// <summary>
        /// 總計每天應有數據, inv hour --> day
        /// </summary>
        /// <param name="siteDB"></param>
        /// <param name="siteID"></param>
        /// <returns></returns>
        public List<ck_inv_day> get_ck_invDay_list(string date1, string date2)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open(); //select PowerStationId, station_code, station_name, dataRows as 'Inv資料量A',  invCT as 'Inv建立量B', periodCT 'B/A', periodDay periodDay_B, (periodCT - periodDay) '差異量', hasData '日報表' from
                string sql = @$"select PowerStationId, station_code, station_name, dataRows as dataRows_A,  invCT as invCT_B, periodCT AdivB_C, periodDay periodDay_B, (periodCT - periodDay) CsubstrctionB, hasData  from
	                             (
			                             select a.PowerStationId, station_code, station_name, b.ct dataRows, a.ct invCT, ifnull(round((b.ct / a.ct), 2), 0) periodCT, (DATEDIFF('{date2}' , '{date1}') + 1) periodDay, c.hasData
			                             from 
				                             ( -- 每個電站的 inv 數量
						                             select b.id PowerStationId, b.`name` station_name, left(inverterid, 11) station_code, count(*) ct
						                             from v_company_inv a join power_station b on left(a.inverterid, 9) = b.`code` 
						                             where b.Deleted = 0 and a.`enabled` = 1 and b.`status` = 1 # 啟用
						                             group by left(inverterid, 11)   
				                             ) a left outer join 
				                             (
					                            select PowerStationId , left(crddate, 7) crddate , a.inverterid, round(a.TODAYKWH, 2) todaykWh, count(*) ct 
					                            from inverter_history_day a
					                            where a.crddate between '{date1}' and '{date2}'
					                            group by a.PowerStationId , left(crddate, 7) 
				                             )b on a.PowerStationId = b.PowerStationId
                                            left join 
			                                (
				                                select powerstationid, sum(case when inv_02 is not null then 1 else 0 end) hasData from report_invday  
				                                where left(report_date, 10) between '{date1}' and '{date2}' and hour(report_date) = 11  
				                                group by powerstationid
			                                )c on a.PowerStationId = c.PowerStationId
		                             )x  ";
                List<ck_inv_day> ds = conn.Query<ck_inv_day>(sql, commandTimeout: 300).AsList<ck_inv_day>();
                conn.Close();
                return ds;
            }
        }

        public List<inv_reportDay> get_reportDay(string powerstationID, string date1, string date2)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                string sql = @$"select powerstationid, report_date, inv_01, inv_02, inv_03, inv_04, inv_05 from report_invday  
	where  PowerStationId = '{powerstationID}' and left(report_date, 10) between '{date1}' and '{date2}' 
	order by report_date   ";
                List<inv_reportDay> ds = conn.Query<inv_reportDay>(sql).AsList<inv_reportDay>();
                conn.Close();
                return ds;
            }
        }

        public List<ck_inv_day_detail1> get_ck_invDay_detail1(string powerstationID, string date1, string date2)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                string sql = @$"select PowerStationId ,  a.inverterid, round(avg(a.TODAYKWH), 2) todaykWh, count(*) RowCT 
					from inverter_history_day a
					where PowerStationId = '{powerstationID}' and a.crddate between '{date1}' and '{date2}'
					group by a.PowerStationId , inverterid  ";
                List<ck_inv_day_detail1> ds = conn.Query<ck_inv_day_detail1>(sql).AsList<ck_inv_day_detail1>();
                conn.Close();
                return ds;
            }
        }

        public List<ck_inv_day_detail2> get_ck_invDay_detail2(string inverterid, string date1, string date2)
        {
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                string sql = @$"select a.PowerStationId, left(crddate, 10) crdDate , a.inverterid, round(a.kwh, 2) kwh, round(a.TODAYKWH, 2) todaykWh, round(a.pr, 2) pr 
		from inverter_history_day a  
					where inverterid = '{inverterid}' and a.crddate between '{date1}' and '{date2}'
					  ";
                List<ck_inv_day_detail2> ds = conn.Query<ck_inv_day_detail2>(sql).AsList<ck_inv_day_detail2>();
                conn.Close();
                return ds;
            }
        }
    }
}
