using Infrastructure;
using Microsoft.Extensions.Logging;
using OpenAuth.App.Base;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App
{
    public class SysMessageApp : SqlSugarBaseApp<SysMessage, SugarDbContext>
    {
        private readonly ILogger<SysMessageApp> _logger;

        public SysMessageApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<SysMessage> repository,
            IAuth auth,
            ILogger<SysMessageApp> logger) : base(unitWork, repository, auth)
        {
            _logger = logger;
        }

        /// <summary>
        /// 加载列表
        /// </summary>
        public async Task<TableData> Load(QuerySysMessageListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }

            int totalCount = 0;
            var result = new TableData();
            var objs = base.Repository.AsQueryable().Where(u => u.ToId == loginContext.User.Id && u.ToStatus != -1)
                .WhereIF(!string.IsNullOrEmpty(request.key), u => u.Title.Contains(request.key))
                .WhereIF(request.Status != 999, u => u.ToStatus == request.Status);

            result.data = await objs.OrderByDescending(u => u.CreateTime).ToPageListAsync(request.page, request.limit, totalCount);
            result.count = totalCount;

            return result;
        }

        public void Add(SysMessage obj)
        {
            obj.Id = Yitter.IdGenerator.YitIdHelper.NextId();
            Repository.Insert(obj);
        }

        /// <summary>
        /// 发送指定消息给用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        public void SendMsgTo(long userId, string message)
        {
            SysUser user = null;
            if (userId == -1)
            {
                user = new SysUser
                {
                    Name = Define.SYSTEM_USERNAME,
                    Id = userId
                };
            }
            else
            {
                user = (Repository.ChangeRepository<SugarRepositiry<SysUser>>()).GetFirst(u => u.Id == userId);
            }
            if (user == null)
            {
                _logger.LogError($"未能找到用户{userId},不能给该用户发送消息");
                return;
            }
            Repository.Insert(new SysMessage
            {
                ToId = user.Id,
                ToName = user.Name,
                TypeName = "系统消息",
                TypeId = "SYS_MSG",
                FromId = Guid.Empty.ToString(),
                FromName = "系统管理员",
                Content = message,
                CreateTime = DateTime.Now
            });
        }

        /// <summary>
        /// 消息变为已读
        /// </summary>
        /// <param name="msgid"></param>
        public void Read(IdRequest<long> req)
        {
            Repository.Update(u => new SysMessage
            {
                ToStatus = 1
            }, u => u.Id == req.Id);
        }
        /// <summary>
        /// 消息采用逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        public void Del(long[] ids)
        {
            Repository.Update(u => new SysMessage
            {
                ToStatus = -1 //逻辑删除
            }, u => ids.Contains(u.Id));

        }

        public void Delete(string[] ids)
        {
            Repository.DeleteByIds(ids);
        }

        public SysMessage Get(string id)
        {
            return Repository.GetById(id);
        }


    }
}