using OASystem.Domain;
using OASystem.Domain.Dtos.System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.System
{
    public class MessageRepository : BaseRepository<Sys_Message, MessageView>
    {
        public MessageRepository(SqlSugarClient sqlSugar) : base(sqlSugar) { }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="msgDto"></param>
        /// <returns></returns>
        public async Task<bool> AddMsg(MessageDto msgDto)
        {
            #region 参数处理

            if (msgDto == null) { return false; }
            if (string.IsNullOrEmpty(msgDto.Title)) { return false; }
            if (string.IsNullOrEmpty(msgDto.Content)) { return false; }
            if (msgDto.UIdList.Count <= 0) { return false; }

            #endregion

            _sqlSugar.BeginTran();
            try
            {
                Sys_Message message = new Sys_Message()
                {
                    Type = msgDto.Type,
                    IssuerId = msgDto.IssuerId,
                    Title = msgDto.Title,
                    Content = msgDto.Content,
                    ReleaseTime = msgDto.ReleaseTime,
                    CreateUserId = msgDto.IssuerId,
                    CreateTime = DateTime.Now,
                    DeleteUserId = null,
                    DeleteTime = "1990-01-01 00:00:00.000",
                    Remark = "",
                    IsDel = 0,
                    DiId = msgDto.DiId
                };

                int? msgId = await _sqlSugar.Insertable(message).ExecuteReturnIdentityAsync();
                if (!msgId.HasValue) { _sqlSugar.RollbackTran(); return false; }

                List<Sys_MessageReadAuth> messageReadAuths = new List<Sys_MessageReadAuth>();
                foreach (int item in msgDto.UIdList)
                {
                    Sys_MessageReadAuth messageReadAuth = new Sys_MessageReadAuth()
                    {
                        MsgId = msgId.Value,
                        ReadableUId = item,
                        ReadTime = new DateTime(1990, 1, 1),
                        CreateUserId = msgDto.IssuerId,
                        CreateTime = DateTime.Now,
                        DeleteUserId = null,
                        DeleteTime = "1990-01-01 00:00:00.000",
                        Remark = "",
                        IsDel = 0
                    };
                    messageReadAuths.Add(messageReadAuth);
                }

                int? readIds = await _sqlSugar.Insertable<Sys_MessageReadAuth>(messageReadAuths).ExecuteCommandAsync();
                if (!readIds.HasValue)
                {
                    _sqlSugar.RollbackTran();
                    return false;
                }
                _sqlSugar.CommitTran();
            }
            catch (Exception)
            {
                _sqlSugar.RollbackTran();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 获取消息列表
        /// </summary>
        /// <param name="uId">可读用户Id</param>
        /// <returns></returns>
        public async Task<Result> GetMsgList(MsgDto dto)
        {
            Result result = new Result() { Code = -1, Msg = "未知错误", Data = null };

            if (dto.PortType == 1 || dto.PortType == 2)  // web/android
            {
                string msgSqlWhere = string.Format(@"Select sm.Type,sm.Title,sm.Content,sd.DepName issuerDep,su.CnName issuerUser, 
                                                            sm.ReleaseTime,smra.Id AuthId,smra.ReadableUId,smra.IsRead,smra.ReadTime 
                                                     From Sys_Message sm 
                                                     Inner Join Sys_MessageReadAuth smra On sm.Id = smra.MsgId
                                                     Inner Join Sys_Users su On sm.IssuerId = su.Id
                                                     Inner Join Sys_Department sd On su.DepId = sd.Id
                                                     Inner Join Sys_Users suAuth On smra.ReadableUId = suAuth.Id
                                                     Where sm.IsDel = 0
                                                     And smra.IsDel = 0 
                                                     And smra.ReadableUId = {0}
                                                     Order By ReleaseTime Desc ", dto.UserId);
                var _readableMsgList = await _sqlSugar.SqlQueryable<ReadbleMessageView>(msgSqlWhere).ToListAsync();
                if (_readableMsgList.Count > 0)
                {
                    result.Code = 0;
                    result.Msg = "成功!";
                    result.Data = _readableMsgList;
                }
                else
                {
                    result.Msg = "暂无该用户的消息!";
                }
            }

            return result;
        }

        /// <summary>
        /// 获取消息详细
        /// </summary>
        /// <param name="dto">msgInfo请求dto</param>
        /// <returns></returns>
        public async Task<Result> GetMsgInfo(MsgInfoDto dto)
        {
            Result result = new Result() { Code = -1, Msg = "未知错误", Data = null };

            if (dto.PortType == 1 || dto.PortType == 2)
            {
                string msgSqlWhere = string.Format(@"Select sm.Type,sc.CompanyName,sd.DepName,sjp.JobName,su.CnName,sm.ReleaseTime,
	                                                        sm.Title,sm.Content,smra.IsRead,smra.ReadTime
                                                     From Sys_Message sm
                                                     Inner Join Sys_MessageReadAuth smra On sm.Id = smra.MsgId
                                                     Inner Join Sys_Users su On sm.IssuerId = su.id
                                                     Inner Join Sys_JobPost sjp On su.JobPostId = sjp.Id
                                                     Inner Join Sys_Department sd On su.DepId = sd.Id
                                                     Inner Join Sys_Company sc On su.CompanyId = sc.Id
                                                     Where sm.IsDel = 0 
                                                     And sm.Id = {0}
                                                     And smra.IsDel = 0", dto.MsgId);
                var _readableMsgInfo = await _sqlSugar.SqlQueryable<MessageInfoView>(msgSqlWhere).FirstAsync();
                if (_readableMsgInfo != null)
                {
                    result.Code = 0;
                    result.Msg = "成功!";
                    result.Data = _readableMsgInfo;
                }
                else
                {
                    result.Msg = "暂无该用户的消息!";
                }
            }

            return result;
        }

        /// <summary>
        /// 消息设置已读
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> SetMsgRead(MsgSetReadDto dto)
        {
            Result result = new Result() { Code = -1, Msg = "未知错误", Data = null };

            if (dto.PortType == 1 || dto.PortType == 2)
            {

                var msgReadStatus = await _sqlSugar.Updateable<Sys_MessageReadAuth>()
                                    .Where(a => a.Id == dto.MsgAnthId)
                                    .SetColumns(a => new Sys_MessageReadAuth
                                    {
                                        IsRead = 1
                                    }).ExecuteCommandAsync();

                if (msgReadStatus > 0)
                {
                    result.Code = 0;
                    result.Msg = "成功!";
                }
                else
                {
                    result.Msg = "失败!";
                }
            }

            return result;
        }

        /// <summary>
        /// 消息设置已读
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> DelMsg(MsgDeleteDto dto)
        {
            Result result = new Result() { Code = -1, Msg = "未知错误", Data = null };

            if (dto.PortType == 1 || dto.PortType == 2)
            {

                var msgReadStatus = await _sqlSugar.Updateable<Sys_Message>()
                                    .Where(a => a.Id == dto.MsgId)
                                    .SetColumns(a => new Sys_Message
                                    {
                                        IsDel = 1,
                                        DeleteUserId = dto.UserId,
                                        DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                    }).ExecuteCommandAsync();

                if (msgReadStatus > 0)
                {
                    result.Code = 0;
                    result.Msg = "成功!";
                }
                else
                {
                    result.Msg = "操作失败!";
                }
            }

            return result;
        }
    }
}
