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

namespace MessageApi.Repositories
{
    public class Wo_Maintain_BaseRepository : BaseRepository<Wo_Maintain_Base, string>, IWo_Maintain_BaseRepository
    {
        protected readonly ILogger<BaseRepository<Wo_Maintain_Base, string>> _logger;
        protected readonly IMongoCollection<Wo_Order_User_Map> _collection_wo_order_user_map;
        public Wo_Maintain_BaseRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Wo_Maintain_Base, string>> logger) : base(settings, logger)
        {
            _collection_wo_order_user_map = _context.GetCollection<Wo_Order_User_Map>();
            _logger = logger;
        }

        /// <summary>
        /// Linq 关联查询 分页 保养工单 - 不用
        /// </summary>
        /// <returns></returns>
        public IEnumerable<WoWorkOrderListDto> GetList(string usercode)
        {
            var query =
                from repair in _collection.AsQueryable()
                join order_user in _collection_wo_order_user_map.AsQueryable() on repair.wocode equals order_user.wocode into order_userDefa
                where repair.isdelete == false
                select new WoWorkOrderListDto
                {
                    id = repair.id,
                    //equipmentid = repair.equipmentid,
                    wocode = repair.wocode,
                    wostate = repair.wostate,
                    content = repair.maintaincontent,
                    createby = repair.createby,
                    createtime = repair.createtime,
                    readby = order_userDefa != null && order_userDefa.Count() > 0 ? order_userDefa.First().readby : "",
                    isread = order_userDefa != null && order_userDefa.Count() > 0 ? order_userDefa.First().isread : 0
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(usercode))
                query = query.Where(it => it.readby == usercode);
            query = query.Where(it => it.isread == 0);
            #endregion
            var list = query.OrderByDescending(it => it.createtime);
            return list;
        }
    }
}
