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

namespace CallCenterApi.Repositories
{
    public class Bus_Order_BaseRepository : BaseRepository<Bus_Order_Base, string>, IBus_Order_BaseRepository
    {
        protected readonly ILogger<BaseRepository<Bus_Order_Base, 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<Sys_Department> _collection_sys_department;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;

        public Bus_Order_BaseRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Bus_Order_Base, string>> logger) : base(settings, logger)
        {
            _logger = logger;
            _collection_sys_department = _context.GetCollection<Sys_Department>();
            _collection_sys_provinces = _context.GetCollection<Sys_Provinces>();
            _collection_sys_city = _context.GetCollection<Sys_City>();
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();
            _collection_sys_user_account= _context.GetCollection<Sys_User_Account>();
        }

        /// <summary>
        /// Linq 关联查询 分页
        /// </summary>
        /// <param name="ordercode"></param>
        /// <param name="key"></param>
        /// <param name="phone"></param>
        /// <param name="province"></param>
        /// <param name="city"></param>
        /// <param name="sourceid"></param>
        /// <param name="typeid"></param>
        /// <param name="deptid"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="state"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<object> GetListsByPage(string ordercode, string key, string phone, string province, string city, string sourceid,
            string typeid, string deptid, string stime, string etime, int state, int pageindex, int pagesize, out int recordCount)
        {
            var query = from p in _collection.AsQueryable()
                        join dic_source in _collection_sys_dictionaryvalue.AsQueryable() on p.sourceid equals dic_source.id into dic_sourceDefa
                        join dic_type in _collection_sys_dictionaryvalue.AsQueryable() on p.typeid equals dic_type.id into dic_typeDefa
                        join dic_dept in _collection_sys_department.AsQueryable() on p.deptid equals dic_dept.id into dic_deptDefa
                        join dic_dealdept in _collection_sys_department.AsQueryable() on p.dealdeptid equals dic_dealdept.id into dic_dealdeptDefa
                        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
                        where p.isdelete == 0
                        select new
                        {
                            p.id,
                            p.ordercode,
                            p.unique_id,
                            p.callrecordid,
                            p.leaverecordid,
                            p.name,
                            p.phone,
                            p.sex,
                            p.province,
                            provincename = sys_provincesDefa != null && sys_provincesDefa.Count() > 0 ? sys_provincesDefa.First().provincename : null,
                            p.city,
                            cityname = sys_cityDefa != null && sys_cityDefa.Count() > 0 ? sys_cityDefa.First().cityname : null,
                            p.address,
                            p.sourceid,
                            sourcename = dic_sourceDefa != null && dic_sourceDefa.Count() > 0 ? dic_sourceDefa.First().name : null,
                            p.typeid,
                            typename = dic_typeDefa != null && dic_typeDefa.Count() > 0 ? dic_typeDefa.First().name : null,
                            p.deptid,
                            deptname = dic_deptDefa != null && dic_deptDefa.Count() > 0 ? dic_deptDefa.First().departmenname : null,
                            p.title,
                            p.content,
                            p.files,
                            p.state,
                            p.dealdeptid,
                            dealdeptname = dic_dealdeptDefa != null && dic_dealdeptDefa.Count() > 0 ? dic_dealdeptDefa.First().departmenname : null,
                            p.dealtime,
                            p.dealuser,
                            p.dealusername,
                            p.result,
                            p.resultfiles,
                            p.createtime,
                            p.createuser,
                            p.createusername
                        };

            #region 查询条件
            if (!string.IsNullOrEmpty(ordercode))
                query = query.Where(it => it.ordercode.Contains(ordercode));
            if (!string.IsNullOrEmpty(key))
                query = query.Where(it => it.title.Contains(key) || it.content.Contains(key));
            if (!string.IsNullOrEmpty(phone))
                query = query.Where(it => it.phone.Contains(phone));
            if (!string.IsNullOrEmpty(province))
                query = query.Where(it => it.province == province);
            if (!string.IsNullOrEmpty(city))
                query = query.Where(it => it.city == city);
            if (!string.IsNullOrEmpty(sourceid))
                query = query.Where(it => it.sourceid == sourceid);
            if (!string.IsNullOrEmpty(typeid))
                query = query.Where(it => it.typeid == typeid);
            if (!string.IsNullOrEmpty(deptid))
                query = query.Where(it => it.deptid == deptid);

            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"));

            #endregion

            recordCount = query.Count();
            var list = query.Skip((pageindex - 1) * pagesize).Take(pagesize).OrderByDescending(p => p.createtime).ToList();

            return list;
        }

        /// <summary>
        /// 详情 - 获取设备详情 by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string ordercode)
        {
            var query = from p in _collection.AsQueryable()
                        join dic_source in _collection_sys_dictionaryvalue.AsQueryable() on p.sourceid equals dic_source.id into dic_sourceDefa
                        join dic_type in _collection_sys_dictionaryvalue.AsQueryable() on p.typeid equals dic_type.id into dic_typeDefa
                        join dic_dept in _collection_sys_department.AsQueryable() on p.deptid equals dic_dept.id into dic_deptDefa
                        join dic_dealdept in _collection_sys_department.AsQueryable() on p.dealdeptid equals dic_dealdept.id into dic_dealdeptDefa
                        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
                        where p.ordercode == ordercode
                        select new
                        {
                            p.id,
                            p.ordercode,
                            p.unique_id,
                            p.callrecordid,
                            p.leaverecordid,
                            p.name,
                            p.phone,
                            p.sex,
                            p.province,
                            provincename = sys_provincesDefa != null && sys_provincesDefa.Count() > 0 ? sys_provincesDefa.First().provincename : null,
                            p.city,
                            cityname = sys_cityDefa != null && sys_cityDefa.Count() > 0 ? sys_cityDefa.First().cityname : null,
                            p.address,
                            p.sourceid,
                            sourcename = dic_sourceDefa != null && dic_sourceDefa.Count() > 0 ? dic_sourceDefa.First().name : null,
                            p.typeid,
                            typename = dic_typeDefa != null && dic_typeDefa.Count() > 0 ? dic_typeDefa.First().name : null,
                            p.deptid,
                            deptname = dic_deptDefa != null && dic_deptDefa.Count() > 0 ? dic_deptDefa.First().departmenname : null,
                            p.title,
                            p.content,
                            p.files,
                            p.state,
                            p.dealdeptid,
                            dealdeptname = dic_dealdeptDefa != null && dic_dealdeptDefa.Count() > 0 ? dic_dealdeptDefa.First().departmenname : null,
                            p.dealtime,
                            p.dealuser,
                            p.dealusername,
                            p.result,
                            p.resultfiles,
                            p.createtime,
                            p.createuser,
                            p.createusername
                        };
            var info = query.FirstOrDefault();
            return info;
        }

        /// <summary>
        /// 获取日周月年工单类型统计
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="optuser"></param>
        /// <returns></returns>
        public object GetWorkOrderTypeCountReport(string stime, string etime, string optuser)
        {
            var query = from p in _collection.AsQueryable() where p.isdelete == 0 select p;
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime));

            var typelist = from p in _collection_sys_dictionaryvalue.AsQueryable() where p.dictionarycode == "GDLX" && p.statetype == true orderby p.sort select p;

            var result = typelist.ToList().Select(p =>
            {
                var count = query.Where(it => it.typeid == p.id).Count();
                return new
                {
                    p.id,
                    p.name,
                    count
                };
            });

            return result;
        }

        /// <summary>
        /// 获取日周月年工单来源统计
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="optuser"></param>
        /// <returns></returns>
        public object GetWorkOrderSourceCountReport(string stime, string etime, string optuser)
        {
            var query = from p in _collection.AsQueryable() where p.isdelete == 0 select p;
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime));

            var typelist = from p in _collection_sys_dictionaryvalue.AsQueryable() where p.dictionarycode == "GDLY" && p.statetype == true orderby p.sort select p;

            var result = typelist.ToList().Select(p =>
            {
                var count = query.Where(it => it.sourceid == p.id).Count();
                return new
                {
                    p.id,
                    p.name,
                    count
                };
            });

            return result;
        }

        /// <summary>
        /// 获取日周月年工单24小时统计
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="optuser"></param>
        /// <returns></returns>
        public object GetWorkOrder24CountReport(string stime, string etime, string optuser)
        {
            int[] hours = Enumerable.Range(0, 24).ToArray<int>();
            int[] counts = new int[24];

            var query = from p in _collection.AsQueryable() where p.isdelete == 0 select p;
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime));

            var list = query.ToList();
            for (int i = 0; i < hours.Length; i++)
            {
                counts[i] = list.Where(it => it.createtime.Hour == i).Count();
            }

            var result = new
            {
                hours,
                counts
            };
            return result;
        }

        /// <summary>
        /// 获取用户工单排行榜
        /// </summary>
        /// <param name="top"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        public object GetUserCountRank(int top, string stime, string etime)
        {
            var query = from p in _collection.AsQueryable()
                        join u in _collection_sys_user_account.AsQueryable() on p.createuser equals u.usercode into userinfo
                        where p.isdelete == 0
                        select new
                        {
                            p.ordercode,
                            usercode = p.createuser,
                            username = userinfo.Count() > 0 ? userinfo.First().username : "",
                            p.createtime
                        };
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.createtime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.createtime <= Convert.ToDateTime(etime));

            var ranklist = query.GroupBy(p => new { p.usercode, p.username }).Select(p => new
            {
                p.Key.usercode,
                p.Key.username,
                count =p.Count()
            }).OrderByDescending(p => p.count).ToList().Select((p, i) => new
            {
                p.usercode,
                p.username,
                p.count,
                rank = i + 1
            });

            return top == 0 ? ranklist : ranklist.Take(top);
        }

    }
}
