using AgileConfig.Client;

using CloudGaming.Code.DataAccess;
using CloudGaming.Code.DataAccess.MultiTenantUtil;
using CloudGaming.DtoModel.Account.User;
using CloudGaming.DtoModel.Game;
using CloudGaming.DtoModel.JY;
using CloudGaming.DtoModel.PlayGame;

using HuanMeng.DotNetCore.Redis;

using Newtonsoft.Json;

using StackExchange.Redis;

using System.Runtime.CompilerServices;

namespace CloudGaming.Code.Game
{
    public static class PlayGameExtend
    {

        /// <summary>
        /// 初始化游戏服务
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IHostApplicationBuilder AddPlayGameServer(this WebApplicationBuilder builder)
        {

            builder.Services.AddHostedService<PlayGameService>();
            return builder;

        }

        public static string GetPlayGameKeyPrefix { get; set; } = $"PlayGame";
        /// <summary>
        /// 
        /// </summary>
        /// <param name="gameId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string GetPlayGameKey(string gameId, int userId) => $"PlayGame:{gameId}:{userId}";
        /// <summary>
        /// 获取用户游戏缓存
        /// </summary>
        /// <param name="cloudGamingBase"></param>
        /// <param name="userInfo"></param>
        /// <param name="gameInfo"></param>
        /// <returns></returns>
        public static async Task<PlayGameUserInfo> GetPlayGameUserInfoCacheAsync(CloudGamingBase cloudGamingBase, UserInfo userInfo, GameInfo gameInfo, IJYApiRespnse? jYApiRespnse = null)
        {
            var redisGameKey = GetPlayGameKey(gameInfo.GameId, userInfo.UserId);
            var gameInfoCache = await cloudGamingBase.RedisCache.StringGetAsync<PlayGameUserInfo>(redisGameKey);
            if (gameInfoCache == null)
            {
                gameInfoCache = new PlayGameUserInfo()
                {
                    GameId = gameInfo.GameId,
                    GameName = gameInfo.GameName,
                    GameStatus = PlayGameStatus.初始化,
                    CreateDateTime = DateTime.Now,
                    GameUserOperation = new List<PlayGameUserOperation>(),
                    UserId = userInfo.UserId,
                    UserPlayGameDiamonds = userInfo.Diamond,
                    SessionId = Guid.NewGuid().ToString("N"),
                };
                gameInfoCache.GameUserOperation.Add(new PlayGameUserOperation()
                {
                    Content = $"初始化游戏，用户剩余钻石{userInfo.Diamond}",
                    ActionId = (int)PlayGameStatus.初始化,
                    OperationDateTime = DateTime.Now,
                });
            }
            return gameInfoCache;
        }

        /// <summary>
        /// 获取用户游戏缓存
        /// </summary>
        /// <param name="cloudGamingBase"></param>
        /// <param name="userInfo"></param>
        /// <param name="gameInfo"></param>
        /// <returns></returns>
        public static async Task<PlayGameUserInfo> GetPlayGameUserInfoOrNull(CloudGamingBase cloudGamingBase, UserInfo userInfo, GameInfo gameInfo)
        {
            var redisGameKey = GetPlayGameKey(gameInfo.GameId, userInfo.UserId);
            var gameInfoCache = await cloudGamingBase.RedisCache.StringGetAsync<PlayGameUserInfo>(redisGameKey);
            return gameInfoCache;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="playGameSettings">开始游戏设置</param>
        /// <returns></returns>
        public static bool InitStartPlayGame(this PlayGameUserInfo playGameUserInfo, PlayGameSettings playGameSettings)
        {
            playGameUserInfo.JyGameId = playGameSettings.GameKey;
            playGameUserInfo.Sn = playGameSettings.Sn;
            playGameUserInfo.ModelName = playGameSettings.ModelName;
            playGameUserInfo.Cpu = playGameSettings.Cpu;
            playGameUserInfo.QueueGrade = playGameSettings.QueueGrade;
            playGameUserInfo.DisplayGrade = playGameSettings.DisplayGrade;
            if (playGameUserInfo.GameStatus == PlayGameStatus.初始化)
            {
                playGameUserInfo.GameStatus = PlayGameStatus.启动游戏;
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
                {
                    Content = $"启动游戏",
                    ActionId = (int)PlayGameStatus.启动游戏,
                    OperationDateTime = DateTime.Now,
                });
            }
            return true;
        }

