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;

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



        public async Task<AnalysisStationCombine> GetPowerStationInfoList(ChartInput post)
        {
            var a = new AnalysisStationCombine();
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        string sql = "";
                        switch(post.SeacrhType)
                        {
                            case 0:
                                string timerange = Convert.ToDateTime(post.Timerange).ToString("yyyy-MM-dd");
                                var today = "";
                                if(timerange == DateTime.Now.ToString("yyyy-MM-dd"))
                                {
                                    today = @$" SELECT 
                                                AVG(a.today_irradiance) AS Now_irradiance
                                                FROM
                                                power_station a
                                                WHERE a.Id IN @ids ";
                                }
                                else
                                {
                                    today = $@" SELECT 
                                                AVG(a.Irradiance) AS Now_irradiance
                                                FROM
                                                sensor_history_day a
                                                WHERE a.PowerStationId IN @ids AND DATE_FORMAT(a.TIMESTAMP,'%Y-%m-%d') = '{timerange}'";
                                }


                                sql = $@"SELECT m.*,n.*,o.*,p.* FROM
                                        (
                                            SELECT 
                                             SUM(TOTALMONEY) AS All_money,
                                             SUM(TOTALKWH) AS All_kwh,
                                             SUM(TOTALCARBON) AS All_Carbon
                                             from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
                                             LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
                                        ) 
                                        AS m,
                                        (
                                            SELECT 
                                            SUM(b.TODAYKWH) AS Now_kwh,
                                            SUM(b.TODAYMONEY) AS Now_money,
                                            AVG(b.KWHKWP) AS Now_KWH_KWP ,
                                            AVG(b.PR) AS Now_PR,
                                            SUM(b.TODAYCARBON) AS Now_Carbon
                                            FROM (SELECT MAX(a.`TIMESTAMP`) AS maxTIMESTAMP FROM 
                                            (SELECT * FROM power_station_history_hour hr WHERE DATE_FORMAT(hr.`TIMESTAMP`,'%Y-%m-%d') = '{timerange}') a ) c
                                            LEFT JOIN 
                                            (SELECT * FROM power_station_history_hour hr WHERE DATE_FORMAT(hr.`TIMESTAMP`,'%Y-%m-%d') = '{timerange}' ) b
                                            ON c.maxTIMESTAMP = b.`TIMESTAMP`
                                            WHERE PowerStationId IN @ids
                                        )
                                        AS n,
                                         (
                                             SELECT 
                                             AVG(avg_kwhkwp) AS All_KWH_KWP,
                                             AVG(avg_PR) AS All_PR,
                                             AVG(avg_irradiance) as All_irradiance
                                             from power_station
                                             WHERE Id IN @ids
                                         ) 
                                         AS o,
                                         (
		                                    {today}
                                         ) AS p";
                                break;
                            case 1:
                                var time = post.Timerange.Split('-');
                                var ttot = "";
                                if(time[1].Replace(" ","") == DateTime.Now.ToString("yyyy/MM/dd"))
                                {
                                    ttot = @$"SELECT 
                                            AVG(c.Now_irradiance) AS Now_irradiance
                                            FROM 
                                            (SELECT AVG(a.today_irradiance) AS Now_irradiance FROM power_station a WHERE a.Id IN (1)
                                            UNION 
                                            SELECT AVG(b.Irradiance) AS Now_irradiance FROM sensor_history_day b 
                                            WHERE b.PowerStationId IN (1) AND DATE_FORMAT(b.TIMESTAMP, '%Y/%m/%d') BETWEEN '{time[0].Replace(" ", "")}' AND '{Convert.ToDateTime(time[1].Replace(" ", "")).AddDays(-1).ToString("yyyy/MM/dd")}') c";
                                }
                                else
                                {
                                    ttot = @$" SELECT 
                                                AVG(a.Irradiance) AS Now_irradiance
                                                FROM
                                                sensor_history_day a
                                                WHERE a.PowerStationId IN @ids AND DATE_FORMAT(a.TIMESTAMP, '%Y/%m/%d') BETWEEN '{time[0].Replace(" ", "")}' AND '{time[1].Replace(" ", "")}'";
                                }


                                sql = $@"SELECT m.*,n.*,o.*,p.* FROM
                                        (
                                            SELECT 
                                             SUM(TOTALMONEY) AS All_money,
                                             SUM(TOTALKWH) AS All_kwh,
                                             SUM(TOTALCARBON) AS All_Carbon
                                             from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
                                             LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
                                        )
                                        AS m,
                                        (
                                            SELECT
                                            SUM(b.TODAYKWH) AS Now_kwh,
                                            SUM(b.MONEY) AS Now_money,
                                            AVG(b.KWHKWP) AS Now_KWH_KWP,
                                            AVG(b.PR) AS Now_PR,
                                            SUM(b.CARBON) AS Now_Carbon
                                            FROM power_station_history_day b
                                            WHERE PowerStationId IN @ids AND TIMESTAMP BETWEEN '{time[0]}' AND '{time[1]}'
                                        )
                                        AS n,
                                         (
                                             SELECT 
                                             AVG(avg_kwhkwp) AS All_KWH_KWP,
                                             AVG(avg_PR) AS All_PR,
                                             AVG(avg_irradiance) as All_irradiance
                                             from power_station
                                             WHERE Id IN @ids
                                         ) 
                                         AS o,
                                         (
		                                    {ttot}
                                         ) AS p";
                                break;
                            case 2:
                                sql = $@"SELECT m.*,n.*,o.*,p.* FROM
                                         (
                                            SELECT 
                                             SUM(TOTALMONEY) AS All_money,
                                             SUM(TOTALKWH) AS All_kwh,
                                             SUM(TOTALCARBON) AS All_Carbon
                                             from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
                                             LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
                                         )
                                         AS m,
                                         (
                                            SELECT
                                            SUM(b.TODAYKWH) AS Now_kwh,
                                            SUM(b.MONEY) AS Now_money,
                                            AVG(b.KWHKWP) AS Now_KWH_KWP,
                                            AVG(b.PR) AS Now_PR,
                                            SUM(b.CARBON) AS Now_Carbon
                                            FROM power_station_history_day b
                                            WHERE PowerStationId IN @ids AND DATE_FORMAT(TIMESTAMP, '%Y-%m') = '{post.Timerange}'
                                         )
                                         AS n,
                                         (
                                             SELECT 
                                             AVG(avg_kwhkwp) AS All_KWH_KWP,
                                             AVG(avg_PR) AS All_PR,
                                             AVG(avg_irradiance) as All_irradiance
                                             from power_station
                                             WHERE Id IN @ids
                                         ) 
                                         AS o,
                                         (
                                             SELECT 
                                             AVG(a.Irradiance) AS Now_irradiance
                                             from sensor_history_month a
                                             WHERE PowerStationId IN @ids AND DATE_FORMAT(TIMESTAMP, '%Y-%m') = '{post.Timerange}'
                                         ) AS p";
                                break;
                            case 3:
                                sql = $@"SELECT m.*,n.*,o.*,p.* FROM
                                         (
                                             SELECT 
                                             SUM(TOTALMONEY) AS All_money,
                                             SUM(TOTALKWH) AS All_kwh,
                                             SUM(TOTALCARBON) AS All_Carbon
                                             from (SELECT psm.PowerStationId, max(psm.TIMESTAMP) AS TIMESTAMP FROM power_station_history_month psm WHERE PowerStationId IN @ids GROUP BY PowerStationId) a
                                             LEFT JOIN power_station_history_month psm ON a.PowerStationId = psm.PowerStationId AND a.TIMESTAMP = psm.TIMESTAMP
                                         )
                                         AS m,
                                         (
                                           SELECT

                                            SUM(b.MONTHKWH) AS Now_kwh,
                                            SUM(b.MONEY) AS Now_money,
                                            AVG(b.KWHKWP) AS Now_KWH_KWP,
                                            AVG(b.PR) AS Now_PR,
                                            SUM(b.CARBON) AS Now_Carbon
                                            FROM power_station_history_month b
                                            WHERE PowerStationId IN @ids AND DATE_FORMAT(TIMESTAMP, '%Y') = '{post.Timerange}'
                                         )
                                         AS n,
                                         (
                                             SELECT 
                                             AVG(avg_kwhkwp) AS All_KWH_KWP,
                                             AVG(avg_PR) AS All_PR,
                                             AVG(avg_irradiance) as All_irradiance
                                             from power_station
                                             WHERE Id IN @ids
                                         ) 
                                         AS o,
                                         (
                                             SELECT 
                                             AVG(a.Irradiance) AS Now_irradiance
                                             from sensor_history_month a
                                             WHERE PowerStationId IN @ids AND DATE_FORMAT(TIMESTAMP, '%Y') = '{post.Timerange}'
                                         ) AS p";
                                break;
                        }

                        a = await conn.QueryFirstOrDefaultAsync<AnalysisStationCombine>(sql,new { ids = post.StationIds});
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return a;
        }

        public async Task<List<Chartoutput>> GetChart(ChartInput post)
        {
            var a = new List<Chartoutput>();
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        string sql = "";
                        switch (post.SeacrhType)
                        {
                            case 0:
                                sql = $@"SELECT DATE_FORMAT(p.TIMESTAMP,'%h %p') AS `Time`,
                                        SUM(p.KWH) AS KWH,
                                        SUM(s.Irradiance) AS Irradiance,
                                        AVG(s.Temperature) AS Temperature
                                        FROM (SELECT * FROM power_station_history_hour ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') = '{post.Timerange}') p
                                        LEFT JOIN (SELECT * FROM sensor_history_hour sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') = '{post.Timerange}') s
                                        ON p.TIMESTAMP = s.TIMESTAMP AND p.PowerStationId = s.PowerStationId
                                        GROUP BY p.TIMESTAMP";
                                break;
                            case 1:
                                var time = post.Timerange.Replace(" ","").Split('-');
                                sql = $@"SELECT 
                                        DATE_FORMAT(p.TIMESTAMP,'%Y-%m-%d') AS `Time`,
                                        SUM(p.TODAYKWH) AS KWH,
                                        SUM(s.Irradiance) AS Irradiance,
                                        AVG(s.Temperature) AS Temperature
                                        FROM (SELECT * FROM power_station_history_day ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') BETWEEN '{time[0].Replace('/', '-')}' AND '{time[1].Replace('/', '-')}') p
                                        LEFT JOIN (SELECT * FROM sensor_history_day sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') BETWEEN '{time[0].Replace('/', '-')}' AND '{time[1].Replace('/', '-')}') s
                                        ON s.TIMESTAMP = p.TIMESTAMP AND p.PowerStationId = s.PowerStationId
                                        GROUP BY p.TIMESTAMP";
                                break;
                            case 2:
                                sql = $@"SELECT 
                                        DATE_FORMAT(p.TIMESTAMP,'%Y-%m-%d') AS `Time`,
                                        SUM(p.TODAYKWH) AS KWH,
                                        SUM(s.Irradiance) AS Irradiance,
                                        AVG(s.Temperature) AS Temperature
                                        FROM (SELECT * FROM power_station_history_day ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y-%m') = '{post.Timerange}') p
                                        LEFT JOIN (SELECT * FROM sensor_history_day sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m') = '{post.Timerange}') s
                                        ON s.TIMESTAMP = p.TIMESTAMP AND p.PowerStationId = s.PowerStationId
                                        GROUP BY p.TIMESTAMP";
                                break;
                            case 3:
                                sql = $@"SELECT 
                                        DATE_FORMAT(p.TIMESTAMP,'%Y-%m') AS `Time`,
                                        SUM(p.MONTHKWH) AS KWH,
                                        SUM(s.Irradiance) AS Irradiance,
                                        AVG(s.Temperature) AS Temperature
                                        FROM (SELECT * FROM power_station_history_month ps WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(ps.TIMESTAMP,'%Y') = '{post.Timerange}') p
                                        LEFT JOIN (SELECT * FROM sensor_history_month sh WHERE sh.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y') = '{post.Timerange}') s
                                        ON s.TIMESTAMP = p.TIMESTAMP AND p.PowerStationId = s.PowerStationId
                                        GROUP BY p.TIMESTAMP";
                                break;
                        }
                        a = (await conn.QueryAsync<Chartoutput>(sql,new { ids = post.StationIds})).ToList();
                    }
                    catch (Exception exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return a;
        }

    }
}
