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

namespace EquipmentApi.Repositories
{
    public class Wo_TimeOutRepository : BaseRepository<Wo_TimeOut, string>, IWo_TimeOutRepository
    {
        protected readonly ILogger<BaseRepository<Wo_TimeOut, string>> _logger;
        public Wo_TimeOutRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Wo_TimeOut, string>> logger) : base(settings, logger)
        {
            _logger = logger;
        }

        public object GetDetails(string id)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<object> GetListsByPage(int wotype, string stime, string etime, string rolecode, string usercode, int pageIndex, int pageSize, out int recordCount)
        {
            //关联查询
            var query =
                from to in _collection.AsQueryable()
                where to.isdelete == false
                orderby to.createtime descending
                select new
                {
                    to.id,
                    to.woid,
                    to.wocode,
                    to.wotype,
                    to.isover,
                    to.istimeout,
                    to.manager,
                    to.timeoutreason,
                    to.times,
                    to.touser,
                    to.tousername,
                    to.grade,
                    to.createtime,
                };
            #region 查询条件
            if (wotype>0)
                query = query.Where(it => it.wotype == wotype);
            
            if (!string.IsNullOrWhiteSpace(stime))
            {
                DateTime dt2 = DateTime.Now;
                if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                    query = query.Where(it => it.createtime >= dt2);
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                DateTime dt2 = DateTime.Now;
                if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                    query = query.Where(it => it.createtime <= dt2);
            }
            if (string.IsNullOrWhiteSpace(rolecode) || !rolecode.Equals("YWZG"))
            {
                //项目主管可以看到所有工单并进行转派
                //其他角色只能看到当天及当天之前的工单
                //query = query.Where(it => it.advancetime <= DateTime.Now);
                //if (rolecode.Equals("YWYG"))//运维员工只能看到自己的工单
                //    query = query.Where(it => it.checkby == usercode);
            }
            #endregion
            recordCount = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }
    }
}