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");
                                sql = $@"SELECT m.*,n.* FROM
                                        (
                                            SELECT AVG(KWHKWP) AS All_KWH_KWP ,SUM(TOTALMONEY) AS All_money,
                                            SUM(TOTALKWH) AS All_kwh,SUM(TOTALCARBON) AS All_Carbon,
                                            AVG(PR) AS All_PR 
                                            from power_station_history_month
                                            WHERE PowerStationId IN @ids
                                        ) 
                                        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";
                                break;
                            case 1:
                                var time = post.Timerange.Split('-');
                                sql = $@"SELECT m.*,n.* FROM
                                        (
                                            SELECT AVG(KWHKWP) AS All_KWH_KWP, SUM(TOTALMONEY) AS All_money,
                                            SUM(TOTALKWH) AS All_kwh, SUM(TOTALCARBON) AS All_Carbon,
                                            AVG(PR) AS All_PR
                                            from power_station_history_month
                                            WHERE PowerStationId IN @ids
                                        )
                                        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";
                                break;
                            case 2:
                                sql = $@"SELECT m.*,n.* FROM
                                         (
                                            SELECT 
                                            AVG(KWHKWP) AS All_KWH_KWP,
                                            SUM(TOTALMONEY) AS All_money,
                                            SUM(TOTALKWH) AS All_kwh,
                                            SUM(TOTALCARBON) AS All_Carbon,
                                            AVG(PR) AS All_PR
                                            from power_station_history_month
                                            WHERE PowerStationId IN @ids
                                         )
                                         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";
                                break;
                            case 3:
                                sql = $@"SELECT m.*,n.* FROM
                                         (
                                             SELECT AVG(KWHKWP) AS All_KWH_KWP, SUM(TOTALMONEY) AS All_money,
                                             SUM(TOTALKWH) AS All_kwh, SUM(TOTALCARBON) AS All_Carbon,
                                             AVG(PR) AS All_PR
                                             from power_station_history_month
                                             WHERE PowerStationId IN @ids
                                         )
                                         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";
                                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(ps.TIMESTAMP,'%h %p') AS `Time`,SUM(ps.KWH) AS KWH,SUM(sh.Irradiance) AS Irradiance 
                                        FROM power_station_history_hour ps 
                                        LEFT JOIN sensor_history_hour sh 
                                        ON sh.TIMESTAMP = ps.TIMESTAMP AND sh.PowerStationId = ps.PowerStationId
                                        WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') = '{post.Timerange}'
                                        GROUP BY ps.TIMESTAMP";
                                break;
                            case 1:
                                var time = post.Timerange.Replace(" ","").Split('-');
                                sql = $@"SELECT 
                                        DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS `Time`,
                                        SUM(ps.TODAYKWH) AS KWH,
                                        SUM(sh.Irradiance) AS Irradiance
                                        FROM power_station_history_day ps
                                        LEFT JOIN sensor_history_day sh 
                                        ON sh.TIMESTAMP = ps.TIMESTAMP
                                        WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m-%d') BETWEEN '{time[0].Replace('/', '-')}' AND '{time[1].Replace('/', '-')}'
                                        GROUP BY ps.TIMESTAMP";
                                break;
                            case 2:
                                sql = $@"SELECT 
                                        DATE_FORMAT(ps.TIMESTAMP,'%Y-%m-%d') AS `Time`,
                                        SUM(ps.TODAYKWH) AS KWH,
                                        SUM(sh.Irradiance) AS Irradiance
                                        FROM power_station_history_day ps
                                        LEFT JOIN sensor_history_day sh 
                                        ON sh.TIMESTAMP = ps.TIMESTAMP
                                        WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y-%m') = '{post.Timerange}'
                                        GROUP BY ps.TIMESTAMP";
                                break;
                            case 3:
                                sql = $@"SELECT 
                                        DATE_FORMAT(ps.TIMESTAMP,'%Y-%m') AS `Time`,
                                        SUM(ps.MONTHKWH) AS KWH,
                                        SUM(sh.Irradiance) AS Irradiance
                                        FROM power_station_history_month ps
                                        LEFT JOIN sensor_history_month sh 
                                        ON sh.TIMESTAMP = ps.TIMESTAMP
                                        WHERE ps.PowerStationId IN @ids AND DATE_FORMAT(sh.TIMESTAMP,'%Y') = '{post.Timerange}'
                                        GROUP BY ps.TIMESTAMP";
                                break;
                        }
                        a = (await conn.QueryAsync<Chartoutput>(sql,new { ids = post.StationIds})).ToList();


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

    }
}
