//using ConfigurationApi.Model;
using EquipmentApi.IRepositories;
using MadRunFabric.Model;
using EquipmentApi.Model.Dto;
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.Common.Enums;

namespace EquipmentApi.Repositories
{
    /// <summary>
    /// 设备信息
    /// </summary>
    public class Eqp_Equipment_InfoRepository : BaseRepository<Eqp_Equipment_Info, string>, IEqp_Equipment_InfoRepository
    {
        protected readonly ILogger<BaseRepository<Eqp_Equipment_Info, string>> _logger;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        protected readonly IMongoCollection<Sys_Provinces> _collection_sys_provinces;
        protected readonly IMongoCollection<Sys_City> _collection_sys_city;
        protected readonly IMongoCollection<Sys_Building> _collection_sys_buliding;
        protected readonly IMongoCollection<Sys_Floor> _collection_sys_floor;
        protected readonly IMongoCollection<Sys_DictionaryValue> _collection_sys_dictionaryvalue;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        public Eqp_Equipment_InfoRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Eqp_Equipment_Info, string>> logger) : base(settings, logger)
        {
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();//获取集合
            _collection_sys_provinces = _context.GetCollection<Sys_Provinces>();
            _collection_sys_city = _context.GetCollection<Sys_City>();
            _collection_sys_buliding = _context.GetCollection<Sys_Building>();
            _collection_sys_floor = _context.GetCollection<Sys_Floor>();
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();
            _collection_sys_user_account = _context.GetCollection<Sys_User_Account>();
            _logger = logger;
        }

