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

namespace EquipmentApi.Repositories
{
    public class Pro_Project_LogRepository : BaseRepository<Pro_Project_Log, string>, IPro_Project_LogRepository
    {
        protected readonly ILogger<BaseRepository<Pro_Project_Log, string>> _logger;
        protected readonly IMongoCollection<Sys_Provinces> _collection_sys_provinces;
        protected readonly IMongoCollection<Sys_City> _collection_sys_city;
        protected readonly IMongoCollection<Sys_DictionaryValue> _collection_sys_dictionaryvalue;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        public Pro_Project_LogRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Pro_Project_Log, string>> logger) : base(settings, logger)
        {
            _collection_sys_provinces = _context.GetCollection<Sys_Provinces>();
            _collection_sys_city = _context.GetCollection<Sys_City>();
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();
            _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<object> GetListsByPage(string keyword, int type, string projectid, string stime, string etime, UserInfoModel userinfo, int pageIndex, int pageSize, out int recordCount)
        {

            //关联查询 Pro_ProjectDto
            var proinfo = from pro in _collection_pro_project_info.AsQueryable()
                          join province in _collection_sys_provinces.AsQueryable() on pro.project_province equals province.provincecode into provinceDefa
                          join city in _collection_sys_city.AsQueryable() on pro.project_city equals city.citycode into cityDefa
                          join dic_pro in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_property equals dic_pro.id into dic_proDefa
                          join dic_nur in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_nature equals dic_nur.id into dic_nurDefa
                          where pro.isdelete == 0
                          orderby pro.createtime descending
                          select new
                          {
                              pro.id,
                              pro.project_name,
                              pro.project_province,
                              provincename = provinceDefa != null && provinceDefa.Count() > 0 ? provinceDefa.First().provincename : null,
                              pro.project_city,
                              cityname = cityDefa != null && cityDefa.Count() > 0 ? cityDefa.First().cityname : null,
                              pro.project_property,
                              protypename = dic_proDefa != null && dic_proDefa.Count() > 0 ? dic_proDefa.First().name : null,
                              pro.project_nature,
                              naturename = dic_nurDefa != null && dic_nurDefa.Count() > 0 ? dic_nurDefa.First().name : null
                          };

            var query = from p in _collection.AsQueryable()
                        where p.isdelete == 0
                        orderby p.createtime descending
                        select new { p.id, p.projectid, p.type, p.details, p.createby, p.createtime };

            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.details.Contains(keyword));     //项目名称，负责人
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid == projectid);
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime + " 00:00:00"));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime + " 23:59:59"));
            if (type != 0)
                query = query.Where(it => it.type == type);
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion

            recordCount = query.Count();
            var querys = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var pros = querys.Select(p => p.projectid);
            var prolist = proinfo.Where(p => pros.Contains(p.id)).ToList();

            var list = querys.Select(p =>
            {
                var pro = prolist.Where(q => q.id == p.projectid).FirstOrDefault();
                string projectname = string.Empty, provincecode = string.Empty, provincename = string.Empty, citycode = string.Empty, cityname = string.Empty,
                natureid = string.Empty, naturename = string.Empty, propertyid = string.Empty, protypename = string.Empty;
                if (pro != null)
                {
                    projectname = pro.project_name;
                    provincecode = pro.project_province;
                    provincename = pro.provincename;
                    citycode = pro.project_city;
                    cityname = pro.cityname;
                    natureid = pro.project_nature;
                    naturename = pro.naturename;
                    propertyid = pro.project_property;
                    protypename = pro.protypename;
                }
                return new
                {
                    p.id,
                    projectname,
                    provincecode,
                    provincename,
                    citycode,
                    cityname,
                    natureid,
                    naturename,
                    propertyid,
                    protypename,
                    p.type,
                    p.details,
                    p.createby,
                    p.createtime
                };
            });
            return list;
        }

        /// <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> GetAppLists(string keyword, int type, string projectid, UserInfoModel userinfo)
        {
            //关联查询 Pro_ProjectDto
            var proinfo = from pro in _collection_pro_project_info.AsQueryable()
                          join province in _collection_sys_provinces.AsQueryable() on pro.project_province equals province.provincecode into provinceDefa
                          join city in _collection_sys_city.AsQueryable() on pro.project_city equals city.citycode into cityDefa
                          join dic_pro in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_property equals dic_pro.id into dic_proDefa
                          join dic_nur in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_nature equals dic_nur.id into dic_nurDefa
                          where pro.isdelete == 0
                          orderby pro.createtime descending
                          select new
                          {
                              pro.id,
                              pro.project_name,
                              pro.project_province,
                              provincename = provinceDefa != null && provinceDefa.Count() > 0 ? provinceDefa.First().provincename : null,
                              pro.project_city,
                              cityname = cityDefa != null && cityDefa.Count() > 0 ? cityDefa.First().cityname : null,
                              pro.project_property,
                              protypename = dic_proDefa != null && dic_proDefa.Count() > 0 ? dic_proDefa.First().name : null,
                              pro.project_nature,
                              naturename = dic_nurDefa != null && dic_nurDefa.Count() > 0 ? dic_nurDefa.First().name : null
                          };

            var query = from p in _collection.AsQueryable()
                        where p.isdelete == 0
                        orderby p.createtime descending
                        select new { p.id, p.projectid, p.type, p.details, p.createby, p.createtime };

            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.details.Contains(keyword));     //项目名称，负责人
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid == projectid);
            if (type != 0)
                query = query.Where(it => it.type == type);
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion

            var querys = query.ToList();
            var pros = querys.Select(p => p.projectid);
            var prolist = proinfo.Where(p => pros.Contains(p.id)).ToList();

            var list = querys.Select(p =>
            {
                var pro = prolist.Where(q => q.id == p.projectid).FirstOrDefault();
                string projectname = string.Empty, provincecode = string.Empty, provincename = string.Empty, citycode = string.Empty, cityname = string.Empty,
                natureid = string.Empty, naturename = string.Empty, propertyid = string.Empty, protypename = string.Empty;
                if (pro != null)
                {
                    projectname = pro.project_name;
                    provincecode = pro.project_province;
                    provincename = pro.provincename;
                    citycode = pro.project_city;
                    cityname = pro.cityname;
                    natureid = pro.project_nature;
                    naturename = pro.naturename;
                    propertyid = pro.project_property;
                    protypename = pro.protypename;
                }
                return new
                {
                    p.id,
                    projectname,
                    provincecode,
                    provincename,
                    citycode,
                    cityname,
                    natureid,
                    naturename,
                    propertyid,
                    protypename,
                    p.type,
                    p.details,
                    p.createby,
                    p.createtime
                };
            });
            return list;
        }

        /// <summary>
        /// Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string id)
        {
            var query = from p in _collection.AsQueryable()
                        where p.isdelete == 0 && p.id == id
                        orderby p.createtime descending
                        select new { p.id, p.projectid, p.type, p.details, p.createby, p.createtime };

            var logmodel = query.FirstOrDefault();
            if (logmodel != null)
            {
                string projectname = string.Empty, provincecode = string.Empty, provincename = string.Empty, citycode = string.Empty, cityname = string.Empty,
                natureid = string.Empty, naturename = string.Empty, propertyid = string.Empty, protypename = string.Empty;

                var proinfo = from pro in _collection_pro_project_info.AsQueryable()
                              join province in _collection_sys_provinces.AsQueryable() on pro.project_province equals province.provincecode into provinceDefa
                              join city in _collection_sys_city.AsQueryable() on pro.project_city equals city.citycode into cityDefa
                              join dic_pro in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_property equals dic_pro.id into dic_proDefa
                              join dic_nur in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_nature equals dic_nur.id into dic_nurDefa
                              where pro.isdelete == 0 && pro.id == logmodel.projectid
                              orderby pro.createtime descending
                              select new
                              {
                                  pro.id,
                                  pro.project_name,
                                  pro.project_province,
                                  provincename = provinceDefa != null && provinceDefa.Count() > 0 ? provinceDefa.First().provincename : null,
                                  pro.project_city,
                                  cityname = cityDefa != null && cityDefa.Count() > 0 ? cityDefa.First().cityname : null,
                                  pro.project_property,
                                  protypename = dic_proDefa != null && dic_proDefa.Count() > 0 ? dic_proDefa.First().name : null,
                                  pro.project_nature,
                                  naturename = dic_nurDefa != null && dic_nurDefa.Count() > 0 ? dic_nurDefa.First().name : null
                              };
                var promodel = proinfo.FirstOrDefault();
                if (promodel != null)
                {
                    projectname = promodel.project_name;
                    provincecode = promodel.project_province;
                    provincename = promodel.provincename;
                    citycode = promodel.project_city;
                    cityname = promodel.cityname;
                    natureid = promodel.project_nature;
                    naturename = promodel.naturename;
                    propertyid = promodel.project_property;
                    protypename = promodel.protypename;
                }

                var model = new
                {
                    logmodel.id,
                    projectname,
                    provincecode,
                    provincename,
                    citycode,
                    cityname,
                    natureid,
                    naturename,
                    propertyid,
                    protypename,
                    logmodel.type,
                    logmodel.details,
                    logmodel.createby,
                    logmodel.createtime
                };

                return model;
            }
            else
            {
                return null;
            }
        }

    }
}