        /// <summary>
        /// 结束游戏
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="sn"></param>
        /// <param name="modenName"></param>
        /// <param name="cpu"></param>
        /// <returns></returns>
        public static bool ExitPlayGame(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse, ExitPlayGameRequest gameRequest)
        {

            if (playGameUserInfo.GameStatus != PlayGameStatus.用户主动结束游戏)
            {
                playGameUserInfo.GameStatus = PlayGameStatus.用户主动结束游戏;
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
                {
                    OperationDateTime = DateTime.Now,
                    Content = "用户主动结束游戏",
                    ActionId = (int)PlayGameStatus.用户主动结束游戏,
                });
                if (!string.IsNullOrEmpty(gameRequest.PlayGameDetails))
                {
                    playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
                    {
                        OperationDateTime = DateTime.Now,
                        Content = "用户玩游戏情况",
                        ActionId = (int)PlayGameStatus.游戏状态,
                        RequestContent = gameRequest.PlayGameDetails ?? ""
                    });
                }
                playGameUserInfo.LastDateTime = DateTime.Now;
            }
            return true;
        }

        /// <summary>
        /// 开始游戏
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="scId">本次游戏连接会话 id</param>
        /// <param name="gameListId">游戏记录id</param>
        /// <param name="display_grade">游戏显示等级</param>
        /// <param name="jYApiRespnse">请求信息</param>
        /// <returns></returns>
        public static bool PlayGameStart(this PlayGameUserInfo playGameUserInfo, int scId, int gameListId, int display_grade, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.开始游戏;
            playGameUserInfo.GameListId = gameListId;
            playGameUserInfo.ScId = scId;
            playGameUserInfo.DisplayGrade = display_grade;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                Content = $"游戏启动成功，开始游戏（scId：{scId}）；",
                OperationDateTime = DateTime.Now,
                ActionId = (int)PlayGameStatus.开始游戏
            });
            playGameUserInfo.PlayGameStartAt = DateTime.Now;
            playGameUserInfo.PlayGameHeartbeatAt = DateTime.Now;
            playGameUserInfo.LastChargingAt = DateTime.Now;
            return true;
        }

        /// <summary>
        /// 游戏启动失败
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameError(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.游戏启动失败;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                OperationDateTime = DateTime.Now,
                Content = "启动游戏失败；",
                ActionId = (int)PlayGameStatus.游戏启动失败
            });
            return true;
        }


        /// <summary>
        /// 游戏心跳
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameHeartbeat(this PlayGameUserInfo playGameUserInfo, string desc = "")
        {
            if (playGameUserInfo.GameStatus != PlayGameStatus.游戏中)
            {

                if (playGameUserInfo.GameStatus == PlayGameStatus.游戏掉线)
                {
                    playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
                    {
                        OperationDateTime = DateTime.Now,
                        Content = "用户游戏掉线重连成功",
                        ActionId = (int)PlayGameStatus.游戏中
                    });
                }
                playGameUserInfo.GameStatus = PlayGameStatus.游戏中;
            }
            playGameUserInfo.PlayGameHeartbeatAt = DateTime.Now;
            playGameUserInfo.PlayGameTotalSeconds = (int)(playGameUserInfo.PlayGameHeartbeatAt ?? DateTime.Now).Subtract(playGameUserInfo.PlayGameStartAt ?? playGameUserInfo.CreateDateTime).TotalSeconds;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
            {
                OperationDateTime = DateTime.Now,
                Content = $"用户持续游戏中，累计游玩时间{(playGameUserInfo.PlayGameTotalSeconds / 60).ToString("0.##")}分钟{desc}；",
                ActionId = (int)PlayGameStatus.游戏中
            });
            return true;
        }

        /// <summary>
        /// 开始排队
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="play_queue_id">队列id</param>
        /// <param name="queue_pos">前面还有多少位</param>
        /// <param name="queue_grade">队列等级</param>
        /// <param name="jYApiRespnse"></param>
        /// <returns></returns>
        public static bool PlayQueueStart(this PlayGameUserInfo playGameUserInfo, int play_queue_id, int queue_pos, int? queue_grade = null, IJYApiRespnse jYApiRespnse = null)
        {
            PlayGameUserOperation? playGameUserOperation = null;
            if (playGameUserInfo.GameStatus == PlayGameStatus.排队中)
            {
                if (playGameUserInfo.LastWriteQueueAt == null || (playGameUserInfo.LastWriteQueueAt != null && DateTime.Now.Subtract(playGameUserInfo.LastWriteQueueAt ?? DateTime.Now).TotalSeconds > 30))
                {
                    playGameUserOperation = new PlayGameUserOperation(jYApiRespnse)
                    {
                        Content = $"继续排队中,排队Id：{play_queue_id}，前面还有{queue_pos}人；",
                        OperationDateTime = DateTime.Now,
                        ActionId = (int)PlayGameStatus.排队中
                    };
                    playGameUserInfo.LastWriteQueueAt = DateTime.Now;
                }
                else
                {
                    playGameUserOperation = new PlayGameUserOperation()
                    {
                        Content = $"继续排队中,排队Id：{play_queue_id}，前面还有{queue_pos}人；",
                        OperationDateTime = DateTime.Now,
                        ActionId = (int)PlayGameStatus.排队中
                    };
                }

                playGameUserInfo.GameUserOperation.Add(playGameUserOperation);
            }
            else
            {
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
                {
                    Content = $"开始排队,排队Id：{play_queue_id},前面还有{queue_pos}人；",
                    OperationDateTime = DateTime.Now,
                    ActionId = (int)PlayGameStatus.排队中
                });
            }
            playGameUserInfo.GameStatus = PlayGameStatus.排队中;
            playGameUserInfo.LastPlayQueueAt = DateTime.Now;
            playGameUserInfo.PlayQueueId = play_queue_id;
            if (playGameUserInfo.PlayQueueStartAt == null)
            {
                playGameUserInfo.PlayQueueStartAt = DateTime.Now;
            }
            if (queue_grade != null)
            {
                playGameUserInfo.QueueGrade = queue_grade ?? 1;
            }
            return true;
        }
        /// <summary>
        /// 排队成功
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayQueueSuccess(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            if (playGameUserInfo.GameStatus == PlayGameStatus.排队中)
            {
                playGameUserInfo.GameStatus = PlayGameStatus.排队成功;
                playGameUserInfo.PlayQueueSuccessAt = DateTime.Now;
                var totalSeconds = 0;
                if (playGameUserInfo.PlayQueueStartAt != null)
                {
                    totalSeconds = (int)DateTime.Now.Subtract(playGameUserInfo.PlayQueueStartAt ?? DateTime.Now).TotalSeconds;
                }
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
                {
                    Content = $"排队成功，本次排队耗时{totalSeconds}秒",
                    OperationDateTime = DateTime.Now,
                    ActionId = (int)playGameUserInfo.GameStatus
                });
                playGameUserInfo.LastPlayQueueAt = DateTime.Now;
            }
            return true;
        }
        /// <summary>
        /// 取消排队
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayQueueCancel(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.取消排队;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                Content = $"用户取消排队",
                OperationDateTime = DateTime.Now,
                ActionId = (int)playGameUserInfo.GameStatus
            });
            return true;
        }

        /// <summary>
        /// 用户切换视频等级
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="displayGrade"></param>
        /// <param name="jYApiRespnse"></param>
        /// <returns></returns>
        public static bool UserSwitchDisplayGrade(this PlayGameUserInfo playGameUserInfo, int displayGrade, IJYApiRespnse jYApiRespnse)
        {

            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                Content = $"用户切换视频等级:{displayGrade};",
                OperationDateTime = DateTime.Now,
                ActionId = (int)PlayGameStatus.切换视频等级
            });
            return true;
        }

        /// <summary>
        /// 用户切换视频等级
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="displayGrade"></param>
        /// <param name="jYApiRespnse"></param>
        /// <returns></returns>
        public static bool UserSwitchDisplayGradeError(this PlayGameUserInfo playGameUserInfo, int displayGrade, IJYApiRespnse jYApiRespnse)
        {

            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                Content = $"用户切换视频等级失败:{displayGrade};",
                OperationDateTime = DateTime.Now,
                ActionId = (int)PlayGameStatus.切换视频等级
            });
            return true;
        }

        /// <summary>
        /// 排队异常
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameQueueError(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.排队异常;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                OperationDateTime = DateTime.Now,
                Content = "排队异常!",
                ActionId = (int)PlayGameStatus.排队异常
            });
            return true;
        }

        /// <summary>
        /// 游戏掉线
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameUserNotAction(this PlayGameUserInfo playGameUserInfo)
        {
            if (playGameUserInfo.GameStatus == PlayGameStatus.开始游戏)
            {
                //说明一次都没有使用过游戏心跳

            }
            if (playGameUserInfo.GameStatus != PlayGameStatus.游戏掉线)
            {
                playGameUserInfo.GameStatus = PlayGameStatus.游戏掉线;
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
                {
                    Content = $"用户游戏掉线，上一次心跳时间{playGameUserInfo.PlayGameHeartbeatAt?.ToString("yyyy-MM-dd HH:mm:ss")};",
                    OperationDateTime = DateTime.Now,
                    ActionId = (int)playGameUserInfo.GameStatus
                });
            }
            return true;
        }

        /// <summary>
        /// 游戏掉线
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameUserNotQueue(this PlayGameUserInfo playGameUserInfo)
        {

            if (playGameUserInfo.GameStatus != PlayGameStatus.排队掉线)
            {
                playGameUserInfo.GameStatus = PlayGameStatus.排队掉线;
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
                {
                    Content = $"用户排队掉线，上一次排队时间{playGameUserInfo.LastPlayQueueAt?.ToString("yyyy-MM-dd HH:mm:ss")}；",
                    OperationDateTime = DateTime.Now,
                    ActionId = (int)playGameUserInfo.GameStatus
                });
            }
            return true;
        }

        /// <summary>
        /// 游戏掉线
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameUserNotQueueEnd(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.排队掉线结束游戏;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                Content = $"用户排队掉线后未上线，上一次排队时间{playGameUserInfo.LastPlayQueueAt?.ToString("yyyy-MM-dd HH:mm:ss")}；准备结束游戏;",
                OperationDateTime = DateTime.Now,
                ActionId = (int)playGameUserInfo.GameStatus
            });
            return true;
        }

        /// <summary>
        /// 游戏掉线
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameDiaoXian(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.游戏掉线结束游戏;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                Content = $"用户游戏掉线后未上线，准备结束游戏；",
                OperationDateTime = DateTime.Now,
                ActionId = (int)PlayGameStatus.游戏掉线结束游戏
            });
            return true;
        }

        /// <summary>
        /// 用户钻石不足，准备退出游戏
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <returns></returns>
        public static bool PlayGameUserNotDiamond(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {
            playGameUserInfo.GameStatus = PlayGameStatus.用户游玩时钻石不足;
            playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
            {
                OperationDateTime = DateTime.Now,
                Content = $"用户余额不足，准备退出游戏",
                ActionId = (int)PlayGameStatus.用户游玩时钻石不足
            });
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="redis"></param>
        /// <param name="redisServer"></param>
        /// <param name="keyPattern"></param>
        /// <returns></returns>
        public static async Task<List<PlayGameUserInfo?>> GetPlayGameUserInfoList(IDatabase redis, IServer redisServer, string keyPattern)
        {
            var keys = await redisServer.ScanKeysAsync(keyPattern, 2000).ConfigureAwait(false);

            var tasks = keys.Select(async gameKey =>
            {
                var gameInfo = await redis.StringGetAsync<PlayGameUserInfo>(gameKey).ConfigureAwait(false);
                return gameInfo;
            });

            var gameInfoList = (await Task.WhenAll(tasks).ConfigureAwait(false)).Where(x => x != null).ToList();
            return gameInfoList;
        }


        /// <summary>
        /// 游戏游戏重连
        /// </summary>
        /// <param name="cloudGamingBase"></param>
        /// <param name="userId"></param>
        /// <param name="scId"></param>
        /// <returns></returns>
        public static async Task<PlayGameUserInfo> PlayGameRecon(CloudGamingBase cloudGamingBase, int userId, int scId, IJYApiRespnse jYApiRespnse)
        {
            var list = await GetPlayGameUserInfoList(cloudGamingBase.RedisCache, cloudGamingBase.RedisServerCache, $"{GetPlayGameKeyPrefix}:*:{userId}");
            if (list != null && list.Count > 0)
            {
                var playGameUserInfo = list.Where(it => it.ScId == scId).FirstOrDefault();
                if (playGameUserInfo == null)
                {
                    playGameUserInfo = list[0];
                }
                if (playGameUserInfo != null)
                {
                    playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
                    {
                        Content = $"用户获取可连接的游戏列表scId:${scId};",
                        OperationDateTime = DateTime.Now,
                        ActionId = (int)PlayGameStatus.排队掉线
                    });
                }
                return playGameUserInfo;
            }

            return null;
        }
        /// <summary>
        /// 游戏游戏重连
        /// </summary>
        /// <param name="cloudGamingBase"></param>
        /// <param name="userId"></param>
        /// <param name="scId"></param>
        /// <returns></returns>
        public static PlayGameUserInfo PlayGameRecon(this PlayGameUserInfo playGameUserInfo, IJYApiRespnse jYApiRespnse)
        {


            if (playGameUserInfo != null)
            {
                if (playGameUserInfo.GameStatus != PlayGameStatus.游戏掉线)
                {
                    playGameUserInfo.GameStatus = PlayGameStatus.游戏中;

                }
                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation(jYApiRespnse)
                {
                    Content = $"用户重连游戏成功，上一次心跳时间{playGameUserInfo.PlayGameHeartbeatAt?.ToString("yyyy-MM-dd HH:mm:ss")};",
                    OperationDateTime = DateTime.Now,
                    ActionId = (int)PlayGameStatus.游戏中
                });
            }
            return playGameUserInfo;
        }
        /// <summary>
        /// 保存缓存到redis中
        /// </summary>
        /// <param name="playGameUserInfo">用户玩游戏信息</param>
        /// <param name="cloudGamingBase"></param>
        /// <returns></returns>
        public static async Task<bool> SaveChangesAsync(this PlayGameUserInfo playGameUserInfo, CloudGamingBase cloudGamingBase)
        {
            return await SaveChangesAsync(playGameUserInfo, cloudGamingBase.Dao, cloudGamingBase.RedisCache);
        }


        /// <summary>
        /// 保存缓存到redis中
        /// </summary>
        /// <param name="playGameUserInfo"></param>
        /// <param name="dao"></param>
        /// <param name="redisDatabase"></param>
        /// <returns></returns>
        public static async Task<bool> SaveChangesAsync(this PlayGameUserInfo playGameUserInfo, DAO dao, IDatabase redisDatabase)
        {
            playGameUserInfo.LastDateTime = DateTime.Now;
            var redisGameKey = GetPlayGameKey(playGameUserInfo.GameId, playGameUserInfo.UserId);
            if (playGameUserInfo.GameStatus == PlayGameStatus.取消排队 ||
                playGameUserInfo.GameStatus == PlayGameStatus.游戏启动失败 ||
                playGameUserInfo.GameStatus == PlayGameStatus.用户主动结束游戏 ||
                playGameUserInfo.GameStatus == PlayGameStatus.用户钻石不足 ||
                playGameUserInfo.GameStatus == PlayGameStatus.用户游玩时钻石不足 ||
                playGameUserInfo.GameStatus == PlayGameStatus.游戏掉线结束游戏 ||
                playGameUserInfo.GameStatus == PlayGameStatus.排队异常 ||
                playGameUserInfo.GameStatus == PlayGameStatus.排队掉线结束游戏)

            {
                //只有不等于下面这几种状态才记录游玩记录
                if (playGameUserInfo.GameStatus != PlayGameStatus.排队掉线 &&
                    playGameUserInfo.GameStatus != PlayGameStatus.取消排队 &&
                    playGameUserInfo.GameStatus != PlayGameStatus.排队掉线结束游戏 &&
                    playGameUserInfo.GameStatus != PlayGameStatus.游戏启动失败 &&
                    playGameUserInfo.GameStatus != PlayGameStatus.用户钻石不足)
                {
                    T_User_GameList userGameListLog = null;
                    if (playGameUserInfo.DiamondListId > 0)
                    {
                        //设置游玩记录
                        userGameListLog = await dao.DaoPhone.Context.T_User_GameList.FirstOrDefaultAsync(it => it.Id == playGameUserInfo.DiamondListId);
                    }
                    if (userGameListLog == null)
                    {
                        userGameListLog = new T_User_GameList
                        {
                            Channel = playGameUserInfo.Channel,
                            CreateTime = playGameUserInfo.PlayGameStartAt ?? playGameUserInfo.CreateDateTime,
                            GameId = playGameUserInfo.GameId,
                            Status = (int)PlayGameStatus.游戏结束,
                            UpdateTime = DateTime.Now,
                            UserId = playGameUserInfo.UserId,
                            SessionId = playGameUserInfo?.SessionId
                        };
                        await dao.DaoPhone.Context.T_User_GameList.AddAsync(userGameListLog);
                    }
                    userGameListLog.Status = (int)PlayGameStatus.游戏结束;


                    var playTime = playGameUserInfo.PlayGameTotalSeconds / 60;
                    userGameListLog.PlaySeconds = playGameUserInfo.PlayGameTotalSeconds;
                    userGameListLog.PlayTime = playTime;
                    userGameListLog.UpdateTime = DateTime.Now;
                    await dao.DaoPhone.Context.SaveChangesAsync();
                    //设置游玩历史
                    var userId = playGameUserInfo.UserId;
                    var gameId = playGameUserInfo.GameId;
                    if (playGameUserInfo.GameStatus != PlayGameStatus.取消排队 && playGameUserInfo.GameStatus != PlayGameStatus.游戏启动失败 && playGameUserInfo.GameStatus != PlayGameStatus.排队掉线)
                    {
                        //设置用户游玩历史
                        var playGameTime = await dao.DaoPhone.Context.T_User_PlayGameTime.Where(it => it.UserId == userId && it.GameId == gameId).FirstOrDefaultAsync();
                        if (playGameTime == null)
                        {
                            playGameTime = new T_User_PlayGameTime()
                            {
                                Createtime = DateTime.Now,
                                NightCardPlayTime = 0,
                                DiamondPlayTime = 0,
                                FreePlayTime = 0,
                                GameId = gameId,
                                PlayTime = 0,
                                UpdateTime = DateTime.Now,
                                UserId = userId,

                            };
                            await dao.DaoPhone.Context.T_User_PlayGameTime.AddAsync(playGameTime);
                        }
                        playGameTime.PlayTime += playTime;
                        playGameTime.UpdateTime = DateTime.Now;
                        playGameTime.DiamondPlayTime += playTime;
                        await dao.DaoPhone.Context.SaveChangesAsync();
                    }

                }

                playGameUserInfo.GameUserOperation.Add(new PlayGameUserOperation()
                {
                    Content = "游戏结束",
                    OperationDateTime = DateTime.Now,
                    ActionId = (int)PlayGameStatus.游戏结束
                });
                playGameUserInfo.GameStatus = PlayGameStatus.游戏结束;
                var playGameLog = playGameUserInfo.ToGamePlayGameLog();
                if (playGameLog != null)
                {
                    await dao.DaoPhone.Context.T_Game_PlayGameLog.AddAsync(playGameLog);
                    await dao.DaoPhone.Context.SaveChangesAsync();
                }
                return await redisDatabase.KeyDeleteAsync(redisGameKey);
            }
            return await redisDatabase.StringSetAsync(redisGameKey, playGameUserInfo, TimeSpan.FromMinutes(10));

        }

    }
}
