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

namespace DistributionApi.Repositories
{
    public class Distri_Workorder_PlanRepository : BaseRepository<Distri_Workorder_Plan, string>, IDistri_Workorder_PlanRepository
    {
        protected readonly ILogger<BaseRepository<Distri_Workorder_Plan, string>> _logger;
        protected readonly IMongoCollection<Sys_DictionaryValue> _collection_sys_dictionaryvalue;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        protected readonly IMongoCollection<Distri_Workorder_PlanTask> _collection_distri_workorder_plantask;
        protected readonly IMongoCollection<Distri_Workorder> _collection_distri_workorder;
        protected readonly IMongoCollection<Sys_SystemConfig> _collection_sys_systemconfig;
        public Distri_Workorder_PlanRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Distri_Workorder_Plan, string>> logger) : base(settings, logger)
        {
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();  //获取集合
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();  //获取集合
            _collection_distri_workorder_plantask = _context.GetCollection<Distri_Workorder_PlanTask>();  //获取集合
            _collection_distri_workorder = _context.GetCollection<Distri_Workorder>();  //获取集合
            _collection_sys_systemconfig = _context.GetCollection<Sys_SystemConfig>();
            _logger = logger;
        }

        /// <summary>
        /// 列表 -  Linq 关联查询 分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<Distri_Workorder_PlanDto> GetListsByPage(string keyword, string projectid, int planstate, UserAccountInfoModel userinfo, int pageIndex, int pageSize, out int recordCount)
        {
            //关联查询
            var query =
                 from plan in _collection.AsQueryable()
                 join proje in _collection_pro_project_info.AsQueryable() on plan.projectid equals proje.id into proje_Defa
                 where plan.isdelete == 0
                 orderby plan.createtime descending
                 select new Distri_Workorder_PlanDto
                 {
                     id = plan.id,
                     channel = plan.channel,
                     planname = plan.planname,
                     plancontent = plan.plancontent,
                     planstate = plan.planstate,
                     hangfireid = plan.hangfireid,
                     startdate = plan.startdate,
                     enddate = plan.enddate,
                     projectid = plan.projectid,
                     projectname = proje_Defa != null && proje_Defa.Count() > 0 ? proje_Defa.First().project_name : null,
                     goodslist = plan.goodslist,
                     //plan.receiverlist,
                     deliverylist = plan.deliverylist,
                     deliveryname = plan.deliveryname,
                     deliverytel = plan.deliverytel,
                     dealby = plan.dealby,
                     dealtime = plan.dealtime,
                     createtby = plan.createtby,
                     createtime = plan.createtime
                 };
            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.planname.Contains(keyword) || it.plancontent.Contains(keyword));     //计划名称，内容       
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid == projectid);
            if (planstate >= 0)
                query = query.Where(it => it.planstate == planstate);
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion

            recordCount = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }

        /// <summary>
        /// Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Distri_Workorder_PlanDto GetDetails(string id)
        {
            //关联查询
            var query =
                 from plan in _collection.AsQueryable()
                 join proje in _collection_pro_project_info.AsQueryable() on plan.projectid equals proje.id into proje_Defa
                 where plan.isdelete == 0 && plan.id == id
                 orderby plan.createtime descending
                 select new Distri_Workorder_PlanDto
                 {
                     id = plan.id,
                     channel = plan.channel,
                     planname = plan.planname,
                     plancontent = plan.plancontent,
                     planstate = plan.planstate,
                     hangfireid = plan.hangfireid,
                     startdate = plan.startdate,
                     enddate = plan.enddate,
                     projectid = plan.projectid,
                     projectname = proje_Defa != null && proje_Defa.Count() > 0 ? proje_Defa.First().project_name : null,
                     goodslist = plan.goodslist,
                     //plan.receiverlist,
                     deliverylist = plan.deliverylist,
                     deliveryname = plan.deliveryname,
                     deliverytel = plan.deliverytel,
                     dealby = plan.dealby,
                     dealtime = plan.dealtime,
                     createtby = plan.createtby,
                     createtime = plan.createtime
                 };
            var model = query.FirstOrDefault();
            if (model != null)
            {
                return model;
            }
            return null;
        }

        /// <summary>
        /// 抢单时效 / 待配送工单滞留时效 
        /// </summary>
        /// <param name="code">编号</param>
        /// <returns></returns>
        public int GetLimitCount(string code)
        {
            int m = 0;
            //1、配送岗 抢单时效  3分钟（某单子此时间内没人抢，系统强制分配）
            var model = _collection_sys_systemconfig.Find(p => p.paramcode == code).FirstOrDefault();
            if (model != null)
            {
                m = Int32.Parse(model.paramvalue);
            }
            return m;
        }

        #region 计划任务
        /// <summary>
        /// 列表 -  Linq 关联查询 分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<object> GetPlanTaskListsByPage(string keyword, string projectid, string stime, string etime, int planwostate, UserAccountInfoModel userinfo, int pageIndex, int pageSize, out int recordCount)
        {
            //关联查询
            var query =
                 from planwo in _collection_distri_workorder_plantask.AsQueryable()
                 join proje in _collection_pro_project_info.AsQueryable() on planwo.projectid equals proje.id into proje_Defa
                 where planwo.isdelete == 0
                 orderby planwo.createtime descending
                 select new
                 {
                     planwo.id,
                     planwo.channel,
                     planwo.wocode,
                     planwo.name,
                     planwo.content,
                     planwo.planwostate,
                     planwo.projectid,
                     projectname = proje_Defa != null && proje_Defa.Count() > 0 ? proje_Defa.First().project_name : null,
                     planwo.joinuserlist,
                     planwo.goodslist,
                     //planwo.receiverlist,
                     planwo.deliverylist,
                     planwo.deliveryname,
                     planwo.deliverytel,
                     planwo.dealby,
                     planwo.dealtime,
                     planwo.createtby,
                     planwo.createtime
                 };
            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.wocode.Contains(keyword) || it.name.Contains(keyword) || it.content.Contains(keyword) || it.dealby.Contains(keyword));     //计划名称，内容       
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid == projectid);
            if (planwostate >= 0)
                query = query.Where(it => it.planwostate == planwostate);
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion

            recordCount = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return list;
        }

        /// <summary>
        /// Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Distri_Workorder_PlanTaskDto GetPlanTaskDetails(string id)
        {
            //关联查询
            var query =
                 from planwo in _collection_distri_workorder_plantask.AsQueryable()
                 join proje in _collection_pro_project_info.AsQueryable() on planwo.projectid equals proje.id into proje_Defa
                 where planwo.isdelete == 0 && planwo.id == id
                 orderby planwo.createtime descending
                 select new Distri_Workorder_PlanTaskDto
                 {
                     id = planwo.id,
                     planid = planwo.planid,
                     channel = planwo.channel,
                     wocode = planwo.wocode,
                     name = planwo.name,
                     content = planwo.content,
                     planwostate = planwo.planwostate,
                     projectid = planwo.projectid,
                     projectname = proje_Defa != null && proje_Defa.Count() > 0 ? proje_Defa.First().project_name : null,
                     joinuserlist = planwo.joinuserlist,
                     goodslist = planwo.goodslist,
                     //receiverlist=planwo.receiverlist,
                     deliverylist = planwo.deliverylist,
                     deliveryname = planwo.deliveryname,
                     deliverytel = planwo.deliverytel,
                     statetime = planwo.statetime,
                     dealby = planwo.dealby,
                     dealtime = planwo.dealtime,
                     createtby = planwo.createtby,
                     createtime = planwo.createtime
                 };
            var model = query.FirstOrDefault();
            if (model != null)
            {
                return model;
            }
            return null;
        }
        #endregion

    }
}
