using ConfigurationApi.IRepositories;
using MadRunFabric.Model;
using ConfigurationApi.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;

namespace ConfigurationApi.Repositories
{
    public class Sys_FloorRepository : BaseRepository<Sys_Floor, string>, ISys_FloorRepository
    {
        protected readonly ILogger<BaseRepository<Sys_Floor, string>> _logger;
        protected readonly IMongoCollection<Sys_Building> _collection_sys_building;
        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;
        public Sys_FloorRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Sys_Floor, string>> logger) : base(settings, logger)
        {
            _collection_sys_building = _context.GetCollection<Sys_Building>();//获取集合
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();//获取集合
            _collection_sys_provinces = _context.GetCollection<Sys_Provinces>();
            _collection_sys_city = _context.GetCollection<Sys_City>();
            _logger = logger;
        }       

        #region 楼层
        /// <summary>
        /// 获取楼层列表 分页 - Linq 关联查询
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="projectid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<SysFloorListDto> GetListsByPage(string keyword, string buildid, int pageIndex, int pageSize, out int recordCount)
        {

            var query_pro = from p in _collection_pro_project_info.AsQueryable() where p.isdelete == 0 select p;
            //关联查询
            var query =
                from fl in _collection.AsQueryable()
                join build in _collection_sys_building.AsQueryable() on fl.buildid equals build.id into buildDefa
                where fl.isdelete == 0
                orderby fl.sortnum ascending, fl.createtime descending
                select new SysFloorListDto
                {
                    id = fl.id,
                    floorname = fl.floorname,
                    buildid = fl.buildid,
                    buildname = buildDefa != null && buildDefa.Count()>0 ? buildDefa.First().buildname : null,
                    projectid = buildDefa != null && buildDefa.Count() > 0 ? buildDefa.First().projectid : null,
                    projectname = "",
                    sortnum = fl.sortnum,
                    remark = fl.remark,
                    isdelete = fl.isdelete,
                    createtime = fl.createtime,
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.floorname.Contains(keyword));
            if (!string.IsNullOrEmpty(buildid))
                query = query.Where(it => it.buildid == buildid);
            #endregion
            recordCount = query.Count();
            var lists = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            var list = new List<SysFloorListDto>();
            foreach (var item in lists)
            {
                var model_pro = query_pro.Where(x => x.id == item.projectid).FirstOrDefault();
                item.projectname = model_pro != null ? model_pro.project_name : "";
                list.Add(item);
            }
            return list;
        }

        /// <summary>
        /// 获取楼层详情 - Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysFloorDetailsDto GetDetails(string id)
        {
            //关联查询
            var query =
                from fl in _collection.AsQueryable()
                join build in _collection_sys_building.AsQueryable() on fl.buildid equals build.id into buildDefa
                where fl.isdelete == 0 && fl.id == id
                orderby fl.createtime
                select new SysFloorDetailsDto
                {
                    id = fl.id,
                    floorname = fl.floorname,
                    buildid = fl.buildid,
                    buildname = buildDefa != null && buildDefa.Count() > 0 ? buildDefa.First().buildname : null,
                    projectid = buildDefa != null && buildDefa.Count() > 0 ? buildDefa.First().projectid : null,
                    sortnum = fl.sortnum,
                    remark = fl.remark,
                    isdelete = fl.isdelete,
                    createtime = fl.createtime,
                };
            var model = query.FirstOrDefault();
            if (model != null)
            {
                return model;
            }
            return null;
        }

        #endregion


        /// <summary>
        /// 获取五级联动
        /// </summary>
        /// <returns></returns>
        public object GetTree()
        {
            var bulidlist = (from equ in _collection_sys_building.AsQueryable() where equ.isdelete == 0 select equ).ToList();
            var floorlist = (from equ in _collection.AsQueryable() where equ.isdelete == 0 select equ).ToList();
            var projectlist = (from proje in _collection_pro_project_info.AsQueryable() where proje.isdelete==0 select proje).ToList();
            var provincelist = (from province in _collection_sys_provinces.AsQueryable() select province).ToList();
            var citylist = (from city in _collection_sys_city.AsQueryable() select city).ToList();

            var result = provincelist.Select(p => new
            {
                id = p.id,
                code = p.provincecode,
                name = p.provincename,
                parentcode = -1,
                entityJson = citylist.Where(q => q.provincecode == p.provincecode).Select(q => new
                {
                    id = q.id,
                    code = q.citycode,
                    name = q.cityname,
                    parentcode = q.provincecode,
                    entityJson = projectlist.Where(j => j.project_city == q.citycode ).Select(j => new
                    {
                        id = j.id,
                        code = j.id,
                        name = j.project_name,
                        parentcode = q.citycode,
                        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,
                                parentcode = b.id
                            })
                        })
                    })
                })
            });
            return result;
        }

    }
}
