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 ElectricitySoldRecordRepository: RepositoryBase<ElectricitySoldRecord>, IElectricitySoldRecordRepository
    {
        public ElectricitySoldRecordRepository(IDatabaseHelper databaseHelper) : base(databaseHelper)
        {
            tableName = "electricity_sold_record";
        }
        public async Task<List<ElectricitySoldRecordTable>> RecordTable (ElectricitySoldRecordTablePost post)
        {
            
            string sql = "";
            List<int> ids = new List<int>();
            foreach(var id in post.StationId)
            {
                ids.Add(Convert.ToInt32(id.Value));
            }


            switch (post.SearchType)
            {
                case 0:
                    post.Time = post.Time.Replace(" ", "");
                    post.Time = post.Time.Replace("-", "~");
                    post.Time = post.Time.Replace("/", "-");
                    var time = post.Time.Split("~");
                    sql = @$"SELECT es.*,ps.Name AS PowerStationName FROM electricity_sold_record es 
                            LEFT JOIN power_station ps ON es.PowerstationId = ps.Id                            
                            WHERE es.StartAt BETWEEN '{time[0]}' AND '{time[1]}' AND es.PowerstationId IN @ids AND es.Deleted = 0";
                    break;
                case 1:
                    post.Time = post.Time.Replace(" ", "");
                    post.Time = post.Time.Replace("-", "~");
                    post.Time = post.Time.Replace("/", "-");
                    var time1 = post.Time.Split("~");
                    sql = @$"SELECT es.*,ps.Name AS PowerStationName FROM electricity_sold_record es 
                            LEFT JOIN power_station ps ON es.PowerstationId = ps.Id                            
                            WHERE es.StartAt BETWEEN '{time1[0]}' AND '{time1[1]}' AND es.PowerstationId IN @ids AND es.Deleted = 0";
                    break;
                case 2:
                    sql = @$"SELECT es.*,ps.Name AS PowerStationName FROM electricity_sold_record es 
                            LEFT JOIN power_station ps ON es.PowerstationId = ps.Id
                            WHERE DATE_FORMAT(es.StartAt , '%Y-%m') = '{post.Time}' AND es.PowerstationId IN @ids AND es.Deleted = 0";
                    break;
                case 3:
                    sql = @$"SELECT es.*,ps.Name AS PowerStationName FROM electricity_sold_record es 
                            LEFT JOIN power_station ps ON es.PowerstationId = ps.Id
                            WHERE DATE_FORMAT(es.StartAt , '%Y') = '{post.Time}' AND es.PowerstationId IN @ids AND es.Deleted = 0";
                    break;
            }
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                List<ElectricitySoldRecordTable> a = new List<ElectricitySoldRecordTable>();
                try
                {
                    a = (await conn.QueryAsync<ElectricitySoldRecordTable>(sql,new { ids = ids})).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                return a;
            }
            
        }

        public async Task<BillInfo> GetBill (int id)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                BillInfo a = new BillInfo();
                try
                {
                    var sql = @$"SELECT es.Money,ps.GUINumber,ps.TPCInvoiceBuyer,ps.TPCInvoiceAddress, ps.TPCMeterNumber,cp.Name,cp.Logo,ps.Id,
                                es.StartAt,es.EndAt,es.Kwh,ps.PowerRate,ps.Name as PowerName
                                FROM electricity_sold_record es 
                                LEFT JOIN power_station ps 
                                ON es.PowerstationId = ps.Id
                                LEFT JOIN company cp 
                                ON cp.Id = ps.CompanyId
                                WHERE es.Id = {id}";


                    a = await conn.QueryFirstOrDefaultAsync<BillInfo>(sql);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                return a;
            }
        }

        public async Task<List<Generation>> GetGenerationList (SearchGeneration info)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                List<Generation> a = new List<Generation>();
                try
                {
                    var sqlwhere = (info.DateType) switch
                    {
                        0 => $"DATE_FORMAT(er.StartAt,'%Y-%m') = '{info.Date}'",//月
                        _ => $"DATE_FORMAT(er.StartAt,'%Y') = '{info.Date}'"//年
                    };



                    var sql = @$"SELECT aa.StartAt,aa.EndAt,aa.Kwh actualkwh,aa.Money actualMoney,SUM(pd.TODAYKWH) realKWH,SUM(pd.MONEY) realMoney,ps.Estimate_kwh CBAkwh,ps.EstimateEfficacy CBAeff ,ps.GeneratingCapacity capacity ,ps.PowerRate rate
                                FROM power_station_history_day pd 
                                LEFT JOIN ( SELECT er.* FROM electricity_sold_record er WHERE {sqlwhere} AND er.Deleted = 0 ) aa
                                ON aa.PowerstationId = pd.PowerStationId
                                LEFT JOIN power_station ps ON ps.Id = pd.PowerStationId
                                WHERE pd.TIMESTAMP BETWEEN aa.StartAt AND aa.EndAt AND ps.Id = {info.PowerstationId} GROUP BY aa.Id";


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