        /// <summary>
        /// Linq 关联查询 分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="provincecode"></param>
        /// <param name="citycode"></param>
        /// <param name="projectid"></param>
        /// <param name="protype"></param>
        /// <param name="systemid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<object> GetListsByPage(string keyword, string provincecode, string citycode, string projectid, string protype,
            string bulidid, string floorid, string systemid, UserAccountInfoModel userinfo, int pageIndex, int pageSize, out int recordCount)
        {
            var query =
                from p in _collection.AsQueryable()
                join dic_system in _collection_sys_dictionaryvalue.AsQueryable() on p.systemid equals dic_system.id into dic_systemDefa
                join dic_protype in _collection_sys_dictionaryvalue.AsQueryable() on p.protypeid equals dic_protype.id into dic_protypeDefa
                join proje in _collection_pro_project_info.AsQueryable() on p.projectid equals proje.id into projeDefa
                join sysprovinces in _collection_sys_provinces.AsQueryable() on p.province equals sysprovinces.provincecode into sys_provincesDefa
                join syscity in _collection_sys_city.AsQueryable() on p.city equals syscity.citycode into sys_cityDefa
                join bld in _collection_sys_buliding.AsQueryable() on p.buildid equals bld.id into bldDefa
                join flr in _collection_sys_floor.AsQueryable() on p.floorid equals flr.id into flrDefa
                where p.isdelete == 0
                select new
                {
                    p.id,
                    p.equipment_name,
                    p.equipment_number,
                    p.equipment_model,
                    p.systemid,
                    systemname = dic_systemDefa.Count() > 0 ? dic_systemDefa.First().name : "",
                    p.floorid,
                    floorname = (flrDefa.Count() > 0 ? flrDefa.First().floorname : "") + " " + (flrDefa.Count() > 0 ? flrDefa.First().remark : ""),
                    p.buildid,
                    bulidingname = bldDefa.Count() > 0 ? bldDefa.First().buildname : "",
                    p.projectid,
                    projectname = projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
                    p.province,
                    provincename = sys_provincesDefa.Count() > 0 ? sys_provincesDefa.First().provincename : "",
                    p.city,
                    cityname = sys_cityDefa.Count() > 0 ? sys_cityDefa.First().cityname : "",
                    p.protypeid,
                    protypename = dic_protypeDefa.Count() > 0 ? dic_protypeDefa.First().name : "",
                    p.equipment_image,
                    p.purchase_order,
                    p.maintenance_order,
                    p.install_place,
                    p.use_startdate,
                    p.use_enddate,
                    p.quality_startdate,
                    p.quality_enddate,
                    p.extensionlist,
                    p.createby,
                    p.createtime
                };


            #region 查询条件

            if (!string.IsNullOrEmpty(provincecode))
                query = query.Where(it => it.province.Equals(provincecode));
            if (!string.IsNullOrEmpty(citycode))
                query = query.Where(it => it.city.Equals(citycode));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid.Equals(projectid));
            if (!string.IsNullOrEmpty(bulidid))
                query = query.Where(it => it.buildid.Equals(bulidid));
            if (!string.IsNullOrEmpty(floorid))
                query = query.Where(it => it.floorid.Equals(floorid));
            if (!string.IsNullOrEmpty(protype))
                query = query.Where(it => it.protypeid.Equals(protype));
            if (!string.IsNullOrEmpty(systemid))
                query = query.Where(it => it.systemid.Equals(systemid));
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.equipment_name.Contains(keyword) || it.equipment_number.Contains(keyword));

            //if (userinfo.isallproject == 0)
            //    query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion

            recordCount = query.Count();
            var list = query.OrderByDescending(it => it.createtime).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return list;
        }

        /// <summary>
        /// Linq 关联查询 - App
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="provincecode"></param>
        /// <param name="citycode"></param>
        /// <param name="projectid"></param>
        /// <param name="protype"></param>
        /// <param name="systemid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<object> GetAppLists(string keyword, string provincecode, string citycode, string projectid, string protype,
            string bulidid, string floorid, string systemid, UserAccountInfoModel userinfo, string equipnum)
        {
            var query =
                from p in _collection.AsQueryable()
                join dic_system in _collection_sys_dictionaryvalue.AsQueryable() on p.systemid equals dic_system.id into dic_systemDefa
                join dic_protype in _collection_sys_dictionaryvalue.AsQueryable() on p.protypeid equals dic_protype.id into dic_protypeDefa
                join proje in _collection_pro_project_info.AsQueryable() on p.projectid equals proje.id into projeDefa
                join sysprovinces in _collection_sys_provinces.AsQueryable() on p.province equals sysprovinces.provincecode into sys_provincesDefa
                join syscity in _collection_sys_city.AsQueryable() on p.city equals syscity.citycode into sys_cityDefa
                join bld in _collection_sys_buliding.AsQueryable() on p.buildid equals bld.id into bldDefa
                join flr in _collection_sys_floor.AsQueryable() on p.floorid equals flr.id into flrDefa
                where p.isdelete == 0
                select new
                {
                    p.id,
                    p.equipment_name,
                    p.equipment_number,
                    p.equipment_model,
                    p.systemid,
                    systemname = dic_systemDefa != null && dic_systemDefa.Count() > 0 ? dic_systemDefa.First().name : "",
                    p.floorid,
                    floorname = (flrDefa != null && flrDefa.Count() > 0 ? flrDefa.First().floorname : "") + " " + (flrDefa != null && flrDefa.Count() > 0 ? flrDefa.First().remark : ""),
                    p.buildid,
                    bulidingname = bldDefa!=null && bldDefa.Count() > 0 ? bldDefa.First().buildname : "",
                    p.projectid,
                    projectname = projeDefa!=null && projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
                    projectdelete = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().isdelete : 0,
                    p.province,
                    provincename = sys_provincesDefa!=null && sys_provincesDefa.Count() > 0 ? sys_provincesDefa.First().provincename : "",
                    p.city,
                    cityname = sys_cityDefa!=null && sys_cityDefa.Count() > 0 ? sys_cityDefa.First().cityname : "",
                    p.protypeid,
                    protypename = dic_protypeDefa!=null && dic_protypeDefa.Count() > 0 ? dic_protypeDefa.First().name : "",
                    p.equipment_image,
                    p.purchase_order,
                    p.maintenance_order,
                    p.install_place,
                    p.use_startdate,
                    p.use_enddate,
                    p.quality_startdate,
                    p.quality_enddate,
                    p.extensionlist,
                    p.createby,
                    p.createtime
                };


            #region 查询条件
            query = query.Where(it => it.projectdelete == 0);
            if (!string.IsNullOrEmpty(provincecode))
                query = query.Where(it => it.province.Equals(provincecode));
            if (!string.IsNullOrEmpty(citycode))
                query = query.Where(it => it.city.Equals(citycode));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.projectid.Equals(projectid));
            if (!string.IsNullOrEmpty(bulidid))
                query = query.Where(it => it.buildid.Equals(bulidid));
            if (!string.IsNullOrEmpty(floorid))
                query = query.Where(it => it.floorid.Equals(floorid));
            if (!string.IsNullOrEmpty(protype))
                query = query.Where(it => it.protypeid.Equals(protype));
            if (!string.IsNullOrEmpty(systemid))
                query = query.Where(it => it.systemid.Equals(systemid));
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.equipment_name.Contains(keyword) || it.equipment_number.Contains(keyword));
            if (!string.IsNullOrEmpty(equipnum ))
                query = query.Where(it => it.equipment_number.Equals(equipnum));

            //if (userinfo.isallproject == 0)
            //    query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            #endregion

            return query;
        }

        /// <summary>
        /// Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string id, UserAccountInfoModel userinfo)
        {
            bool bl = false;
            if (userinfo.type == 2)
            {
                var bduser = from p in _collection_sys_user_account.AsQueryable() where p.delete_flag == false && p.weixin == userinfo.usercode && p.type != 2 select p;
                if (bduser.Count() == 0)
                {
                    bl = true;
                }
            }
            if (bl)
            {
                return null;
            }
            var query =
                from p in _collection.AsQueryable()
                join dic_system in _collection_sys_dictionaryvalue.AsQueryable() on p.systemid equals dic_system.id into dic_systemDefa
                join dic_protype in _collection_sys_dictionaryvalue.AsQueryable() on p.protypeid equals dic_protype.id into dic_protypeDefa
                join proje in _collection_pro_project_info.AsQueryable() on p.projectid equals proje.id into projeDefa
                join sysprovinces in _collection_sys_provinces.AsQueryable() on p.province equals sysprovinces.provincecode into sys_provincesDefa
                join syscity in _collection_sys_city.AsQueryable() on p.city equals syscity.citycode into sys_cityDefa
                join bld in _collection_sys_buliding.AsQueryable() on p.buildid equals bld.id into bldDefa
                join flr in _collection_sys_floor.AsQueryable() on p.floorid equals flr.id into flrDefa
                where p.isdelete == 0
                select new
                {
                    p.id,
                    p.equipment_name,
                    p.equipment_number,
                    p.equipment_model,
                    p.systemid,
                    systemname = dic_systemDefa.Count() > 0 ? dic_systemDefa.First().name : "",
                    p.floorid,
                    floorname = (flrDefa.Count() > 0 ? flrDefa.First().floorname : "") + " " + (flrDefa.Count() > 0 ? flrDefa.First().remark : ""),
                    p.buildid,
                    bulidingname = bldDefa.Count() > 0 ? bldDefa.First().buildname : "",
                    p.projectid,
                    projectname = projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
                    p.province,
                    provincename = sys_provincesDefa.Count() > 0 ? sys_provincesDefa.First().provincename : "",
                    p.city,
                    cityname = sys_cityDefa.Count() > 0 ? sys_cityDefa.First().cityname : "",
                    p.protypeid,
                    protypename = dic_protypeDefa.Count() > 0 ? dic_protypeDefa.First().name : "",
                    p.equipment_image,
                    p.purchase_order,
                    p.maintenance_order,
                    p.install_place,
                    p.use_startdate,
                    p.use_enddate,
                    p.quality_startdate,
                    p.quality_enddate,
                    p.extensionlist,
                    p.createby,
                    p.createtime
                };

            if (id.Length == 24)
            {
                query = query.Where(p => p.id == id);
            }
            else
            {
                query = query.Where(p => p.equipment_number == id);
            }

            var model = query.FirstOrDefault();
            if (model != null)
            {
                return model;
            }
            return null;
        }

        /// <summary>
        /// 获取五级联动
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetFiveTree(UserAccountInfoModel userinfo)
        {
            var query =
                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 //项目性质
                };
            //if (userinfo.isallproject == 0)
            //    query = query.Where(it => userinfo.projectlist.Contains(it.id));
            var projectlist = query.ToList();
            var bulidlist = (from equ in _collection_sys_buliding.AsQueryable() where equ.isdelete == 0 select equ).ToList();
            var floorlist = (from equ in _collection_sys_floor.AsQueryable() where equ.isdelete == 0 select equ).ToList();
            var provincelist = projectlist.Select(p => new { p.project_province, p.provincename }).Distinct().ToList();
            var citylist = projectlist.Select(p => new { p.project_province, p.project_city, p.cityname }).Distinct().ToList();

            var result = provincelist.Select(p => new
            {
                code = p.project_province,
                name = p.provincename,
                parentcode = -1,
                entityJson = citylist.Where(q => q.project_province == p.project_province).Select(q => new
                {
                    code = q.project_city,
                    name = q.cityname,
                    parentcode = q.project_province,
                    entityJson = projectlist.Where(j => j.project_city == q.project_city).Select(j => new
                    {
                        id = j.id,
                        code = j.id,
                        name = j.project_name,
                        protypeid = j.project_property,
                        j.protypename,
                        natureid = j.project_nature,
                        j.naturename,
                        parentcode = q.project_city,
                        entityJson = bulidlist.Where(b => b.projectid == j.id).Select(b => new
                        {
                            id = b.id,
                            code = b.id,
                            name = b.buildname,
                            parentcode = j.id,
                            entityJson = floorlist.Where(f => f.buildid == b.id).Select(f => new
                            {
                                id = f.id,
                                code = f.id,
                                name = f.floorname + " " + f.remark,
                                remark = f.remark,
                                parentcode = b.id
                            })
                        })
                    })
                })
            });
            return result;
        }

        /// <summary>
        /// 获取项目树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetProjectTree(UserAccountInfoModel userinfo)
        {
            var query =
                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 //项目性质
                };
            //if (userinfo.isallproject == 0)
            //    query = query.Where(it => userinfo.projectlist.Contains(it.id));
            var projectlist = query.ToList();

            var provincelist = projectlist.Select(p => new { p.project_province, p.provincename }).Distinct().ToList();
            var citylist = projectlist.Select(p => new { p.project_province, p.project_city, p.cityname }).Distinct().ToList();

            var result = provincelist.Select(p => new
            {
                code = p.project_province,
                name = p.provincename,
                parentcode = -1,
                entityJson = citylist.Where(q => q.project_province == p.project_province).Select(q => new
                {
                    code = q.project_city,
                    name = q.cityname,
                    parentcode = q.project_province,
                    entityJson = projectlist.Where(j => j.project_city == q.project_city).Select(j => new
                    {
                        id = j.id,
                        code = j.id,
                        name = j.project_name,
                        protypeid = j.project_property,
                        j.protypename,
                        natureid = j.project_nature,
                        j.naturename,
                        parentcode = q.project_city
                    })
                })
            });
            return result;
        }

        /// <summary>
        /// 获取楼层树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetAddressTree(string projectid)
        {
            var bulidlist = (from equ in _collection_sys_buliding.AsQueryable() where equ.isdelete == 0 && equ.projectid== projectid select equ).ToList();
            var blds = bulidlist.Select(p => p.id).ToList();
            var floorlist = (from equ in _collection_sys_floor.AsQueryable() where equ.isdelete == 0 && blds.Contains(equ.buildid) select equ).ToList();

            var result = bulidlist.Select(b => new
            {
                id = b.id,
                code = b.id,
                name = b.buildname,
                parentcode = projectid,
                entityJson = floorlist.Where(f => f.buildid == b.id).Select(f => new
                {
                    id = f.id,
                    code = f.id,
                    name = f.floorname + " " + f.remark,
                    departmentname = f.remark,
                    parentcode = b.id
                })
            });
            return result;
        }

        /// <summary>
        /// 获取楼层信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetTreeInfo(string floorid)
        {
            var floor = (from p in _collection_sys_floor.AsQueryable() where p.isdelete == 0 && p.id== floorid select p).FirstOrDefault();
            var bulid = (from p in _collection_sys_buliding.AsQueryable() where p.isdelete == 0 && p.id == floor.buildid select p).FirstOrDefault();
            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==bulid.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 //项目性质
                }).FirstOrDefault();

            var result = new
            {
                floorid = floor.id,
                floorname = floor.floorname + " " + floor.remark,
                floor.remark,
                bulidid = bulid.id,
                bulidname= bulid.buildname,
                departmentname = floor.remark,
                projectid = proinfo.id,
                projectname= proinfo.project_name,
                province= proinfo.project_province,
                proinfo.provincename,
                city = proinfo.project_city,
                proinfo.cityname,
                property = proinfo.project_property,
                proinfo.protypename,
                nature = proinfo.project_nature,
                proinfo.naturename
            };
            return result;
        }

    }
}