using GameData;
using ObjectModel.Club;
using Server.DB.Redis;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameData.Club;

namespace GameDAL.Club
{
    /// <summary>
    /// 俱乐部联赛数据逻辑
    /// </summary>
    public static class ClubLeagueMatchDal
    {

        public static readonly string clubMatchKeyPrefix = "ClubLeagueMatch";
        public static readonly DbStyle redisdb = DbStyle.main;
        public static readonly int dbidx = 7;
        static TimeSpan expiry = TimeSpan.FromDays(1);
        
        
        /// <summary>
        /// 获取俱乐部权限
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public static ClubLeaguePower GetClubLeaguePower(int clubId)
        {
            if (clubId <= 0) return null;
            return ClubLeagueMatchAdo.GetClubLeaguePower(clubId);
        }

        /// <summary>
        /// 获取俱乐部权限
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public static Task<ClubLeaguePower> GetClubLeaguePowerAsync(int clubId)
        {
            return ClubLeagueMatchAdo.GetClubLeaguePowerAsync(clubId);
        }

        public static async Task<bool> SaveClubLeaguePowerAsync(ClubLeaguePower leaguePower)
        {
            return await Task.Run(()=>ClubLeagueMatchAdo.SaveClubLeaguePower(leaguePower));
        }

        public static Task SaveBanDesksAsync(List<LeagueMatchBanDesk> list,int matchId)
        {
            return Task.Run(() => SaveBanDesks(list, matchId));
        }

        /// <summary>
        /// 保存联赛禁桌数据，每次删除数据在保存。根据ClubMatchId 删除
        /// </summary>
        /// <param name="list"></param>
        public static void SaveBanDesks(List<LeagueMatchBanDesk> list,int matchId)
        {
            if (list == null || list.Count < 1) return;
            ClubLeagueMatchAdo.SaveBanDesks(list,matchId);
        }

        /// <summary>
        /// 获取联赛禁桌数据
        /// </summary>
        /// <param name="clubMatchId"></param>
        /// <returns></returns>
        public static List<LeagueMatchBanDesk> GetLeagueMatchBanDesks(int clubMatchId)
        {
            if (clubMatchId <= 0) return null;
            return ClubLeagueMatchAdo.GetLeagueMatchBanDesks(clubMatchId);
        }

        public static Task SaveLeagueMatchClubScoreAsync(List<LeagueMatchClubScore> list,int matchId)
        {
            return Task.Run(() => SaveLeagueMatchClubScore(list, matchId));
        }

        /// <summary>
        /// 保存联赛俱乐部统计数据，每次删除数据在保存。根据ClubMatchId 删除
        /// </summary>
        /// <param name="list"></param>
        public static void SaveLeagueMatchClubScore(List<LeagueMatchClubScore> list,int matchId)
        {
            if (list == null || list.Count < 1) return;
            ClubLeagueMatchAdo.SaveLeagueMatchClubScore(list,matchId);
        }

        /// <summary>
        /// 获取联赛俱乐部统计数据
        /// </summary>
        /// <param name="clubMatchId"></param>
        /// <returns></returns>
        public static List<LeagueMatchClubScore> GetLeagueMatchClubScores(int clubMatchId)
        {
            if (clubMatchId <= 0) return null;
            return ClubLeagueMatchAdo.GetLeagueMatchClubScores(clubMatchId);
        }

        /// <summary>
        /// 保存联赛颁奖记录，清空对应clubMatchId比赛的缓存（每次都是新的数据，不用做删除操作）
        /// </summary>
        public static async Task<bool> SaveAwardRecord(long awardId, int leagueClubId, int leagueMatchId, List<AwardRecord> list)
        {
            if (list == null || list.Count < 1) return false;
            var b = await ClubDBUtil.DoLeagueAwardRecord(awardId, leagueClubId, leagueMatchId, list);
            if (b)
            {
                var clubMatchIds = list.Select(p => p.ClubMatchId).Distinct().ToArray();
                var keys1 = clubMatchIds.Select(p => GetAwardRecordListKey(p));
                var keys2 = clubMatchIds.Select(p => GetAwardRecordKey(p));
                var keys3 = clubMatchIds.Select(p => GetAwardRecordListByDateKey(p));
                _ = redisdb.DeleteAsync(dbidx, keys1.Concat(keys2).Concat(keys3).ToArray());
            }
            return b;
        }

        // /// <summary>
        // /// 获取联赛颁奖记录 近几条
        // /// </summary>
        // /// <param name="clubMatchId"></param>
        // /// <param name="topNum"></param>
        // /// <returns></returns>
        // public static AwardRecord GetAwardByTop(int clubMatchId, int topNum = 1)
        // {
        //     if (clubMatchId <= 0) return null;
        //     var result = redisdb.GetOrAdd(RedisType.String, GetAwardRecordKey(clubMatchId), () =>
        //     {
        //         return ClubLeagueMatchAdo.GetAwardByTop(clubMatchId, topNum) ?? new AwardRecord();
        //     }, dbidx, expiry);
        //     return result.AwardRecordId != 0 ? result : null;
        // }

