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

namespace WorkOrderApi.Repositories
{
    public class Cus_Customer_BaseRepository : BaseRepository<Cus_Customer_Base, string>, ICus_Customer_BaseRepository
    {
        protected readonly ILogger<BaseRepository<Cus_Customer_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;
        public Cus_Customer_BaseRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Cus_Customer_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>();
        }

        /// <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 key, string province, string city, string stime, string etime,string rolecode,string usercode, int pageindex, int pagesize, out int recordCount)
        {
            var query = from p in _collection.AsQueryable()
                        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 && (p.rolecode == "" || p.rolecode == null || p.rolecode == rolecode) && (p.usercode == "" || p.usercode == null || p.usercode == usercode)   //权限（角色，用户）
                        orderby p.createtime descending
                        select new
                        {
                            p.id,
                            p.name,
                            p.mobilephone,
                            p.telephone,
                            p.manager,
                            p.isblack,
                            p.iscustomer,

                            p.customername,
                            p.companyame,
                            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.rolecode,
                            p.usercode,
                            p.customfields,

                            p.createtime,
                            p.createuser,
                            p.createusername,
                            p.isdelete
                        };

            #region 查询条件
            if (!string.IsNullOrEmpty(key))
                query = query.Where(it => it.name.Contains(key) || it.mobilephone.Contains(key));
            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(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"));

            //// 权限（角色，用户）
            //query = query.Where(it => it.rolecode == "" || it.rolecode == rolecode);
            //query = query.Where(it => it.usercode == "" || it.usercode == usercode);
            #endregion

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

            return list;
        }

        /// <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<Cus_Customer_BaseDto> GetListsExport(string key, string province, string city, string stime, string etime, string rolecode, string usercode)
        {
            var query = from p in _collection.AsQueryable()
                        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 && (p.rolecode == "" || p.rolecode == null || p.rolecode == rolecode) && (p.usercode == "" || p.usercode == null || p.usercode == usercode)   //权限（角色，用户）
                        orderby p.createtime descending
                        select new Cus_Customer_BaseDto
                        {
                            id = p.id,
                            name= p.name,
                            mobilephone=p.mobilephone,
                            telephone= p.telephone,
                            manager=p.manager,
                            isblack= p.isblack,
                            iscustomer=p.iscustomer,

                            customername=p.customername,
                            companyame=p.companyame,
                            province=p.province,
                            provincename = sys_provincesDefa != null && sys_provincesDefa.Count() > 0 ? sys_provincesDefa.First().provincename : null,
                            city=p.city,
                            cityname = sys_cityDefa != null && sys_cityDefa.Count() > 0 ? sys_cityDefa.First().cityname : null,
                            address=p.address,
                            rolecode=p.rolecode,
                            usercode=p.usercode,
                            customfields=p.customfields
                        };

            #region 查询条件
            if (!string.IsNullOrEmpty(key))
                query = query.Where(it => it.name.Contains(key) || it.mobilephone.Contains(key));
            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(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"));

            //// 权限（角色，用户）
            //query = query.Where(it => it.rolecode == "" || it.rolecode == rolecode);
            //query = query.Where(it => it.usercode == "" || it.usercode == usercode);
            #endregion
            
            var list = query;

            return list;
        }

        /// <summary>
        /// 详情 - 获取工单详情 by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string id)
        {
            var query = from p in _collection.AsQueryable()
                        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.id == id
                        select new
                        {
                            p.id,
                            p.name,
                            p.mobilephone,
                            p.telephone,
                            p.manager,
                            p.isblack,
                            p.iscustomer,

                            p.customername,
                            p.companyame,
                            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.customfields,

                            p.createtime,
                            p.createuser,
                            p.createusername,
                            p.isdelete
                        };
            var info = query.FirstOrDefault();
            return info;
        }
    }
}
