using CloudGaming.Code.Account;
using CloudGaming.DtoModel.Other;
using CloudGaming.DtoModel.PlayGame;

using HuanMeng.DotNetCore.QuartzExtend;

using Newtonsoft.Json;

using Quartz;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudGaming.Code.Monitor;


/// <summary>
/// 基础信息定时监控
/// </summary>
[QuartzTrigger("MonitorProcessor", "3/10 * * * * ?")]
public class MonitorProcessor : AppJobBase
{
    public MonitorProcessor(IServiceScopeFactory scopeFactory) : base(scopeFactory)
    {
    }

    /// <summary>
    /// 单个项目的处理循环
    /// </summary>
    public override async Task AppConfigProcessLoop(AppConfig appConfig, AppMonitorInfo appMonitorInfo, IServiceProvider serviceProvider, CloudGamingBase cloudGamingBase)
    {
        int day = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
        var nowDay = DateOnly.FromDateTime(DateTime.Now);
        //今日登录人数
        var todayLoggedInUsers = await cloudGamingBase.Dao.DaoExt.Context.T_User_LoginDay_Log.Where(it => it.CreateTimeDay == day).CountAsync();
        //今日注册人数
        var todayRegisteredUsers = await cloudGamingBase.Dao.DaoExt.Context.T_User_LoginDay_Log.Where(it => it.CreateTimeDay == day && it.IsNew).CountAsync();
        //今日意向订单
        var todayIntendedOrders = await cloudGamingBase.Dao.DaoUser.Context.T_User_IntentOrder.Where(it => it.CreatedDay == day).CountAsync();
        //今日支付订单
        var todayPaidOrders = await cloudGamingBase.Dao.DaoUser.Context.T_User_Order.Where(it => it.PaymentDay == nowDay).CountAsync();
        //今日支付金额
        var todayRechargeAmount = await cloudGamingBase.Dao.DaoUser.Context.T_User_Order.Where(it => it.PaymentDay == nowDay).SumAsync(it => (decimal?)it.TotalPrice);
        // 查询游戏数据
        var playGameStatusStatistics = appMonitorInfo.PlayGameStatusStatistics();
        //排队数据
        int currentQueuedUsers = playGameStatusStatistics.GetValueOrDefault(PlayGameStatus.排队中);
        //开始游戏
        int currentPlayingUsers = playGameStatusStatistics.GetValueOrDefault(PlayGameStatus.开始游戏) + playGameStatusStatistics.GetValueOrDefault(PlayGameStatus.游戏中);
        //查询在线人数
        //ScanKeysCount user:userInfo:*
        var currentOnlineUsers = await cloudGamingBase.RedisServerCache.ScanKeysCountAsync($"{AccountExtend.UserInfoRedisKeyPrefix}:*");

        appMonitorInfo.TodayLoggedInUsers = todayLoggedInUsers;
        appMonitorInfo.TodayRegisteredUsers = todayRegisteredUsers;
        appMonitorInfo.TodayIntendedOrders = todayIntendedOrders;
        appMonitorInfo.TodayPaidOrders = todayPaidOrders;
        appMonitorInfo.TodayRechargeAmount = todayRechargeAmount ?? 0;
        appMonitorInfo.CurrentOnlineUsers = currentOnlineUsers;
        appMonitorInfo.CurrentQueuedUsers = currentQueuedUsers;
        appMonitorInfo.CurrentPlayingUsers = currentPlayingUsers;
    }
}