        #if Server
        /// <summary>
        /// 获取联赛颁奖记录。根据主键id倒序
        /// </summary>
        /// <param name="clubMatchId">比赛Id</param>
        /// <param name="dateTime"> CreateTime>dateTime </param>
        /// <returns></returns>
        public static List<AwardRecord> GetAwardRecords(int clubMatchId, DateTime dateTime)
        {
            if (clubMatchId <= 0) return null;
            return redisdb.GetOrAdd(GetAwardRecordListByDateKey(clubMatchId), dateTime.ToString("yyyyMMddHHmmss"), () =>
                 ClubLeagueMatchAdo.GetAwardRecords(clubMatchId, dateTime)
            , dbidx, expiry);
        }
        
        public static FightScore GetFightScorebyId(int id)
        {
            return DbStyle.bisai.GetOrAdd(RedisType.String, GetFightScoreByIdKey(id), () =>
                 ClubDataManager.GetFightScoreById(id)
            , dbidx, TimeSpan.FromMinutes(30));
        }
        
        
        #endif

        static RedisKey GetFightScoreByIdKey(int id)
        {
            return $"GetFightScores:id:{id}";
        }

        static RedisKey GetAwardRecordListByDateKey(int clubMatchId)
        {
            return $"{clubMatchKeyPrefix}:AwardRecordListBydate:{clubMatchId}";
        }

        /// <summary>
        /// 获取联赛颁奖记录。根据主键id倒序,根据比赛：clubMatchId缓存 时间1天
        /// </summary>
        /// <param name="clubMatchId"></param>
        /// <returns></returns>
        public static List<AwardRecord> GetAwardRecords(int clubMatchId)
        {
            if (clubMatchId <= 0) return null;
            return redisdb.GetOrAdd(RedisType.String, GetAwardRecordListKey(clubMatchId),
                () => ClubLeagueMatchAdo.GetAwardRecords(clubMatchId)
            , dbidx, expiry);
        }

        static RedisKey GetAwardRecordListKey(int clubMatchId)
        {
            return $"{clubMatchKeyPrefix}:AwardRecordList:{clubMatchId}";
        }

        static RedisKey GetAwardRecordKey(int clubMatchId)
        {
            return $"{clubMatchKeyPrefix}:AwardRecord:{clubMatchId}";
        }

        public static Task SaveLeagueClubLiveTasksAsync(List<LeagueClubLiveTask> list,int matchId)
        {
            return Task.Run(() => SaveLeagueClubLiveTasks(list, matchId));
        }

        /// <summary>
        /// 保存生存任务，先删除再保存
        /// </summary>
        /// <param name="lists"></param>
        public static void SaveLeagueClubLiveTasks(List<LeagueClubLiveTask> list,int matchId)
        {
            if (list == null || list.Count < 1) return;
            ClubLeagueMatchAdo.SaveLeagueClubLiveTasks(list,matchId);
        }

        /// <summary>
        /// 保存加入到联赛的俱乐部集合
        /// </summary>
        /// <param name="model"></param>
        public static void SaveJoinInClubLeagueMatch(JoinInClubLeagueMatch model)
        {
            if (model == null) return;
            ClubLeagueMatchAdo.SaveJoinInClubLeagueMatch(model);
        }

        // /// <summary>
        // /// 获取 保存加入到联赛的俱乐部集合 对象
        // /// </summary>
        // /// <param name="clubMatchId"></param>
        // /// <returns></returns>
        // public static JoinInClubLeagueMatch GetJoinInClubLeagueMatch(int clubMatchId)
        // {
        //     if (clubMatchId <= 0) return null;
        //     return ClubLeagueMatchAdo.GetJoinInClubLeagueMatch(clubMatchId);
        // }

        static string GetLeagueAdminClubsKey(int clubId)
        {
            return $"GetLeagueAdminClubsKey:{clubId}";
        }

        #if Server
        /// <summary>
        /// 保存联赛俱乐部管理员
        /// </summary>
        public static void SaveLeagueAdminClubs(int clubId, List<LeagueAdminClub> data)
        {
            if (clubId <= 0 || data == null) return;
            var key = GetLeagueAdminClubsKey(clubId);
            var str = JsonPack.GetJson(data);
            redisManager.GetBiSaidb(6).StringSet(key, str, TimeSpan.FromDays(365)); //数据缓存一年
        }

        /// <summary>
        /// 获取联赛管理员列表
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public static List<LeagueAdminClub> GetLeagueAdminClubs(int clubId)
        {
            var result = new List<LeagueAdminClub>();
            if (clubId <= 0) return result;
            var key = GetLeagueAdminClubsKey(clubId);
            string str = redisManager.GetBiSaidb(6).StringGet(key);
            if (!string.IsNullOrWhiteSpace(str) && str.Length > 2)
            {
                return JsonPack.GetData<List<LeagueAdminClub>>(str);
            }
            return result;
        }
        #endif
    }
}
