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 NoticeScheduleRepository : RepositoryBase<NoticeSchedule>, INoticeScheduleRepository
    {
        public NoticeScheduleRepository(IDatabaseHelper databaseHelper) : base(databaseHelper)
        {
            tableName = "notice_schedule";
        }

        public async Task<List<NoticeSchedule>> GetNotYetDelivery()
        {
            List<NoticeSchedule> result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                try
                {
                    var sql = $"SELECT * FROM {tableName} WHERE IsDelivery = 0";

                    result = (await conn.QueryAsync<NoticeSchedule>(sql)).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                return result;
            }
        }

        public async Task UpdateList(List<NoticeSchedule> noticeSchedules, List<string> properties)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        var sql = GenerateUpdateQuery(properties);

                        await conn.ExecuteAsync(sql, noticeSchedules, trans);

                        trans.Commit();
                    }
                    catch (Exception exception)
                    {
                        trans.Rollback();
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }

        public async Task<List<OperationPersonnel>> GetPowerStationOperationPersonnel(int Userid)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                var result = new List<OperationPersonnel>();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        var sql = $@"SELECT p.*,ps.Name FROM power_station_operation_personnel p 
                                    LEFT JOIN power_station ps ON p.PowerStationId = ps.Id   
                                    WHERE p.UserId = {Userid} AND p.Deleted = 0 and ps.Deleted = 0 and ps.Status = 1";

                        result = (await conn.QueryAsync<OperationPersonnel>(sql)).ToList();

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

        public async Task<List<NoticeScheduleTable>> GetNoticeTable(NoticeTableSearch info)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                var result = new List<NoticeScheduleTable>();
                using (var trans = conn.BeginTransaction())
                {
                    var EmailType = info.FormType switch
                    {
                        99 => $"",
                        _ => $"AND ns.EmailType = {info.FormType}"
                    };
                    var IsDelivery = info.CheckType switch
                    {
                        0 => $"AND ns.IsDelivery != 0",
                        1 => $"AND ns.IsDelivery = 1",
                        2 => $"AND ns.IsDelivery = 2",
                        _ => $"",
                    };
                    string time=""; 
                    switch(info.TimeType)
                    {
                        case 0:
                            time = $"AND DATE_FORMAT(ns.DeliveryAt,'%Y-%m-%d') = '{info.TimeRange}'";
                            break;
                        case 1:
                            var timechange = info.TimeRange.Replace(" ", "").Split("-");
                            time = $"AND DATE_FORMAT(ns.DeliveryAt,'%Y/%m/%d') between '{timechange[0]}' and '{timechange[1]}'";
                            break;
                        case 2:
                            time = $"AND DATE_FORMAT(ns.DeliveryAt,'%Y-%m') = '{info.TimeRange}'";
                            break;
                        case 3:
                            time = $"AND DATE_FORMAT(ns.DeliveryAt,'%Y') = '{info.TimeRange}'";
                            break;
                    }

                    try
                    {
                        var sql = $@"SELECT psp.PowerStationId,ns.`*` 
                                    FROM power_station_operation_personnel psp
                                    LEFT JOIN notice_schedule ns
                                    ON ns.UserId = psp.UserId 
                                    WHERE psp.PowerStationId IN @ids
                                    AND psp.Deleted = 0 
                                    {EmailType} {IsDelivery} {time}
                                    GROUP BY ns.Id ORDER BY ns.DeliveryAt desc";

                        result = (await conn.QueryAsync<NoticeScheduleTable>(sql,new { ids = info.PowerstationIds})).ToList();

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

        public async Task<string> GetCompanyNameById(int noticeId)
        {
            string result;
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = @$"select c.Name
                                from notice_schedule ns   
                                left join user u on ns.UserId = u.id
                                left join company c on u.CompanyId = c.id
                                where ns.id = {noticeId}";

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


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

    }
}
