using OpenAuth.App.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using SqlSugar;
using OpenAuth.App.BaseApp.Request;
using DocumentFormat.OpenXml.Office2010.Excel;
using Infrastructure.Helpers;
using OpenAuth.Repository.Core;
using OpenAuth.App.BaseApp.WFTask;
using OpenAuth.App.BaseApp.ImMsgManager;
using Microsoft.Extensions.Configuration;
using DocumentFormat.OpenXml.EMMA;
using OpenAuth.App.BaseApp.Base;

namespace OpenAuth.App.BaseApp
{
    public class ImMsgApp : SqlSugarBaseApp<ImMsg, SugarDbContext>
    {
        private ChatsHub _hub;
        private readonly IConfiguration _configuration;
        private readonly ISqlSugarClient client;
        #region 构造函数
        public ImMsgApp(ChatsHub hub, ISqlSugarClient sqlSugarClient, ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<ImMsg> repository, IConfiguration configuration) : base(unitWork, repository, null)
        {
            _hub = hub;
            _configuration = configuration;
            this.client = sqlSugarClient;
        }
        #endregion

        #region 数据查询
        /// <summary>
        /// 分页获取列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<ImMsg>>>> LoadImMsgList(string sendUserId, string recvUserId, string keyword, int pageindex, int pagesize)
        {
            //定义且实例化分页数据
            RefAsync<int> totalCount = 0;
            //数据查询并返回
            var info = await this.Repository.AsQueryable()
                .Where(t => (t.SendUserid == sendUserId && t.RecvUserid == recvUserId))
                .WhereIF(!string.IsNullOrEmpty(keyword), t => t.Content.Contains(keyword))
                .OrderByDescending(t => t.CreateDate)
                .ToPageListAsync(pageindex, pagesize, totalCount);
            return new Response<PageInfo<List<ImMsg>>>
            {
                Result = new PageInfo<List<ImMsg>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }

        /// <summary>
        /// 获取收到的未读消息
        /// </summary>
        ///<param name="userId">当前登录用户id</param>
        /// <returns></returns>
        public async Task<Response<List<ImMsg>>> GetLastList(string userId)
        {
            //数据查询并返回
            var info = await this.Repository.AsQueryable()
                .Where(t => t.RecvUserid == userId&&t.IsRead==0)
                .OrderByDescending(t => t.CreateDate)
                .ToListAsync();
            return new Response<List<ImMsg>>
            {
                Result = info
            };
        }

        /// <summary>
        /// 分页获取系统消息
        /// </summary>
        /// <param name="myId"></param>
        /// <param name="sysCode"></param>
        /// <param name="keyword"></param>
        /// <param name="isDelete"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<ImMsg>>>> LoadSysImMsgList(string myId, string sysCode, string keyword, int? isDelete, int pageindex, int pagesize)
        {
            //定义且实例化分页数据
            RefAsync<int> totalCount = 0;
            //数据查询并返回
            var info = await this.Repository.AsQueryable()
                .Where(r=>r.Issystem==1)
                .WhereIF(!string.IsNullOrEmpty(myId),r=>r.RecvUserid==myId)
                .WhereIF(!string.IsNullOrEmpty(sysCode),r=>r.SendUserid==sysCode)
                .WhereIF(!string.IsNullOrEmpty(keyword), t => t.Content.Contains(keyword))
                .WhereIF(isDelete!=null,r=>r.DeleteMark==isDelete)
                .OrderByDescending(t => t.CreateDate)
                .ToPageListAsync(pageindex, pagesize, totalCount);
            return new Response<PageInfo<List<ImMsg>>>
            {
                Result = new PageInfo<List<ImMsg>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }

        //根据contentid获取任务信息
        public async Task<dynamic> GetInfoByContentId(string contentid)
        {
            var info= await client.Queryable<OpenAuth.Repository.Domain.WFTask>().Where(r=>r.Token==contentid)
                .Select<dynamic>(r => new
                {
                    r.Id,
                    r.ProcessCode,
                    r.Type,
                    r.ProcessId
                }).ToListAsync();
            return new Response<dynamic>
            {
                Result = info.Count > 0 ? info.First() : null
            };
        }
        #endregion

        #region 增删改
        /// <summary>
        /// 保存（新增）
        /// </summary>
        /// <param name="imsg">数据源实体</param>
        /// <returns></returns>
        public async Task<Response<bool>> SaveEntity(ImMsgReq imsg)
        {
            var flag = false;
            ImMsg entity = imsg.MapTo<ImMsg>();
            entity.MsgId = Guid.NewGuid().ToString();
            entity.CreateDate = DateTime.Now;
            entity.Issystem = 0;
            entity.DeleteMark = 0;

            flag = await this.Repository.InsertAsync(entity);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }
        /// <summary>
        /// 保存（新增）
        /// </summary>
        /// <param name="imsg">数据源实体</param>
        /// <returns></returns>
        public Response<bool> SaveEntitys(List<ImMsg> mglist)
        {
            var flag = false;
            flag =  this.Repository.InsertRange(mglist);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }
        /// <summary>
        /// 删除数据源
        /// </summary>
        /// <param name="id">主键</param>
        public async Task<Response<bool>> DeleteEntity(string id)
        {
            var flag = await this.Repository.DeleteByIdAsync(id);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除数据源
        /// </summary>
        /// <param name="ids">主键list</param>
        public async Task<Response<bool>> DeleteEntitys(List<string> ids)
        {
            List<ImMsg> list = new List<ImMsg>();
            list = this.Repository.AsQueryable().Where(r => ids.Contains(r.MsgId)).ToList();
            var flag = await this.Repository.DeleteAsync(list);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        /// <summary>
        /// 删除数据源(虚拟删除)
        /// </summary>
        /// <param name="id">主键</param>
        public async Task<Response<bool>> VirtualDeleteEntity(string id)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                await uow.ImMsg.UpdateAsync(r => new ImMsg { DeleteMark = 1 }, r => r.MsgId == id);
                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }                       
        }

        /// <summary>
        /// 删除数据源(虚拟删除)
        /// </summary>
        /// <param name="ids">主键list</param>
        public async Task<Response<bool>> VirtualDeleteEntitys(List<string> ids)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                foreach(var id in ids)
                {
                    await uow.ImMsg.UpdateAsync(r => new ImMsg { DeleteMark = 1 }, r => r.MsgId == id);
                }
                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }
        #endregion

        #region 确认阅读
        /// <summary>
        /// 确认阅读
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<Response<bool>> ReadMsg(string id)
        {
            using (var uow = base.UnitWork.CreateContext())
            {

                await uow.ImMsg.UpdateAsync(r => new ImMsg { IsRead = 1 }, r => r.MsgId == id);
                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="code">编码</param>
        /// <param name="userIdList">用户列表</param>
        /// <param name="content">消息内容</param>
        /// <param name="messageType">消息类型1.短信 2.邮箱 3.微信 4.IM（站内消息）</param>
        /// <param name="contentId">消息内容id</param>
        public async Task SendMsg(string code, IEnumerable<string> userIdList, string content, string messageType, string contentId = "")
        {
            if (!string.IsNullOrEmpty(content) && userIdList != null)
            {
                foreach (var userId in userIdList)
                {
                    if (messageType.IndexOf("4") != -1) // 站内消息
                    {
                        ImMsg iMMsgEntity = new ImMsg();
                        iMMsgEntity.SendUserid = code;
                        iMMsgEntity.RecvUserid = userId;
                        iMMsgEntity.Content = content;
                        iMMsgEntity.ContentId = contentId;
                        iMMsgEntity.Issystem = 1;
                        iMMsgEntity.IsRead = 0;
                        iMMsgEntity.DeleteMark = 0;

                        iMMsgEntity.MsgId = Guid.NewGuid().ToString();
                        iMMsgEntity.CreateDate = DateTime.Now;
                        await this.Repository.InsertAsync(iMMsgEntity);

                        var url = _configuration.GetSection("AppSetting:IMUrl").Value;
                        var imopen = _configuration.GetSection("AppSetting:IMOpen").Value;
                        await SendHubs.callMethod(url, imopen, "SendMsg", code, userId, content, iMMsgEntity.MsgId, 1);
                        //await _hub.SendMsg(url,imopen,code, userId, content, iMMsgEntity.MsgId, 1);
                    }
                }
            }
        }
        #endregion
    }
}
