using System;
using System.Collections.Generic;
using System.Text;
using MadRunFabric.Common;
using MadRunFabric.Common.Options;
using MadRunFabric.Model.TestUserTypeApi;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using TestUserTypeApi.IRepositories;
using System.Linq;

namespace TestUserTypeApi.Repositories
{
   public  class msgonlineRepository : BaseRepository<T_Msg_Chat, string>, ImsgonlineRepository
    {
        protected readonly ILogger<BaseRepository<T_Msg_Chat, string>> _logger;
        protected readonly IMongoCollection<T_Msg_Chat> _collection_T_Msg_Chat;
        protected readonly IMongoCollection<T_Msg_Chat_Map> _collection_T_Msg_Chat_Map;
        public msgonlineRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<T_Msg_Chat, string>> logger) : base(settings, logger)
        {
            _collection_T_Msg_Chat_Map = _context.GetCollection<T_Msg_Chat_Map>();
            _collection_T_Msg_Chat = _context.GetCollection<T_Msg_Chat>();
            _logger = logger;
        }
       
        public IEnumerable<object> GetList(int pageindex, int pagesize, int isread, out int recordCount)
        {
            var query =
                 from chat in _collection.AsQueryable()
                 join chatmap in _collection_T_Msg_Chat_Map.AsQueryable() on chat.id equals chatmap.chatid into chatDefa
                 where chat.isdelete == 0
                 select new TestUserTypeApi.Model.Dto.T_Msg_Chat
                 {
                     id = chat.id,
                     Msgcontent = chat.Msgcontent,
                     fromuserid = chat.fromuserid,//消息来源
                     touserid   = chat.touserid,//发送给谁
                     isonetype  = chat.isonetype,//1是微信接口进入的
                     isdelete   = chat.isdelete,
                     createtime  = chat.createtime,
                     isread      = chatDefa != null && chatDefa.Count() > 0 ? chatDefa.First().isread : 0
                 };
            #region 查询条件
            if (!string.IsNullOrEmpty(isread.ToString()))
                query = query.Where(it => it.isread == isread);
            query = query.Where(it => it.isread == 0);
            #endregion
            //var list = query.OrderByDescending(it => it.createtime);
            recordCount = query.Count();
            var list = query.Skip((pageindex - 1) * pagesize).Take(pagesize);
            return list;
        }
    }
}
