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

namespace EquipmentApi.Repositories
{
    public class Wo_Maintain_BaseRepository : BaseRepository<Wo_Maintain_Base, string>, IWo_Maintain_BaseRepository
    {
        protected readonly ILogger<BaseRepository<Wo_Maintain_Base, string>> _logger;
        protected readonly IMongoCollection<Pro_Project_Info> _collection_pro_project_info;
        protected readonly IMongoCollection<Eqp_Equipment_Info> _collection_equipment_info;
        protected readonly IMongoCollection<Sys_DictionaryValue> _collection_sys_dictionaryvalue;
        protected readonly IMongoCollection<Wo_Maintain_Plan> _collection_wo_maintain_plan;
        protected readonly IMongoCollection<Sys_Building> _collection_sys_buliding;
        protected readonly IMongoCollection<Sys_Floor> _collection_sys_floor;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        public Wo_Maintain_BaseRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Wo_Maintain_Base, string>> logger) : base(settings, logger)
        {
            _collection_pro_project_info = _context.GetCollection<Pro_Project_Info>();//获取集合
            _collection_equipment_info = _context.GetCollection<Eqp_Equipment_Info>();//获取集合
            _collection_sys_dictionaryvalue = _context.GetCollection<Sys_DictionaryValue>();
            _collection_wo_maintain_plan = _context.GetCollection<Wo_Maintain_Plan>();
            _collection_sys_buliding = _context.GetCollection<Sys_Building>();
            _collection_sys_floor = _context.GetCollection<Sys_Floor>();
            _collection_sys_user_account = _context.GetCollection<Sys_User_Account>();
            _logger = logger;
        }

