using CloudGaming.Code.DataAccess;
using CloudGaming.DtoModel.Other;

using Microsoft.Win32;

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

using static SKIT.FlurlHttpClient.Wechat.TenpayV3.Models.CreateNewTaxControlFapiaoApplicationRequest.Types.Fapiao.Types;

namespace CloudGaming.Code.Monitor;

/// <summary>
/// 监控类
/// </summary>
public class MonitorBLL : CloudGamingBase
{
    public MonitorBLL(IServiceProvider serviceProvider) : base(serviceProvider)
    {
    }

    /// <summary>
    /// 获取监控数据
    /// </summary>
    /// <returns></returns>
    public AppBasicStatistics GetAppMonitorInfo()
    {
        return AppConfig.GetAppMonitorInfo().ToAppBasicStatistics();
    }

    /// <summary>
    /// 获取近一月活跃人数统计
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetActiveUserCount(long startTimeStamp = 0, long endTimeStamp = 0)
    {
        if (endTimeStamp == 0)
        {
            endTimeStamp = DateTime.Now.ToUnixTimestamp();
        }
        if (startTimeStamp == 0)
        {
            startTimeStamp = DateTime.Now.AddMonths(-1).ToUnixTimestamp();
        }
        //开始时间
        DateOnly startDate = DateOnly.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(startTimeStamp));
        //结束时间
        DateOnly endDate = DateOnly.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(endTimeStamp));
        DateOnly curr = startDate;
        var userStatisticsList = await Dao.DaoExt.Context.T_Statistics_User.Where(it => it.LoginDate > startDate && it.LoginDate < endDate).ToListAsync();
        var channels = userStatisticsList.GroupBy(it => it.Channel).Select(it => it.Key).ToList();
        List<StatisticsDto> userLogin = new List<StatisticsDto>();
        List<StatisticsDto> userRegistr = new List<StatisticsDto>();
        List<StatisticsDto> userActive = new List<StatisticsDto>();
        var nowDay = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
        while (curr <= endDate)
        {
            int day = int.Parse(curr.ToString("yyyyMMdd"));
            var _Statistics_Users = userStatisticsList.Where(it => it.LoginDate == curr).OrderBy(it => it.Channel).ToList();
            var statisticsDtoUserList = new List<StatisticsDto>();
            var statisticsDtoRegistrList = new List<StatisticsDto>();
            var statisticsDtoActiveList = new List<StatisticsDto>();

            var currDateStr = curr.ToString("MM月dd号");
            StatisticsDto _UserLogin = new StatisticsDto(currDateStr, 0, "全部");
            StatisticsDto _userRegistr = new StatisticsDto(currDateStr, 0, "全部");
            StatisticsDto _userActive = new StatisticsDto(currDateStr, 0, "全部");
            if (day == nowDay)
            {
                var m = AppConfig.GetAppMonitorInfo();
                _UserLogin.Value += m.TodayLoggedInUsers;
                _userRegistr.Value += m.TodayRegisteredUsers;
                _userActive.Value += 0;

            }
            foreach (var _channel in channels)
            {


                var item = _Statistics_Users.FirstOrDefault(it => it.Channel == _channel);

                if (item == null)
                {
                    item = new T_Statistics_User();
                }
                _UserLogin.Value += item.LoginCount;
                _userRegistr.Value += item.RegistrCount;
                _userActive.Value += item.ActiveCount;
                //item.ActiveCount
                statisticsDtoUserList.Add(new StatisticsDto(currDateStr, item.LoginCount, item.Channel));
                statisticsDtoRegistrList.Add(new StatisticsDto(currDateStr, item.RegistrCount, item.Channel));
                statisticsDtoActiveList.Add(new StatisticsDto(currDateStr, item.ActiveCount, item.Channel));

            }
            userLogin.Add(_UserLogin);
            userLogin.AddRange(statisticsDtoUserList);
            userRegistr.Add(_userRegistr);
            userRegistr.AddRange(statisticsDtoRegistrList);
            userActive.Add(_userActive);
            userActive.AddRange(statisticsDtoActiveList);

            curr = curr.AddDays(1);
        }
        return new { Login = userLogin, Registr = userRegistr, Active = userActive };
    }


    /// <summary>
    /// 获取近一月登录人数统计
    /// </summary>
    /// <returns></returns>
    public async Task<dynamic> GetAppMonitorHourAsync(long startTimeStamp = 0, long endTimeStamp = 0)
    {
        if (endTimeStamp == 0)
        {
            endTimeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        }
        if (startTimeStamp == 0)
        {
            startTimeStamp = DateTimeOffset.UtcNow.AddHours(-24).ToUnixTimeSeconds();
        }
        //开始时间
        var startDate = DateTimeOffset.FromUnixTimeSeconds(startTimeStamp).ToLocalTime().DateTime;
        //结束时间
        var endDate = DateTimeOffset.FromUnixTimeSeconds(endTimeStamp).ToLocalTime().DateTime;
        var curr = startDate;
        var list = await Dao.DaoExt.Context.T_App_Channel.Where(it => !string.IsNullOrEmpty(it.ChannelId)).ToListAsync();
        int startDateHour = int.Parse(startDate.ToString("yyyyMMddHH"));
        int endDateHour = int.Parse(endDate.ToString("yyyyMMddHH"));
        var userStatisticsList = await Dao.DaoExt.Context.T_Statistics_UserHour.Where(it => it.LoginHour >= startDateHour && it.LoginHour <= endDateHour).ToListAsync();

        var gameStatisticsList = await Dao.DaoExt.Context.T_Statistics_GameHour.Where(it => it.LoginHour >= startDateHour && it.LoginHour <= endDateHour).ToListAsync();
        List<StatisticsDto> userLogin = new List<StatisticsDto>();
        List<StatisticsDto> userRegistr = new List<StatisticsDto>();
        List<StatisticsDto> playGame = new List<StatisticsDto>();
        List<StatisticsDto> playTimeGame = new List<StatisticsDto>();
        while (curr <= endDate)
        {

            var loginAll = GetStatisticsDto(curr, "全部", 0);
            var registrAll = GetStatisticsDto(curr, "全部", 0);
            var gameAll = GetStatisticsDto(curr, "全部", 0);
            var gameTimeAll = GetStatisticsDto(curr, "全部", 0);
            // 添加 "全部" 统计到结果
            userLogin.Add(loginAll);
            userRegistr.Add(registrAll);
            playGame.Add(gameAll);
            playTimeGame.Add(gameTimeAll);
            int dayHour = int.Parse(curr.ToString("yyyyMMddHH"));
            foreach (var channel in list)
            {
                var channelId = channel.ChannelId;
                var statis = userStatisticsList.FirstOrDefault(it => it.LoginHour == dayHour && it.Channel == channelId);
                var gameStatis = gameStatisticsList.FirstOrDefault(it => it.LoginHour == dayHour && it.Channel == channelId);

                var _loginCount = statis?.LoginCount ?? 0;
                var _registrCount = statis?.RegistrCount ?? 0;
                var _playGameCount = gameStatis?.PlayGameCount ?? 0;
                var _playGameTimeCount = gameStatis?.PlayGameTimeCount ?? 0;
                loginAll.Value += _loginCount;
                registrAll.Value += _registrCount;
                gameAll.Value += _playGameCount;
                gameTimeAll.Value += Math.Round(_playGameTimeCount, 2);
                userLogin.Add(GetStatisticsDto(curr, channel.Name, _loginCount));
                userRegistr.Add(GetStatisticsDto(curr, channel.Name, _registrCount));
                playGame.Add(GetStatisticsDto(curr, channel.Name, _playGameCount));
                playTimeGame.Add(GetStatisticsDto(curr, channel.Name, _playGameTimeCount));
            }
            curr = curr.AddHours(1);
        }
        return new { Login = userLogin, Registr = userRegistr, PlayGame = playGame, PlayTimeGame = playTimeGame };

    }
    private StatisticsDto GetStatisticsDto(DateTime curr, string channelId, decimal count)
    {
        return new StatisticsDto()
        {
            Category = channelId,
            TimeStamp = curr.ToString("dd-HH"),
            Value = Math.Round(count, 2)
        };
    }
    /// <summary>
    /// 获取近一月注册人数统计
    /// </summary>
    /// <returns></returns>
    public async Task GetRegisteredUserCount()
    {
    }

}

