using CloudGaming.Code.Cache;
using CloudGaming.Code.DataAccess;
using CloudGaming.DtoModel.Messages;

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

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

namespace CloudGaming.Code.Other;

/// <summary>
/// 消息
/// </summary>
public class MessagesBLL : CloudGamingBase
{
    public MessagesBLL(IServiceProvider serviceProvider) : base(serviceProvider)
    {
    }
    /// <summary>
    /// 给用户发送消息
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="title"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    public async Task SendUserMessage(int userId, string title, string content)
    {
        T_User_Messages t_User_Messages = new T_User_Messages()
        {
            Content = content,
            CreateAt = DateTime.Now,
            MessageType = MessageType.user.ToString(),
            IsRead = false,
            SendAt = DateTime.Now,
            SystemId = 0,
            Title = title,
            UserId = userId
        };
        await Dao.DaoPhone.Context.T_User_Messages.AddAsync(t_User_Messages);
        await Dao.DaoPhone.Context.SaveChangesAsync();
    }
    /// <summary>
    /// 获取用户消息列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<MessageListDto>> GetUserMessageList()
    {
        List<MessageListDto> messageListDtos = new List<MessageListDto>();
        if (_UserId == 0)
        {
            return messageListDtos;
        }
        await InitSystemMessage();
        var list = await Dao.DaoPhone.Context.T_User_Messages.AsNoTracking().Where(it => it.UserId == _UserId).OrderBy(it => it.IsRead).ThenByDescending(it => it.SendAt).Take(100).ToListAsync();

        list.ForEach(it =>
        {
            MessageListDto messageListDto = new MessageListDto()
            {
                Content = it.Content,
                MessageId = it.Id,
                SendDateTime = it.SendAt.ToString("yyyy-MM-dd"),
                Title = it.Title,
                IsRead = it.IsRead,
            };
            if (messageListDto.Content.Length > 20)
            {
                messageListDto.Content = messageListDto.Content[..20] + "...";
            }
            messageListDtos.Add(messageListDto);
        });
        return messageListDtos;
    }

    /// <summary>
    /// 获取消息详情
    /// </summary>
    /// <param name="messageId"></param>
    /// <returns></returns>
    public async Task<MessageListDto> GetUserMessageInfo(int messageId)
    {
        var userMessages = await Dao.DaoPhone.Context.T_User_Messages.Where(it => it.UserId == _UserId && it.Id == messageId).FirstOrDefaultAsync();
        if (userMessages == null)
        {
            throw MessageBox.ErrorShow("消息不存在");
        }
        userMessages.IsRead = true;
        userMessages.ReadAt = DateTime.Now;
        await Dao.DaoPhone.Context.SaveChangesAsync();
        MessageListDto messageListDto = new MessageListDto()
        {
            Content = userMessages.Content,
            IsRead = userMessages.IsRead,
            MessageId = messageId,
            SendDateTime = userMessages.SendAt.ToString("yyyy-MM-dd HH:mm:ss")
        };
        return messageListDto;
    }

    /// <summary>
    /// 用户消息读取
    /// </summary>
    /// <param name="messageId"></param>
    /// <returns></returns>
    public async Task<bool> UserMessageRead(int messageId)
    {
        var userMessages = await Dao.DaoPhone.Context.T_User_Messages.Where(it => it.UserId == _UserId && it.Id == messageId).FirstOrDefaultAsync();
        if (userMessages == null)
        {
            throw MessageBox.ErrorShow("消息不存在");
        }
        userMessages.ReadAt = DateTime.Now;
        userMessages.IsRead = true;
        await Dao.DaoPhone.Context.SaveChangesAsync();
        return true;
    }

    /// <summary>
    /// 全部已读
    /// </summary>
    /// <returns></returns>
    public async Task<bool> UserAllMessageRead()
    {
        var userMessages = await Dao.DaoPhone.Context.T_User_Messages.Where(it => it.UserId == _UserId && !it.IsRead).ToListAsync();
        userMessages.ForEach(item =>
        {
            item.IsRead = true;
            item.ReadAt = DateTime.Now;
        });
        await Dao.DaoPhone.Context.SaveChangesAsync();
        return true;
    }

    /// <summary>
    /// 获取未读取消息的数量
    /// </summary>
    /// <returns></returns>
    public async Task<int> GetUserMessageNotReadCount()
    {
        if (_UserId == 0)
        {
            return 0;
        }
        await InitSystemMessage();
        var coun = await Dao.DaoPhone.Context.T_User_Messages.Where(it => it.UserId == _UserId && !it.IsRead).CountAsync();
        return coun;
    }

    /// <summary>
    /// 初始话系统消息
    /// </summary>
    /// <returns></returns>
    private async Task InitSystemMessage()
    {
        var systemIds = Dao.DaoPhone.Context.T_User_Messages.Where(it => it.UserId == _UserId && it.MessageType == MessageType.system.ToString()).Select(it => it.SystemId).ToList();
        if (systemIds != null && systemIds.Count > 0)
        {
            var sysMessage = await Dao.DaoPhone.Context.T_Sys_Message.Where(it => !systemIds.Contains(it.Id)).ToListAsync();
            if (sysMessage != null && sysMessage.Count > 0)
            {
                sysMessage.ForEach(item =>
                {
                    T_User_Messages t_User_Messages = new T_User_Messages()
                    {
                        Content = item.Content,
                        CreateAt = item.CreatedAt,
                        MessageType = MessageType.system.ToString(),
                        IsRead = false,
                        SendAt = item.CreatedAt,
                        SystemId = item.Id,
                        Title = item.Title,
                        UserId = _UserId
                    };
                    Dao.DaoPhone.Context.T_User_Messages.Add(t_User_Messages);
                });
                await Dao.DaoPhone.Context.SaveChangesAsync();
            }
        }
    }
}