        /// <summary>
        /// 获取保养工单列表 Linq 关联查询 分页
        /// </summary>
        /// <param name="proid"></param>
        /// <param name="sysnameid"></param>
        /// <param name="equipmentid"></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<Wo_Maintain_BaseDto> GetListsByPage(string projectid, string matterid,string maintainman, string stime, string etime, int state,string nowusercode, UserAccountInfoModel userinfo, int pageindex, int pagesize, out int recordCount)
        {
            try
            {
                //关联查询
                var query =
                    from maintain in _collection.AsQueryable()
                    //join dic_pro in _collection_sys_dictionaryvalue.AsQueryable() on maintain.systemid equals dic_pro.id into dic_sysDefa
                    join plan in _collection_wo_maintain_plan.AsQueryable() on maintain.planid equals plan.id into planDefa
                    join proje in _collection_pro_project_info.AsQueryable() on maintain.projectid equals proje.id into projeDefa
                    //join dic_equ in _collection_equipment_info.AsQueryable() on maintain.equipmentid equals dic_equ.id into dic_equDefa
                    join users in _collection_sys_user_account.AsQueryable() on maintain.createby equals users.usercode into createuserDefa
                    //join users in _collection_sys_user_account.AsQueryable() on maintain.maintainman equals users.usercode into maintainuserDefa
                    //join users in _collection_sys_user_account.AsQueryable() on maintain.dealby equals users.usercode into dealuserDefa
                    where maintain.isdelete == false
                    orderby maintain.createtime descending
                    select new Wo_Maintain_BaseDto
                    {
                        id = maintain.id,
                        wodate=maintain.wodate,
                        woname=maintain.woname,
                        projectid = maintain.projectid,
                        projectname = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().project_name : null,
                        matterids=maintain.matterids,
                        //systemid = maintain.systemid,
                        //systemname = dic_sysDefa != null && dic_sysDefa.Count() > 0 ? dic_sysDefa.First().name : null,
                        //equipmentid = maintain.equipmentid,
                        //equipname = dic_equDefa != null && dic_equDefa.Count() > 0 ? dic_equDefa.First().equipment_name : null,
                        //sysnameid = dic_sysDefa != null && dic_sysDefa.Count() > 0 ? dic_sysDefa.First().name : null,
                        wocode = maintain.wocode,
                        maintaintype = maintain.maintaintype,
                        equipstate = maintain.equipstate,
                        exceptiondes = maintain.exceptiondes,
                        lastmaintainresult = maintain.lastmaintainresult,
                        lastmaintaintime = maintain.lastmaintaintime,
                        lastmaintaintype = maintain.lastmaintaintype,
                        maintaincontent = maintain.maintaincontent,
                        maintainclim = maintain.maintainclim,
                        maintainuser = maintain.maintainuser,
                        maintainusername = maintain.maintainusername,
                        //maintainman = maintain.maintainman,
                        //maintainbyuser = maintainuserDefa != null && maintainuserDefa.Count() > 0 ? maintainuserDefa.First().username : null,
                        maintainpic = maintain.maintainpic,
                        planid = maintain.planid,
                        planname = planDefa != null && planDefa.Count() > 0 ? planDefa.First().planname : null,
                        maintaintime = maintain.maintaintime,
                        maintainunit = maintain.maintainunit,
                        replacedes = maintain.replacedes,
                        timemaintaintype = maintain.timemaintaintype,
                        wostate = maintain.wostate,
                        dealtime = maintain.dealtime,
                        dealuser = maintain.dealuser,
                        dealusername = maintain.dealusername,
                        //dealby=maintain.dealby,
                        //dealbyuser = dealuserDefa != null && dealuserDefa.Count() > 0 ? dealuserDefa.First().username : null,
                        starttime = maintain.starttime,
                        endtime = maintain.endtime,
                        createtime = maintain.createtime,
                        createby = maintain.createby,
                        createbyuser = createuserDefa != null && createuserDefa.Count() > 0 ? createuserDefa.Where(c => c.delete_flag == false).First().username : null,
                        isdelete = maintain.isdelete,
                        extensionlist = maintain.extensionlist
                    };
                #region 查询条件
                if (!string.IsNullOrWhiteSpace(projectid))
                    query = query.Where(it => it.projectid == projectid);
                if (!string.IsNullOrEmpty(matterid))
                    query = query.Where(it => it.matterids.Contains(matterid));
                //if (!string.IsNullOrEmpty(equipname))
                //    query = query.Where(it => it.equipmentid == equipname);
                //if (!string.IsNullOrEmpty(maintainman))
                //    query = query.Where(it => it.maintainuser.Contains(maintainman));
                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 (state >= 0)
                {
                    switch (state)
                    {
                        case 10:
                            //未指派
                            query = query.Where(it => it.wostate == (int)EnumWoMaintainState.create);
                            break;
                        case 11:
                            //未处理
                            query = query.Where(it => it.wostate < (int)EnumWoMaintainState.deal & it.wostate > (int)EnumWoMaintainState.create);
                            break;
                        case 12:
                            //已处理
                            query = query.Where(it => it.wostate == (int)EnumWoMaintainState.deal);
                            break;
                        case 13:
                            //已挂起 已评价和已取消的均为完结工单
                            query = query.Where(it => it.wostate == (int)EnumWoMaintainState.hangup);
                            break;
                        default:
                            query = query.Where(it => it.wostate.Equals(state));
                            break;
                    }
                }
                
                #region
                if (userinfo.type == 2)//查看自己创建的工单
                {
                    query = query.Where(it => it.createby == userinfo.usercode);
                }
                else
                {
                    if (userinfo.isallproject == 1)
                    {
                        if (!string.IsNullOrEmpty(maintainman))
                            query = query.Where(it => (it.maintainuser.Contains(maintainman) || it.dealuser.Contains(maintainman)));
                    }
                    else if (userinfo.isallproject == 0)
                    {
                        query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
                        
                        if (userinfo.role_code == "YWYG")
                        {
                            query = query.Where(it => (it.maintainuser.Count() == 0 || it.maintainuser.Contains(nowusercode) || it.dealuser.Contains(nowusercode)));
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(maintainman))
                                query = query.Where(it => (it.maintainuser.Contains(maintainman) || it.dealuser.Contains(maintainman)));
                        }
                    }
                }
                //if (string.IsNullOrWhiteSpace(rolecode))
                //{
                //    //运维员工只能看到自己的工单
                //    //且只能看到当天及当天之前的工单
                //    if (rolecode.Equals("YWYG"))
                //    {
                //        query = query.Where(it => it.starttime >= DateTime.Now);
                //        query = query.Where(it => it.maintainuser.Contains(maintainman));
                //    }
                //}
                #endregion
                #endregion
                var list = query.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
                var listnew = new List<Wo_Maintain_BaseDto>();
                #region 筛选设备后重新赋值
                //if (!string.IsNullOrEmpty(equipname))
                //{
                //    foreach (var item in list)
                //    {
                //        if (item.equipmentid != null)
                //        {
                //            var eqid = string.Join(",", item.equipmentid);
                //            if (!string.IsNullOrWhiteSpace(eqid))
                //            {
                //                if (eqid.Contains(equipname))
                //                {
                //                    listnew.Add(item);
                //                }
                //            }
                //        }
                //    }
                //}
                //else
                //{
                    listnew = list;
                //}
                #endregion
                recordCount = query.Count();// listnew.Count();
                var listNN = listnew;
                return listNN;
                //recordCount = query.Count();
                //var list = query.Skip((pageindex - 1) * pagesize).Take(pagesize);
                //return list;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
        public IEnumerable<Wo_Maintain_BaseDto> GetLists()
        {
            try
            {
                //关联查询
                var query =
                    from maintain in _collection.AsQueryable()
                    //join dic_pro in _collection_sys_dictionaryvalue.AsQueryable() on maintain.systemid equals dic_pro.id into dic_sysDefa
                    join plan in _collection_wo_maintain_plan.AsQueryable() on maintain.planid equals plan.id into planDefa
                    join proje in _collection_pro_project_info.AsQueryable() on maintain.projectid equals proje.id into projeDefa
                    //join dic_equ in _collection_equipment_info.AsQueryable() on maintain.equipmentid equals dic_equ.id into dic_equDefa
                    where maintain.isdelete == false
                    orderby maintain.createtime descending
                    select new Wo_Maintain_BaseDto
                    {
                        id = maintain.id,
                        wodate=maintain.wodate,
                        woname=maintain.woname,
                        projectid = maintain.projectid,
                        projectname = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().project_name : null,
                        matterids = maintain.matterids,
                        //systemid = maintain.systemid,
                        //systemname = dic_sysDefa != null && dic_sysDefa.Count() > 0 ? dic_sysDefa.First().name : null,
                        //equipmentid = maintain.equipmentid,
                        //equipname = dic_equDefa != null && dic_equDefa.Count() > 0 ? dic_equDefa.First().equipment_name : null,
                        //sysnameid = dic_sysDefa != null && dic_sysDefa.Count() > 0 ? dic_sysDefa.First().name : null,
                        wocode = maintain.wocode,
                        maintaintype = maintain.maintaintype,
                        equipstate = maintain.equipstate,
                        exceptiondes = maintain.exceptiondes,
                        lastmaintainresult = maintain.lastmaintainresult,
                        lastmaintaintime = maintain.lastmaintaintime,
                        lastmaintaintype = maintain.lastmaintaintype,
                        maintaincontent = maintain.maintaincontent,
                        maintainclim = maintain.maintainclim,
                        //maintainman = maintain.maintainman,
                        maintainuser = maintain.maintainuser,
                        maintainusername = maintain.maintainusername,
                        maintainpic = maintain.maintainpic,
                        planid = maintain.planid,
                        planname = planDefa != null && planDefa.Count() > 0 ? planDefa.First().planname : null,
                        maintaintime = maintain.maintaintime,
                        maintainunit = maintain.maintainunit,
                        replacedes = maintain.replacedes,
                        timemaintaintype = maintain.timemaintaintype,
                        wostate = maintain.wostate,
                        dealtime = maintain.dealtime,
                        //dealby = maintain.dealby,
                        dealuser = maintain.dealuser,
                        dealusername = maintain.dealusername,
                        starttime = maintain.starttime,
                        endtime = maintain.endtime,
                        createtime = maintain.createtime,
                        createby = maintain.createby,
                        isdelete = maintain.isdelete
                    };

                var list = query;
                return list;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }

        /// <summary>
        /// 获取保养计划详情 by id Linq 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Wo_Maintain_BaseDto GetDetails(string id)
        {
            try
            {
                var queryequipment = from equipment in _collection_equipment_info.AsQueryable() select equipment;
                var querybulid = from bulidin in _collection_sys_buliding.AsQueryable() select bulidin;
                var queryfloor = from floor in _collection_sys_floor.AsQueryable() select floor;
                //关联查询
                var query =
                    from maintain in _collection.AsQueryable()
                    //join dic_pro in _collection_sys_dictionaryvalue.AsQueryable() on maintain.systemid equals dic_pro.id into dic_sysDefa
                    join plan in _collection_wo_maintain_plan.AsQueryable() on maintain.planid equals plan.id into planDefa
                    join proje in _collection_pro_project_info.AsQueryable() on maintain.projectid equals proje.id into projeDefa
                    //join dic_equ in _collection_equipment_info.AsQueryable() on maintain.equipname equals dic_equ.id into dic_equDefa
                    join users in _collection_sys_user_account.AsQueryable() on maintain.createby equals users.usercode into createuserDefa
                    //join users in _collection_sys_user_account.AsQueryable() on maintain.maintainman equals users.usercode into maintainuserDefa
                    //join users in _collection_sys_user_account.AsQueryable() on maintain.dealby equals users.usercode into dealuserDefa
                    where maintain.isdelete == false && maintain.id == id
                    orderby maintain.createtime descending
                    select new Wo_Maintain_BaseDto
                    {
                        id = maintain.id,
                        wodate=maintain.wodate,
                        woname=maintain.woname,
                        projectid = maintain.projectid,
                        projectname = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().project_name : null,
                        matterids = maintain.matterids,
                        //systemid = maintain.systemid,
                        //systemname = dic_sysDefa != null && dic_sysDefa.Count() > 0 ? dic_sysDefa.First().name : null,
                        //equipmentid = maintain.equipmentid,
                        //equipname = dic_equDefa != null && dic_equDefa.Count() > 0 ? dic_equDefa.First().equipment_name : null,
                        //sysnameid = dic_equDefa != null && dic_equDefa.Count() > 0 ? dic_equDefa.First().systemid : null,
                        wocode = maintain.wocode,
                        maintaintype = maintain.maintaintype,
                        equipstate = maintain.equipstate,
                        exceptiondes = maintain.exceptiondes,
                        lastmaintainresult = maintain.lastmaintainresult,
                        lastmaintaintime = maintain.lastmaintaintime,
                        lastmaintaintype = maintain.lastmaintaintype,
                        maintaincontent = maintain.maintaincontent,
                        maintainclim = maintain.maintainclim,
                        maintainuser = maintain.maintainuser,
                        maintainusername =maintain.maintainusername,
                        //maintainman = maintain.maintainman,
                        //maintainbyuser = maintainuserDefa != null && maintainuserDefa.Count() > 0 ? maintainuserDefa.First().username : null,
                        maintainpic = maintain.maintainpic,
                        planid = maintain.planid,
                        planname = planDefa != null && planDefa.Count() > 0 ? planDefa.First().planname : null,
                        maintaintime = maintain.maintaintime,
                        maintainunit = maintain.maintainunit,
                        replacedes = maintain.replacedes,
                        timemaintaintype = maintain.timemaintaintype,
                        wostate = maintain.wostate,
                        dealtime = maintain.dealtime,
                        dealuser = maintain.dealuser,
                        dealusername = maintain.dealusername,
                        //dealby = maintain.dealby,
                        //dealbyuser = dealuserDefa != null && dealuserDefa.Count() > 0 ? dealuserDefa.First().username : null,
                        starttime = maintain.starttime,
                        endtime = maintain.endtime,
                        createtime = maintain.createtime,
                        createby = maintain.createby,
                        createbyuser = createuserDefa != null && createuserDefa.Count() > 0 ? createuserDefa.Where(c => c.delete_flag == false).First().username : null,
                        isdelete = maintain.isdelete,
                        extensionlist=maintain.extensionlist
                    };
                var info = query.FirstOrDefault();
                if (info != null)
                {
                    var floorname = string.Empty;
                    var bulidname = string.Empty;
                    //var modelequipment = queryequipment.FirstOrDefault(x => x.id.Equals(info.equipmentid));
                    //if (modelequipment != null)
                    //{
                    //    var modelfloor = queryfloor.FirstOrDefault(x => x.id.Equals(modelequipment.floorid));
                    //    if (modelfloor != null)
                    //    {
                    //        floorname = modelfloor.floorname ;
                    //        var modelbulid = querybulid.FirstOrDefault(x => x.id.Equals(modelfloor.buildid));
                    //        if (modelbulid != null)
                    //        {
                    //            bulidname =modelbulid.buildname;
                    //        }
                    //    }
                    //}
                    double timeoutlong = 0;
                    if (info.wostate == (int)EnumWoMaintainState.deal || info.wostate == (int)EnumWoMaintainState.hangup)
                    {
                        if (info.dealtime > info.endtime)
                            timeoutlong = (info.dealtime - info.endtime).TotalSeconds;
                    }
                    else
                    {
                        if (DateTime.Now > info.endtime)
                            timeoutlong = (DateTime.Now - info.endtime).TotalSeconds;
                    }
                    var newmodel = info;
                    newmodel.timeoutlong = (int)Math.Ceiling(timeoutlong);
                    newmodel.floorname = bulidname + floorname; //楼号+楼层（地点）
                    
                    return newmodel;
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }

        public IEnumerable<Wo_Maintain_BaseChartDto> GetChart(string projectid)
        {
            var query = from eqrun in _collection.AsQueryable()
                        where eqrun.projectid.Equals(projectid)
                        group eqrun by eqrun.wodate into eqrunc
                        select new Wo_Maintain_BaseChartDto
                        {
                            wodate = eqrunc.Key,
                            counts = eqrunc.Count(),
                        };
            var list = query.ToList();

            return list;
        }
    }
}
