using Dapper;
using SolarPower.Helper;
using SolarPower.Models;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;

namespace SolarPower.Repository.Implement
{
    public class StationReportRepository : RepositoryBase<StationReport>, IStationReportRepository
    {
        public StationReportRepository(IDatabaseHelper databaseHelper) : base(databaseHelper)
        {
            tableName = "power_station";
        }


        public async Task<List<string>> GetInverterId(string DBname, Select_table post)
        {
            List<string> result = new List<string>();
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    string sql = @$"SELECT InverterId from {DBname}.inverter i left JOIN {DBname}.controller c ON i.ControllerId = c.Id 
                                    WHERE i.Deleted != 1 AND c.PowerStationId = {post.PowerStation}";
                    result = (await conn.QueryAsync<string>(sql)).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        public async Task<dynamic> Gettablebody(Select_table post)
        {
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                dynamic a;
                conn.Open();
                try
                {
                    //string sql =  @$"SET SESSION group_concat_max_len = 102400;  
                    //         SELECT GROUP_CONCAT( 'a.inv_',RIGHT(v.InverterId, 2))  
                    //         from inv_status v 
                    //         LEFT JOIN power_station p ON p.Code = left(inverterid, 9)
                    //         WHERE p.Id = {post.PowerStation}  AND v.enabled = 1 
                    //         order by 1";
                    string sql = @$" SELECT  RIGHT(v.InverterId, 2) inv
                             from inv_status v 
                             LEFT JOIN power_station p ON p.Code = left(inverterid, 9)
                             WHERE p.Id = {post.PowerStation}  AND v.enabled = 1 
                             order by 1";
                    var invList = conn.Query<string>(sql).ToList();
                    string inv = string.Empty;
                    foreach (var s in invList)
                    {
                        inv += "round(sum( inv_" + s + ") , 2) inv_" + s + " , "; 
                    }
                    
                    // sum(inv_01) as inv_01
                    //var inv_ss = inv.Split(',').Select(x => " round(sum(" + x + "), 2) " + x.Substring(2, x.Length -2) + ", ").ToList();
                    //string inv_sum = string.Empty;
                    //foreach (string s in inv_ss)
                    //{
                    //    inv_sum += s;
                    //}
                    //sql = $@"  select  GROUP_CONCAT( ' round(sum(inv_',RIGHT(v.InverterId, 2), '), 3) inv_',RIGHT(v.InverterId, 2) )  
                    //            from inv_status v  LEFT JOIN power_station p ON p.Code = left(inverterid, 9)
                    //            WHERE p.Id = {post.PowerStation}  and v.enabled = 1 
                    //            order by 1;";
                    //var inv_sum = conn.Query<string>(sql).FirstOrDefault();

                    switch (post.FormType)
                    {
                        case 0: //日報
                            sql = $@"
                            DROP TABLE IF EXISTS temp_inv;
                            create TEMPORARY TABLE temp_inv as
                            SELECT DATE_FORMAT(a.report_date,'%m-%d %H') report_date, {inv}
                                 a.hourKWH hourKWH, a.hourKWHp 'hourKWHp', IFNULL(a.irrDay, 0) irrDay, IFNULL(a.irrDayHour, 0) irrDayHour, a.Temperature 'temperature',
                                 a.hourmoney 'hourmoney',  c.TODAYKWH 'totKWH', c.KWHKWP 'totKWHKWP', c.money 'totmoney',  stationName, powerRate daymoney, c.SOLARHOUR tothour,round(a.PR, 2) as pr,GeneratingCapacity
                            FROM report_invday a 
                             left join 
                             ( # day
                                 select powerStationid, DATE_FORMAT(TIMESTAMP,'%Y-%m-%d') report_date, sitetype, round(TODAYKWH, 2) TODAYKWH, round(KWHKWP, 2) KWHKWP
                                 , round(PR, 2) PR, round(money, 2)  money , round(SOLARHOUR, 2) SOLARHOUR
                                 from power_station_history_day
                                 where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = '{post.Time}'
                             ) c on  a.PowerStationID = c.powerStationid and DATE_FORMAT(a.`report_date`,'%Y-%m-%d') = c.report_date
                             join 
                             (
                                 select id, name stationName, powerRate,GeneratingCapacity from power_station where id = {post.PowerStation}
                             )z on a.PowerStationID = z.id          
                             where DATE_FORMAT(a.report_date,'%Y-%m-%d') = '{post.Time}' and a.PowerStationID = {post.PowerStation}
                             GROUP BY DATE_FORMAT(a.report_date,'%Y-%m-%d %H:%i')
                             order by DATE_FORMAT(a.report_date,'%Y-%m-%d %H:%i') ; 
                            -- step 2
                            DROP TABLE IF EXISTS temp_inv2;
                            create TEMPORARY TABLE temp_inv2 as
                            select * from temp_inv;
                            -- step 3 
		                            select * from temp_inv  
                                    union  
		                                    SELECT '總計' report_date,  {inv}
		                                      round(sum(hourKWH), 2) hourKWH, round(sum(hourKWHp), 2) hourKWHp, round(sum(irrDay),2) irrDay, round(sum(irrDayHour),2) irrDayHour,
                                           round( avg(temperature), 2) temperature, round(sum(hourmoney), 2) hourmoney, round(sum(totKWH), 2) totKWH, round(sum(totKWHKWP),2) totKWHKWP, round(sum(totmoney),2) totmoney, '電站名稱' stationName,
                                           round( sum(daymoney), 2) daymoney, round(sum(tothour), 2) tothour, round(sum(pr), 2) pr, avg(GeneratingCapacity) GeneratingCapacity
                                    from temp_inv2 a;    ";  

                            break;
                        case 1: //月報
                            if(post.SearchType == 2)
                            {
                                sql= @$"  DROP TABLE IF EXISTS temp_inv;
                                         create TEMPORARY TABLE temp_inv as
                                        SELECT DATE_FORMAT(a.report_date,'%m/%d') report_date,  {inv}
                                              b.TODAYKWH 'dayKWH', round((b.TODAYKWH / c.monthKWH)*100,2) 'dayKWHp', b.SOLARHOUR 'tothour',  b.KWHKWP 'KWHKWP', b.PR,z.GeneratingCapacity,
                                              d.irradiance 'irradiance', d.Temperature 'temperature', b.money 'soldmoney', 
                                              c.monthKWH 'monthKWH', c.money 'monthmoney',  stationName, powerRate 'monthmoneyone',SolarType,SiteDB,d.IrrDay
                                         FROM report_invday a left join 
                                          ( # 每日加總 inv 
                                           select powerStationid, DATE_FORMAT(TIMESTAMP,'%Y-%m-%d') report_date, siteid, sitetype, #, round(KWH, 2) KWH, 
                                             round(todayKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                           from power_station_history_day
                                           where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y-%m') = '{post.Time}'  
                                          ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m-%d') = b.report_date
                                          left join 
                                          ( # month
                                           select powerStationid, DATE_FORMAT(TIMESTAMP,'%Y-%m') report_date, sitetype, round(monthKWH, 2) monthKWH,round(KWHKWP, 2) KWHKWP
                                           , round(PR, 2) PR, round(money, 2)  money , round(SOLARHOUR, 2) SOLARHOUR
                                           from power_station_history_month
                                           where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y-%m') = '{post.Time}'
                                          ) c on  a.powerStationid = c.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m') = c.report_date
                                          left join 
                                          (
                                           select powerStationID, DATE_FORMAT(TIMESTAMP,'%Y-%m-%d')report_date, irradiance, Temperature ,IrrDay 
                                           from sensor_history_day
                                           where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y-%m') = '{post.Time}'  
                                          ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m-%d') = d.report_date
                                          join 
                                          (
                                           select id, name stationName, powerRate, SolarType, SiteDB, GeneratingCapacity from power_station where id = {post.PowerStation}
                                          )z on a.powerstationid = z.id          
                                          where a.PowerStationID ={post.PowerStation} and DATE_FORMAT(a.report_date,'%Y-%m') = '{post.Time}'
                                          GROUP BY DATE_FORMAT(a.report_date,'%Y-%m-%d')
                                          order by DATE_FORMAT(a.report_date,'%Y-%m-%d') ;
                                         -- step 2
                            DROP TABLE IF EXISTS temp_inv2;
                            create TEMPORARY TABLE temp_inv2 as
                            select * from temp_inv;
                            -- step 3 
		                            select * from temp_inv  
                                    union  
		                                    SELECT '總計' report_date,  {inv}
		                                      round(sum(dayKWH), 2) dayKWH, round(sum(dayKWHp), 2) dayKWHp, round(max(tothour), 2) tothour, round(avg(KWHKWP), 2) KWHKWP, round(avg(PR), 2) PR,  
                                                   GeneratingCapacity, round(sum(irradiance), 2) irradiance, round(avg(temperature), 2) temperature, round(sum(soldmoney), 2) soldmoney,                                     
                                               round(monthKWH, 2)  monthKWH, monthmoney, stationName, monthmoneyone, SolarType, SiteDB, round(avg(IrrDay), 2) IrrDay
                                    from temp_inv2 a;  "; 
                            }
                            else
                            {  //區間
                                var times = post.Time.Replace('-', 'a').Replace('/', '-').Replace(" ", "").Split('a');
                                #region old sql 
                                //sql = @$"SET @sql = NULL;
                                //    SELECT
                                //      GROUP_CONCAT(DISTINCT
                                //        CONCAT('max(case when INVERTERID = ''', INVERTERID, ''' then round(a.KWH, 2) end) ''inv_', right(INVERTERID, 2), '''')
                                //      ) INTO @sql
                                //    FROM inverter_history_day where powerstationId = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}';
                                //SET @sql = CONCAT('SELECT DATE_FORMAT(a.TIMESTAMP,''%m/%d'') report_date, ', @sql, 
                                //         ',b.TODAYKWH ''dayKWH'', round((b.TODAYKWH / c.monthKWH)*100,2) ''dayKWHp'', b.SOLARHOUR ''tothour'',  b.KWHKWP ''KWHKWP'', b.PR,GeneratingCapacity,
                                //  d.irradiance ''irradiance'', d.Temperature ''temperature'', b.money ''soldmoney'', 
                                // c.monthKWH ''monthKWH'', c.money ''monthmoney'',  stationName, powerRate ''monthmoneyone'',SolarType,SiteDB ,d.IrrDay
                                //         FROM inverter_history_day a left join 
                                //              ( # 每日加總 inv 
                                //               select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') report_date, siteid, sitetype, #, round(KWH, 2) KWH, 
                                //                 round(todayKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                //               from power_station_history_day
                                //               where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                //              ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'') = b.report_date
                                //              left join 
                                //              ( # month
                                //                SELECT powerStationid, ROUND(SUM(TODAYKWH),2) AS monthKWH,
                                //           ROUND(AVG(KWHKWP),2)  AS KWHKWP,
                                //             ROUND(AVG(PR),2) AS PR,
                                //           ROUND(SUM(MONEY),2) AS money,
                                //           ROUND(SUM(SOLARHOUR),2)  AS SOLARHOUR
                                //         FROM power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                //              ) c on  a.powerStationid = c.powerStationid 
                                //              left join 
                                //              (
                                //               select powerStationID, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'')report_date, irradiance, Temperature ,IrrDay
                                //               from sensor_history_day
                                //               where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                //              ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'') = d.report_date
                                //              join 
                                //              (
                                //               select id, name stationName, powerRate, SolarType, SiteDB,GeneratingCapacity   from power_station where id = {post.PowerStation}
                                //              )z on a.powerstationid = z.id          
                                //              where DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                //              GROUP BY DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'')
                                //              order by DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'')  ');

                                //    # select  @sql as 'mySelect'; #顯示動態語法
                                //     PREPARE stmt FROM @sql; 
                                //     EXECUTE stmt;
                                //     DEALLOCATE PREPARE stmt;"; 
                                #endregion old sql 

                                sql = @$"   DROP TABLE IF EXISTS temp_inv;
                                         create TEMPORARY TABLE temp_inv as 
                                        SELECT DATE_FORMAT(a.report_date,'%m/%d') report_date, {inv}
                                           b.TODAYKWH 'dayKWH', round((b.TODAYKWH / c.monthKWH)*100,2) 'dayKWHp', b.SOLARHOUR 'tothour',  b.KWHKWP 'KWHKWP', b.PR,GeneratingCapacity,
                                              d.irradiance 'irradiance', d.Temperature 'temperature', b.money 'soldmoney', 
                                             c.monthKWH 'monthKWH', c.money 'monthmoney',  stationName, powerRate 'monthmoneyone',SolarType,SiteDB ,d.IrrDay
                                         FROM report_invday a left join 
                                              ( # 每日加總 inv 
                                               select powerStationid, DATE_FORMAT(TIMESTAMP,'%Y-%m-%d') report_date, siteid, sitetype, #, round(KWH, 2) KWH, 
                                                 round(todayKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                               from power_station_history_day
                                               where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'
                                              ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m-%d') = b.report_date
                                              left join 
                                              ( # month
                                                SELECT powerStationid, ROUND(SUM(TODAYKWH),2) AS monthKWH,
		                                         ROUND(AVG(KWHKWP),2)  AS KWHKWP,
	  	                                         ROUND(AVG(PR),2) AS PR,
		                                         ROUND(SUM(MONEY),2) AS money,
		                                         ROUND(SUM(SOLARHOUR),2)  AS SOLARHOUR
                                         FROM power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'
                                              ) c on  a.powerStationid = c.powerStationid 
                                              left join 
                                              (
                                               select powerStationID, DATE_FORMAT(TIMESTAMP,'%Y-%m-%d')report_date, irradiance, Temperature ,IrrDay
                                               from sensor_history_day
                                               where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'
                                              ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m-%d') = d.report_date
                                              join 
                                              (
                                               select id, name stationName, powerRate, SolarType, SiteDB,GeneratingCapacity   from power_station where id = {post.PowerStation}
                                              )z on a.powerstationid = z.id          
                                              where  a.powerstationId = {post.PowerStation} and  DATE_FORMAT(a.report_date,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'
                                              GROUP BY DATE_FORMAT(a.report_date,'%Y-%m-%d')
                                              order by DATE_FORMAT(a.report_date,'%Y-%m-%d');
                                               -- step 2
                            DROP TABLE IF EXISTS temp_inv2;
                            create TEMPORARY TABLE temp_inv2 as
                            select * from temp_inv;
                            -- step 3 
		                            select * from temp_inv  
                                    union  
		                                    SELECT '總計' report_date,  {inv}
		                                      round(sum(dayKWH), 2) dayKWH, round(sum(dayKWHp), 2) dayKWHp, round(max(tothour), 2) tothour, avg(KWHKWP) KWHKWP, round(avg(PR), 2) PR,  
                                                   GeneratingCapacity, round(sum(irradiance), 2) irradiance, round(avg(temperature), 2) temperature, round(sum(soldmoney), 2) soldmoney,                                     
                                              round( monthKWH,2) monthKWH , monthmoney, stationName, monthmoneyone, SolarType, SiteDB, round(avg(IrrDay), 2) IrrDay
                                    from temp_inv2 a;  ";
                            }

                            break;
                        case 3: //年報
                            #region old SQL 
                            //sql = @$"
                            //    SET @sql = NULL;
                            //    SELECT
                            //     GROUP_CONCAT(DISTINCT
                            //       CONCAT('max(case when INVERTERID = ''', INVERTERID, ''' then round(a.KWH, 2) end) ''inv_', right(INVERTERID, 2), '''')
                            //     ) INTO @sql
                            //    FROM inverter_history_month where powerstationId = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y') = '{post.Time}';
                            //    SET @sql = CONCAT('SELECT DATE_FORMAT(a.TIMESTAMP,''%Y/%m'') report_date, ', @sql, 
                            //            ',b.todayKWH ''dayKWH'', round((b.todayKWH / c.monthKWH)*100,2) ''dayKWHp'', b.SOLARHOUR ''tothour'',  b.KWHKWP ''KWHKWP'', b.PR,z.GeneratingCapacity,
                            //     d.irradiance ''irradiance'', d.Temperature ''temperature'', b.money ''soldmoney'', 
                            //    c.monthKWH ''monthKWH'', c.money ''monthmoney'',  stationName, powerRate ''monthmoneyone'',SolarType,SiteDB
                            //            FROM inverter_history_month a left join 
                            //             ( # 每日加總 inv 
                            //              select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m'') report_date, siteid, sitetype,
                            //                round(MONTHKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                            //              from power_station_history_month
                            //              where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y'') = ''{post.Time}''  
                            //             ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m'') = b.report_date
                            //             left join 
                            //             ( # month
                            //              select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y'') report_date, sitetype,  sum(round(monthKWH, 2)) monthKWH , avg(round(KWHKWP, 2)) KWHKWP
                            //              , avg(round(PR, 2)) PR, sum(round(money, 2))  money , sum(round(SOLARHOUR, 2)) SOLARHOUR
                            //              from power_station_history_month
                            //              where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y'') = ''{post.Time}'' group by DATE_FORMAT(TIMESTAMP,''%Y'')
                            //             ) c on  a.powerStationid = c.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y'') = c.report_date
                            //             left join 
                            //             (
                            //              select powerStationID, DATE_FORMAT(TIMESTAMP,''%Y-%m'')report_date, irradiance, Temperature  
                            //              from sensor_history_month
                            //              where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y'') = ''{post.Time}''  
                            //             ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m'') = d.report_date
                            //             join 
                            //             (
                            //              select id, name stationName, powerRate,SolarType,SiteDB,GeneratingCapacity from power_station where id = {post.PowerStation}
                            //             )z on a.powerstationid = z.id          
                            //             where DATE_FORMAT(a.TIMESTAMP,''%Y'') = ''{post.Time}''
                            //             GROUP BY DATE_FORMAT(a.TIMESTAMP,''%Y-%m'')
                            //             order by DATE_FORMAT(a.TIMESTAMP,''%Y-%m'')  ');

                            //    # select  @sql as 'mySelect'; #顯示動態語法
                            //    PREPARE stmt FROM @sql; 
                            //    EXECUTE stmt;
                            //    DEALLOCATE PREPARE stmt;"; 
                            #endregion
                            DateTime firstDay = new DateTime(int.Parse(post.Time), 01, 01);
                            DateTime lastDay;
                            if (DateTime.Now.Year == int.Parse(post.Time))
                            {
                                lastDay = DateTime.Now.Date;
                            }
                            else
                            {
                                lastDay = new DateTime(int.Parse(post.Time), 12, 31);
                            }
                            string days = (lastDay - firstDay).TotalDays.ToString();

                            sql = @$"  DROP TABLE IF EXISTS temp_inv;
                                         create TEMPORARY TABLE temp_inv as 
                                SELECT DATE_FORMAT(a.report_date,'%Y/%m') report_date,  {inv}
                                         b.todayKWH 'dayKWH', round((b.todayKWH / c.monthKWH)*100,2) 'dayKWHp', b.SOLARHOUR 'tothour',  b.KWHKWP 'KWHKWP', b.PR,z.GeneratingCapacity,
                                 d.irradiance 'irradiance', d.Temperature 'temperature', b.money 'soldmoney', 
                                c.monthKWH 'monthKWH', c.money 'monthmoney',  stationName, powerRate 'monthmoneyone',SolarType,SiteDB, d.IrrDay, {days} Days
                                        FROM report_invday a left join 
                                         ( # 每日加總 inv 
                                          select powerStationid, DATE_FORMAT(TIMESTAMP,'%Y-%m') report_date, siteid, sitetype,
                                            round(MONTHKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                          from power_station_history_month
                                          where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y') = '{post.Time}'  
                                         ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m') = b.report_date
                                         left join 
                                         ( # month
                                          select powerStationid, DATE_FORMAT(TIMESTAMP,'%Y') report_date, sitetype,  sum(round(monthKWH, 2)) monthKWH , avg(round(KWHKWP, 2)) KWHKWP
                                          , avg(round(PR, 2)) PR, sum(round(money, 2))  money , sum(round(SOLARHOUR, 2)) SOLARHOUR
                                          from power_station_history_month
                                          where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y') = '{post.Time}' group by DATE_FORMAT(TIMESTAMP,'%Y')
                                         ) c on  a.powerStationid = c.powerStationid and DATE_FORMAT(a.report_date,'%Y') = c.report_date
                                         left join 
                                         (
                                          select powerStationID, DATE_FORMAT(TIMESTAMP,'%Y-%m')report_date, irradiance, Temperature, IrrDay
                                          from sensor_history_month
                                          where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,'%Y') = '{post.Time}'  
                                         ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.report_date,'%Y-%m') = d.report_date
                                         join 
                                         (
                                          select id, name stationName, powerRate,SolarType,SiteDB,GeneratingCapacity from power_station where id = {post.PowerStation}
                                         )z on a.powerstationid = z.id          
                                         where a.powerstationId = {post.PowerStation} and DATE_FORMAT(a.report_date,'%Y') = '{post.Time}'
                                         GROUP BY DATE_FORMAT(a.report_date,'%Y-%m')
                                         order by DATE_FORMAT(a.report_date,'%Y-%m')  ;
                                         -- step 2
                            DROP TABLE IF EXISTS temp_inv2;
                            create TEMPORARY TABLE temp_inv2 as
                            select * from temp_inv;
                            -- step 3 
		                            select * from temp_inv  
                                    union  
		                                    SELECT '總計' report_date,  {inv}
		                                      round(sum(dayKWH), 2) dayKWH, round(sum(dayKWHp), 2) dayKWHp, round(max(tothour), 2) tothour, avg(KWHKWP) KWHKWP, round(avg(PR), 2) PR,  
                                                   GeneratingCapacity, round(sum(irradiance), 2) irradiance, avg(temperature) temperature, round(sum(soldmoney), 2) soldmoney,                                     
                                               round(monthKWH, 2) monthKWH, monthmoney, stationName, monthmoneyone, SolarType, SiteDB,  round(avg(IrrDay), 2) IrrDay, 0 
                                    from temp_inv2 a; ";
                            break;

                    }
                    a = await conn.QueryAsync<dynamic>(sql, commandTimeout: 600);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return a;
            }
        }

        public async Task<int> CheckExcelAsync(Select_table post)
        {
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                int a; 
                conn.Open();
                try
                {
                    string sql = "";
                    switch ( post.FormType )
                    {
                        case 0:
                            sql = @$"select Id from power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') = '{post.Time}'";
                            break;
                        case 1:
                            if(post.SearchType == 2)
                            {
                                sql = @$"select Id from power_station_history_month where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m') = '{post.Time}'";
                            }
                            else
                            {
                                var times = post.Time.Replace('-', 'a').Replace('/', '-').Replace(" ", "").Split('a');
                                sql = @$"select Id from power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'";
                            }
                            break;
                        case 3:
                            sql = @$"select Id from power_station_history_month where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y') = '{post.Time}'";
                            break;
                    }
                     a = await conn.QueryFirstOrDefaultAsync<int>(sql, 600);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return a;
            }
        }




        public async Task<List<Landinfo>> GetHire (PsIdAndSiteDB post)
        {
            List<Landinfo> result = new List<Landinfo>();
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    string sql = @$"SELECT LeaseRate,Landowner from {post.SiteDB}.land_building WHERE PowerStationId = {post.PowerstationId} and Deleted = 0";
                    result = (await conn.QueryAsync<Landinfo>(sql)).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        /// <summary>
        /// 綜合比較
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public async Task<List<MaxFormbody>> GetMaxtablebody(Select_table2 post)
        {
            string day1 = $"{1} 'Days'";
            List<MaxFormbody> result = new List<MaxFormbody>();
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    List<int> ids = new List<int>();
                    foreach (var i in post.PowerStation)
                    {
                        ids.Add(Convert.ToInt32(i.Value));
                    }
                    string[] times = { };
                    if (post.SearchType == 1)
                    {
                        times = post.Time.Replace('-', 'a').Replace('/', '-').Replace(" ", "").Split('a');
                    }

                    
                    if (post.SearchType == 2)
                    {
                        DateTime today = DateTime.Now.Date;
                        DateTime FirstDay = DateTime.ParseExact(post.Time, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime LastDay = FirstDay.AddMonths(1).AddDays(-FirstDay.AddMonths(1).Day);
                        if((LastDay-today).Days > 0)
                        {
                            LastDay = today.AddDays(-1);
                        }

                        day1 = $"TIMESTAMPDIFF(DAY,'{FirstDay}','{LastDay}') 'Days'";
                    }
                    else if (post.SearchType == 3)
                    {
                        DateTime yFirstDay = DateTime.ParseExact(post.Time, "yyyy", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime yLastDay = yFirstDay.AddMonths(12).AddDays(-yFirstDay.AddMonths(1).Day);
                        if ((yLastDay - DateTime.Now.Date).Days > 0)
                        {
                            yLastDay = DateTime.Now.Date.AddDays(-1);
                        }
                        day1 = $"TIMESTAMPDIFF(DAY,'{yFirstDay}','{yLastDay}') 'Days'";
                    }
                    else
                    {
                        day1 = post.SearchType switch
                        {
                            0 => $"{1} 'Days'",
                            1 => $"TIMESTAMPDIFF(DAY,'{times[0]}','{times[1]}') 'Days'",
                            _ => ""
                        };
                    }

                    var wheretime = post.SearchType switch
                    {
                        0 => $"AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') = '{post.Time}'",
                        1 => $"AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}'",
                        2 => $"AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m') = '{post.Time}' AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') != '{DateTime.Now.ToString("yyyy-MM-dd")}'",
                        3 => $"AND DATE_FORMAT(ps.TIMESTAMP,'%Y') = '{post.Time}' AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') != '{DateTime.Now.ToString("yyyy-MM-dd")}'",
                        _ => ""
                    };
                    //string sql = @$"SELECT 
                    //    c.Name AS 'CityName',
                    //    a.Name AS 'AreaName',
                    //    ps.Name AS 'PowerstationName',
                    //    ps.SiteDB AS 'PowerstationDB',
                    //    ps.SolarType AS 'PowerstationType',
                    //    ps.Id as 'PowerStationId',
                    //    n.*
                    //    FROM power_station ps 
                    //    LEFT JOIN city c ON c.Id = ps.CityId
                    //    LEFT JOIN area a ON a.Id = ps.AreaId
                    //    left JOIN 
                    //    (
                    //     SELECT a.SolarHour ,a.Kwh ,b.PR AvgPR,b.KWHKWP AvgKWHKWP,c.Irradiance AvgIrradiance,b.TodayMoney as 'TodayMoney',a.Id,a.time,a.maxtime,a.mintime FROM 
                    //     (
                    //        SELECT ps.Id,SUM(k.SolarHour) SolarHour,SUM(k.Kwh) Kwh , k.time , max(k.maxtime) maxtime ,min(k.mintime) mintime FROM power_station ps 
                    //      LEFT JOIN 
                    //      (
                    //       SELECT Max(ps.SOLARHOUR) AS 'SolarHour',MAX(ps.TODAYKWH) 'Kwh' ,DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d %H:%i') AS 'time',MAX(DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d %H:%i')) AS 'maxtime',MIN(DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d %H:%i')) AS 'mintime', ps.PowerStationId
                    //       FROM power_station_history_hour ps 
                    //       WHERE ps.PowerStationId IN @ids {wheretime}
                    //       GROUP BY DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d'),ps.PowerStationId 
                    //      ) k ON k.PowerStationId = ps.Id WHERE ps.Id IN @ids GROUP BY k.PowerStationId 
                    //     ) a
                    //     LEFT JOIN 
                    //     (
                    //        SELECT ps.Id,AVG(n.PR) PR,AVG(n.KWHKWP) KWHKWP,SUM(n.TodayMoney) TodayMoney FROM power_station ps
                    //      LEFT JOIN 
                    //      (
                    //       SELECT B.PR ,B.KWHKWP,B.TODAYMONEY AS 'TodayMoney', DATE_FORMAT(A.bb,'%Y-%m-%d') 'time' ,B.PowerStationId FROM
                    //       (
                    //          SELECT Max(ps.TIMESTAMP) AS bb FROM power_station_history_hour ps 
                    //          WHERE ps.PowerStationId IN @ids {wheretime}
                    //          GROUP BY DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d'),ps.PowerStationId 
                    //       ) A 
                    //       LEFT JOIN power_station_history_hour B ON A.bb = B.TIMESTAMP 
                    //       GROUP BY B.PowerStationId ,DATE_FORMAT(A.bb,'%Y-%m-%d')
                    //      )n ON ps.Id = n.PowerStationId WHERE ps.Id IN @ids GROUP BY n.PowerStationId  
                    //     ) b
                    //     ON a.Id = b.Id
                    //     LEFT JOIN 
                    //     (
                    //        SELECT SUM(ps.Irradiance) AS Irradiance , DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS TIME ,ps.PowerStationId
                    //        from sensor_history_hour ps 
                    //        WHERE ps.PowerStationId IN @ids {wheretime}
                    //        GROUP BY DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d'),ps.PowerStationId
                    //     ) c
                    //     ON a.Id = c.PowerStationId
                    //     GROUP BY a.Id,a.time
                    //    ) n ON n.Id = ps.Id
                    //    WHERE ps.Id IN @ids ORDER BY ps.CityId";
                    string sql = $@"SELECT  ct.`Name` AS 'CityName', ar.Name AS 'AreaName', ps.Name AS 'PowerstationName', ps.SiteDB AS 'PowerstationDB', ps.SolarType AS 'PowerstationType',
                                         ps.Id as 'PowerStationId', ps.ElectricityMeterAt as 'electricityMeterAt', ps.PowerRate, ps.GeneratingCapacity,
                                       a.SolarHour ,a.Kwh ,a.PR AvgPR, a.KWHKWP AvgKWHKWP,c.Irradiance Irradiance, a.TOTALKWH TotalKWH, 
                                        (a.TODAYKWH * PowerRate) 'TodayMoney', a.Id,a.time,a.maxtime,a.mintime, {day1}
                                     FROM power_station ps 
                                     LEFT JOIN city ct ON ct.Id = ps.CityId
                                     LEFT JOIN area ar ON ar.Id = ps.AreaId
                                     left JOIN     
                                         (
                                         SELECT powerStationid id, ps.SOLARHOUR AS 'SolarHour',SUM(ps.TODAYKWH) 'Kwh' , PR, KWHKWP, TODAYKWH, TOTALKWH,
                                          DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS 'time', 
                                          MAX(DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d %H:%i')) AS 'maxtime',
                                          MIN(DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d %H:%i')) AS 'mintime', ps.PowerStationId
                                         FROM power_station_history_day ps 
                                         WHERE ps.PowerStationId IN  @ids {wheretime}
                                         GROUP BY ps.PowerStationId 
                                         ) a ON ps.Id = a.Id  
                                       LEFT JOIN 
                                         (
                                            SELECT SUM(ps.Irradiance) AS Irradiance , DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS TIME ,ps.PowerStationId
                                            from sensor_history_day ps 
                                            WHERE ps.PowerStationId IN  @ids  {wheretime}
                                            GROUP BY  ps.PowerStationId
                                         ) c  ON a.Id = c.PowerStationId and a.time = c.time
                                        WHERE ps.Id IN @ids ORDER BY ps.CityId";
                    result = (await conn.QueryAsync<MaxFormbody>(sql,new { ids = ids}, commandTimeout: 600)).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        public async Task<dynamic> Findhaveinv(Select_table post)
        {
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                dynamic a;
                conn.Open();
                try
                {
                    string sql = "";
                    switch (post.FormType)
                    {
                        case 0:
                            sql = @$"
                                SET @sql = NULL;
                                SELECT
                                GROUP_CONCAT( 'a.inv_',RIGHT(v.InverterId, 2)) INTO @sql
                                from v_company_inv v 
                                LEFT JOIN power_station p ON p.Code = left(inverterid, 9)
                                WHERE p.Id = {post.PowerStation}  AND v.enabled = 1 ;
 
                                SET @sql = CONCAT('SELECT DATE_FORMAT(a.report_date,''%m-%d %H'') report_date, ', @SQL, 
                                ', a.hourKWH hourKWH, a.hourKWHp ''hourKWHp'',  a.irradiance ''irradiance'', a.Temperature ''temperature'',
                                a.hourmoney ''hourmoney'',  c.TODAYKWH ''totKWH'', c.KWHKWP ''totKWHKWP'', c.money ''totmoney'',  stationName, powerRate daymoney, c.SOLARHOUR tothour,round(a.PR, 2) as pr,GeneratingCapacity
                                FROM report_invday a 
                                left join 
                                ( # day
                                select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') report_date, sitetype, round(TODAYKWH, 2) TODAYKWH,round(KWHKWP, 2) KWHKWP
                                , round(PR, 2) PR, round(money, 2)  money , round(SOLARHOUR, 2) SOLARHOUR
                                from power_station_history_day
                                where powerstationid = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,''%Y-%m-%d'') = ''{post.Time}''
                                ) c on  a.PowerStationID = c.powerStationid and DATE_FORMAT(a.`report_date`,''%Y-%m-%d'') = c.report_date
                                join 
                                (
                                select id, name stationName, powerRate,GeneratingCapacity from power_station where id = {post.PowerStation}
                                )z on a.PowerStationID = z.id          
                                where DATE_FORMAT(a.report_date,''%Y-%m-%d'') = ''{post.Time}'' and 
                                GROUP BY DATE_FORMAT(a.report_date,''%Y-%m-%d %H:%i'')
                                order by DATE_FORMAT(a.report_date,''%Y-%m-%d %H:%i'') ');

                                select  @sql as 'mySelect'; #顯示動態語法
                                #PREPARE stmt FROM @sql; 
                                #EXECUTE stmt;
                                #DEALLOCATE PREPARE stmt;";
                            break;
                        case 1:
                            if (post.SearchType == 2)
                            {
                                sql = @$"
                                SET @sql = NULL;
                                SELECT
                                  GROUP_CONCAT(DISTINCT
                                    CONCAT('max(case when INVERTERID = ''', INVERTERID, ''' then round(a.KWH, 2) end) ''inv_', right(INVERTERID, 2), '''')
                                  ) INTO @sql
                                FROM inverter_history_day where powerstationId = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m') = '{post.Time}';
                                SET @sql = CONCAT('SELECT DATE_FORMAT(a.TIMESTAMP,''%m/%d'') report_date, ', @sql, 
                                         ',b.TODAYKWH ''dayKWH'', round((b.TODAYKWH / c.monthKWH)*100,2) ''dayKWHp'', b.SOLARHOUR ''tothour'',  b.KWHKWP ''KWHKWP'', b.PR,
                                  d.irradiance ''irradiance'', d.Temperature ''temperature'', b.money ''soldmoney'', 
                                 c.monthKWH ''monthKWH'', c.money ''monthmoney'',  stationName, powerRate ''monthmoneyone'',SolarType,SiteDB
                                         FROM inverter_history_day a left join 
                                          ( # 每日加總 inv 
                                           select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') report_date, siteid, sitetype, #, round(KWH, 2) KWH, 
                                             round(todayKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                           from power_station_history_day
                                           where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m'') = ''{post.Time}''  
                                          ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'') = b.report_date
                                          left join 
                                          ( # month
                                           select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m'') report_date, sitetype, round(monthKWH, 2) monthKWH,round(KWHKWP, 2) KWHKWP
                                           , round(PR, 2) PR, round(money, 2)  money , round(SOLARHOUR, 2) SOLARHOUR
                                           from power_station_history_month
                                           where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m'') = ''{post.Time}''
                                          ) c on  a.powerStationid = c.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m'') = c.report_date
                                          left join 
                                          (
                                           select powerStationID, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'')report_date, irradiance, Temperature  
                                           from sensor_history_day
                                           where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m'') = ''{post.Time}''  
                                          ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'') = d.report_date
                                          join 
                                          (
                                           select id, name stationName, powerRate,SolarType,SiteDB from power_station where id = {post.PowerStation}
                                          )z on a.powerstationid = z.id          
                                          where DATE_FORMAT(a.TIMESTAMP,''%Y-%m'') = ''{post.Time}''
                                          GROUP BY DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'')
                                          order by DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'')  ');

                                select  @sql as 'mySelect'; #顯示動態語法
                                        #PREPARE stmt FROM @sql; 
                                        #EXECUTE stmt;
                                        #DEALLOCATE PREPARE stmt;";
                            }
                            else
                            {
                                var times = post.Time.Replace('-', 'a').Replace('/', '-').Replace(" ", "").Split('a');

                                sql = @$"SET @sql = NULL;
                                    SELECT
                                      GROUP_CONCAT(DISTINCT
                                        CONCAT('max(case when INVERTERID = ''', INVERTERID, ''' then round(a.KWH, 2) end) ''inv_', right(INVERTERID, 2), '''')
                                      ) INTO @sql
                                    FROM inverter_history_day where powerstationId = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d') BETWEEN '{times[0]}' AND '{times[1]}';
                                SET @sql = CONCAT('SELECT DATE_FORMAT(a.TIMESTAMP,''%m/%d'') report_date, ', @sql, 
                                         ',b.TODAYKWH ''dayKWH'', round((b.TODAYKWH / c.monthKWH)*100,2) ''dayKWHp'', b.SOLARHOUR ''tothour'',  b.KWHKWP ''KWHKWP'', b.PR,
                                  d.irradiance ''irradiance'', d.Temperature ''temperature'', b.money ''soldmoney'', 
                                 c.monthKWH ''monthKWH'', c.money ''monthmoney'',  stationName, powerRate ''monthmoneyone'',SolarType,SiteDB
                                         FROM inverter_history_day a left join 
                                              ( # 每日加總 inv 
                                               select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') report_date, siteid, sitetype, #, round(KWH, 2) KWH, 
                                                 round(todayKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                               from power_station_history_day
                                               where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                              ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'') = b.report_date
                                              left join 
                                              ( # month
                                                SELECT powerStationid, ROUND(AVG(TODAYKWH),2) AS monthKWH,
		                                         ROUND(AVG(KWHKWP),2)  AS KWHKWP,
	  	                                         ROUND(AVG(PR),2) AS PR,
		                                         ROUND(SUM(MONEY),2) AS money,
		                                         ROUND(SUM(SOLARHOUR),2)  AS SOLARHOUR
                                         FROM power_station_history_day where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                              ) c on  a.powerStationid = c.powerStationid 
                                              left join 
                                              (
                                               select powerStationID, DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'')report_date, irradiance, Temperature  
                                               from sensor_history_day
                                               where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                              ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'') = d.report_date
                                              join 
                                              (
                                               select id, name stationName, powerRate, SolarType, SiteDB   from power_station where id = {post.PowerStation}
                                              )z on a.powerstationid = z.id          
                                              where DATE_FORMAT(TIMESTAMP,''%Y-%m-%d'') BETWEEN ''{times[0]}'' AND ''{times[1]}''
                                              GROUP BY DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'')
                                              order by DATE_FORMAT(a.TIMESTAMP,''%Y-%m-%d'')  ');

                                    select  @sql as 'mySelect'; #顯示動態語法
                                        #PREPARE stmt FROM @sql; 
                                        #EXECUTE stmt;
                                        #DEALLOCATE PREPARE stmt;";
                            }
                            break;
                        case 3:
                            sql = @$"
                                SET @sql = NULL;
                                SELECT
                                 GROUP_CONCAT(DISTINCT
                                   CONCAT('max(case when INVERTERID = ''', INVERTERID, ''' then round(a.KWH, 2) end) ''inv_', right(INVERTERID, 2), '''')
                                 ) INTO @sql
                                FROM inverter_history_month where powerstationId = {post.PowerStation} and DATE_FORMAT(`TIMESTAMP`,'%Y') = '{post.Time}';
                                SET @sql = CONCAT('SELECT DATE_FORMAT(a.TIMESTAMP,''%Y/%m'') report_date, ', @sql, 
                                        ',b.todayKWH ''dayKWH'', round((b.todayKWH / c.monthKWH)*100,2) ''dayKWHp'', b.SOLARHOUR ''tothour'',  b.KWHKWP ''KWHKWP'', c.PR,
                                 d.irradiance ''irradiance'', d.Temperature ''temperature'', b.money ''soldmoney'', 
                                c.monthKWH ''monthKWH'', c.money ''monthmoney'',  stationName, powerRate ''monthmoneyone'',SolarType,SiteDB
                                        FROM inverter_history_month a left join 
                                         ( # 每日加總 inv 
                                          select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y-%m'') report_date, siteid, sitetype,
                                            round(MONTHKWH, 2) todayKWH,round(KWHKWP, 2) KWHKWP, round(PR, 2) PR, ifnull(round(money, 2),0) money, round(SOLARHOUR, 2) SOLARHOUR
                                          from power_station_history_month
                                          where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y'') = ''{post.Time}''  
                                         ) b on a.powerStationid = b.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m'') = b.report_date
                                         left join 
                                         ( # month
                                          select powerStationid, DATE_FORMAT(TIMESTAMP,''%Y'') report_date, sitetype,  sum(round(monthKWH, 2)) monthKWH , avg(round(KWHKWP, 2)) KWHKWP
                                          , avg(round(PR, 2)) PR, sum(round(money, 2))  money , sum(round(SOLARHOUR, 2)) SOLARHOUR
                                          from power_station_history_month
                                          where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y'') = ''{post.Time}'' group by DATE_FORMAT(TIMESTAMP,''%Y'')
                                         ) c on  a.powerStationid = c.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y'') = c.report_date
                                         left join 
                                         (
                                          select powerStationID, DATE_FORMAT(TIMESTAMP,''%Y-%m'')report_date, irradiance, Temperature  
                                          from sensor_history_month
                                          where powerstationid = {post.PowerStation} and DATE_FORMAT(TIMESTAMP,''%Y'') = ''{post.Time}''  
                                         ) d on  a.powerStationid = d.powerStationid and DATE_FORMAT(a.TIMESTAMP,''%Y-%m'') = d.report_date
                                         join 
                                         (
                                          select id, name stationName, powerRate,SolarType,SiteDB from power_station where id = {post.PowerStation}
                                         )z on a.powerstationid = z.id          
                                         where DATE_FORMAT(a.TIMESTAMP,''%Y'') = ''{post.Time}''
                                         GROUP BY DATE_FORMAT(a.TIMESTAMP,''%Y-%m'')
                                         order by DATE_FORMAT(a.TIMESTAMP,''%Y-%m'')  ');

                                select  @sql as 'mySelect'; #顯示動態語法
                                        #PREPARE stmt FROM @sql; 
                                        #EXECUTE stmt;
                                        #DEALLOCATE PREPARE stmt;

                                ";

                            break;
                    }
                    a = await conn.QueryAsync<dynamic>(sql,commandTimeout: 600);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return a;
            }
        }

        public async Task<string> GetCompanyNameByPowerStationId(int powerStationId)
        {
            string result;
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = @$"SELECT c.Name
                                FROM power_station ps
                                LEFT JOIN company c ON ps.CompanyId = c.id
                                WHERE ps.id = {powerStationId} AND ps.Deleted = 0";

                    result = await conn.QueryFirstOrDefaultAsync<string>(sql);

                    
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

    }
}
