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

namespace EquipmentApi.Repositories
{
    public class RunningRepairRepository : BaseRepository<Pro_Project_Info, string>, IRunningRepairRepository
    {
        protected readonly ILogger<BaseRepository<Pro_Project_Info, string>> _logger;
        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<Eqp_Equipment_Info> _collection_eqp_equipment_info;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        protected readonly IMongoCollection<Wo_Repair_Base> _collection_wo_repair_base;
        protected readonly IMongoCollection<Wo_Maintain_Base> _collection_wo_maintain_base;
        protected readonly IMongoCollection<Wo_EquipmentRunning> _collection_equipmentrunning;
        protected readonly IMongoCollection<Sys_Role_Info> _collection_role_info;
        protected readonly IMongoCollection<Wo_Matters> _collection_matters;
        protected readonly IMongoCollection<Wo_TimeOut> _collection_wo_timeout;
        public RunningRepairRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<Pro_Project_Info, string>> logger) : base(settings, logger)
        {
            _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_eqp_equipment_info = _context.GetCollection<Eqp_Equipment_Info>();
            _collection_sys_user_account = _context.GetCollection<Sys_User_Account>();
            _collection_wo_repair_base= _context.GetCollection<Wo_Repair_Base>();
            _collection_wo_maintain_base = _context.GetCollection<Wo_Maintain_Base>();
            _collection_equipmentrunning = _context.GetCollection<Wo_EquipmentRunning>();
            _collection_role_info = _context.GetCollection<Sys_Role_Info>();
            _collection_matters = _context.GetCollection<Wo_Matters>();
            _collection_wo_timeout = _context.GetCollection<Wo_TimeOut>();
            _logger = logger;
        }

        #region Pc项目统计
        /// <summary>
        /// 项目统计报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetProjectListAndStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from pro in _collection.AsQueryable()
                join dic in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_property equals dic.id into dicDefa
                join city in _collection_sys_city.AsQueryable() on pro.project_city equals city.citycode into cityDefa
                join provinces in _collection_sys_provinces.AsQueryable() on pro.project_province equals provinces.provincecode into provincesDefa
                where pro.isdelete == 0
                orderby pro.createtime descending
                select new
                {
                    pro.id,
                    pro.createtime,
                    pro.project_name,
                    project_propertyname = dicDefa != null && dicDefa.Count() > 0 ? dicDefa.First().name : "",
                    cityname = cityDefa != null && cityDefa.Count() > 0 ? cityDefa.First().cityname : "",
                    provincesname = provincesDefa != null && provincesDefa.Count() > 0 ? provincesDefa.First().provincename : "",
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.project_name.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.id.Equals(projectid));
            if (!string.IsNullOrEmpty(start))
                query = query.Where(it => it.createtime>=DateTime.Parse(start+" 00:00:00"));
            if (!string.IsNullOrEmpty(end))
                query = query.Where(it => it.createtime <= DateTime.Parse(end + " 23:59:59"));
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.id));

            #endregion
            recordCount = query.Count();
            var queryList = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var list = queryList;
            var obj = new
            {
                list,
                procount = recordCount
            };
            return obj;
        }

        /// <summary>
        /// 项目工单来源统计报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetProjectRepairOrderListAndStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {

            //关联查询
            var query =
                from pro in _collection.AsQueryable()
                join dic in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_property equals dic.id into dicDefa
                join city in _collection_sys_city.AsQueryable() on pro.project_city equals city.citycode into cityDefa
                join provinces in _collection_sys_provinces.AsQueryable() on pro.project_province equals provinces.provincecode into provincesDefa
                where pro.isdelete == 0
                orderby pro.createtime descending
                select new
                {
                    pro.id,
                    pro.createtime,
                    pro.project_name,
                    project_propertyname = dicDefa != null && dicDefa.Count() > 0 ? dicDefa.First().name : "",
                    cityname = cityDefa != null && cityDefa.Count() > 0 ? cityDefa.First().cityname : "",
                    provincename = provincesDefa != null && provincesDefa.Count() > 0 ? provincesDefa.First().provincename : "",
                };
            #region 查询条件
            //var queryList = query.ToList();
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.project_name.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.id.Equals(projectid));
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.id));

            var queryList = query.ToList();

            var pros = query.ToList().Select(p => p.id);
            var queryrepair = from repair in _collection_wo_repair_base.AsQueryable() where repair.isdelete==0 && pros.Contains(repair.projectid) && repair.wostate!=(int)EnumWorkOrderState.cancle select repair;

            if (!string.IsNullOrEmpty(start))
                queryrepair = queryrepair.Where(it => it.createtime >= DateTime.Parse(start + " 00:00:00"));
            if (!string.IsNullOrEmpty(end))
                queryrepair = queryrepair.Where(it => it.createtime <= DateTime.Parse(end + " 23:59:59"));

            var repairlist = queryrepair.ToList();

            //电话来源数
            int channelpcnum = repairlist.Where(x => x.channel == (int)EnumWorkOrderChannel.pc).Count();
            //微信来源数
            int channelwechatnum = repairlist.Where(x => x.channel == (int)EnumWorkOrderChannel.wechat).Count();
            //APP来源数
            int channelappnum = repairlist.Where(x => x.channel == (int)EnumWorkOrderChannel.ios || x.channel == (int)EnumWorkOrderChannel.android).Count();

            #endregion

            recordCount = query.Count();
            var lists = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var list = lists.Select(p =>
            {
                var queryrepairlist = repairlist.Where(x => x.projectid == p.id);
                //电话来源数
                int itemchannelpcnum = queryrepairlist.Where(x => x.channel == (int)EnumWorkOrderChannel.pc).Count();
                //微信来源数
                int itemchannelwechatnum = queryrepairlist.Where(x => x.channel == (int)EnumWorkOrderChannel.wechat).Count();
                //APP来源数
                int itemchannelappnum = queryrepairlist.Where(x => x.channel == (int)EnumWorkOrderChannel.ios || x.channel == (int)EnumWorkOrderChannel.android).Count();

                return new
                {
                    p.id,
                    p.provincename,
                    p.cityname,
                    projectname = p.project_name,
                    channelpcnum = itemchannelpcnum,
                    channelwechatnum = itemchannelwechatnum,
                    channelappnum = itemchannelappnum
                };
            });

            var obj = new
            {
                list,
                channelpcnum,
                channelwechatnum,
                channelappnum
            };
            return obj;
        }

        /// <summary>
        /// 项目报修统计报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetProjectRepairListAndStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var diclist = from dic in _collection_sys_dictionaryvalue.AsQueryable() select dic;
            //关联查询
            var query =
                from pro in _collection.AsQueryable()
                join dic in _collection_sys_dictionaryvalue.AsQueryable() on pro.project_property equals dic.id into dicDefa
                join city in _collection_sys_city.AsQueryable() on pro.project_city equals city.citycode into cityDefa
                join provinces in _collection_sys_provinces.AsQueryable() on pro.project_province equals provinces.provincecode into provincesDefa
                where pro.isdelete == 0
                orderby pro.createtime descending
                select new
                {
                    pro.id,
                    pro.project_name,
                    project_propertyname = dicDefa != null && dicDefa.Count() > 0 ? dicDefa.First().name : "",
                    cityname = cityDefa != null && cityDefa.Count() > 0 ? cityDefa.First().cityname : "",
                    provincename = provincesDefa != null && provincesDefa.Count() > 0 ? provincesDefa.First().provincename : "",
                };

            //var queryList = query.ToList();
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.project_name.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
                query = query.Where(it => it.id.Equals(projectid));
            if (userinfo.isallproject == 0)
                query = query.Where(it => userinfo.projectlist.Contains(it.id));

            var pros = query.ToList().Select(p => p.id);
            var queryrepair = from repair in _collection_wo_repair_base.AsQueryable()
                               where pros.Contains(repair.projectid) && repair.wostate != (int)EnumWorkOrderState.cancle && repair.wostate >= (int)EnumWorkOrderState.deal
                               select repair;

            if (!string.IsNullOrEmpty(start))
                queryrepair = queryrepair.Where(it => it.createtime >= DateTime.Parse(start + " 00:00:00"));
            if (!string.IsNullOrEmpty(end))
                queryrepair = queryrepair.Where(it => it.createtime <= DateTime.Parse(end + " 23:59:59"));

            var repairlist = queryrepair.ToList();

            //var modeldic = diclist.FirstOrDefault(x => x.dictionarycode.Equals("XTMC") && x.name.Equals("日常类"));
            //var dailylist = new List<Wo_Repair_Base>();
            //var equlist = new List<Wo_Repair_Base>();
            //if (modeldic != null)
            //{
            //    //日常报修列表
            //    dailylist = repairlist.Where(x => x.systemid == modeldic.id).ToList();
            //    //设备报修列表
            //    equlist = repairlist.Where(x => x.systemid != modeldic.id).ToList();
            //}

            //日常报修列表
            var dailylist = repairlist.Where(x => x.equipmentid == null).ToList();
            //设备报修列表
            var equlist = repairlist.Where(x => x.equipmentid != null).ToList();

            //日常待维修数量
            int nodailycount = dailylist.Where(x => x.wostate == (int)EnumWorkOrderState.hangup).Count();
            //日常已维修数量
            int dailyedcount = dailylist.Where(x => x.wostate == (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.evaluate).Count();
            //设备待维修数量
            int noequcount = equlist.Where(x => x.wostate == (int)EnumWorkOrderState.hangup).Count();
            //设备已维修数量
            int equedcount = equlist.Where(x => x.wostate == (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.evaluate).Count();

            

            recordCount = query.Count();
            var lists = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var list = lists.Select(p =>
             {
                 var dailynumlist = dailylist.Where(x => x.projectid == p.id);
                 var equlistnumlist = equlist.Where(x => x.projectid == p.id);
                 //日常待维修数量
                 int nodailynum = dailynumlist.Where(x => x.wostate == (int)EnumWorkOrderState.hangup).Count();

                 //日常已维修数量
                 int dailyednum = dailynumlist.Where(x => x.wostate == (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.evaluate).Count();

                 //设备待维修数量
                 int noequnum = equlistnumlist.Where(x => x.wostate == (int)EnumWorkOrderState.hangup).Count();

                 //设备已维修数量
                 int equednum = equlistnumlist.Where(x => x.wostate == (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.evaluate).Count();

                 return new
                 {
                     p.id,
                     projectname = p.project_name,
                     p.provincename,
                     p.cityname,
                     nodailynum,
                     dailyednum,
                     noequnum,
                     equednum
                 };
             });

            var obj = new
            {
                list,
                nodailycount,
                dailyedcount,
                noequcount,
                equedcount
            };
            return obj;
        }

        /// <summary>
        /// 人员满意度统计 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetUserEvaluateStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var prolist = from pro in _collection.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 //项目属性
                          };

            var repairlist = from repair in _collection_wo_repair_base.AsQueryable()
                             where repair.isdelete == 0 && (repair.wostate == (int)EnumWorkOrderState.evaluate || repair.wostate == (int)EnumWorkOrderState.deal)
                             select repair;

            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG");

            if (!string.IsNullOrEmpty(keyword))
                wxlist = wxlist.Where(it => it.usercode.Contains(keyword) || it.username.Contains(keyword));

            if (!string.IsNullOrEmpty(projectid))
            {
                prolist = prolist.Where(it => it.id.Equals(projectid));
                repairlist = repairlist.Where(it => it.projectid.Equals(projectid));
                wxlist = wxlist.Where(it => it.projectid.Equals(projectid));
            }
            if (!string.IsNullOrEmpty(start))
            {
                repairlist = repairlist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
            }
            if (!string.IsNullOrEmpty(end))
            {
                repairlist = repairlist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
            }
            if (userinfo.isallproject == 0)
            {
                prolist = prolist.Where(it => userinfo.projectlist.Contains(it.id));
                repairlist = repairlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wxlist = wxlist.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            int allnums = repairlist.Count(), allsatisfied = repairlist.Where(p => p.wostate == (int)EnumWorkOrderState.evaluate && p.score >= 3).Count(), 
                allnosatisfied = repairlist.Where(p => (p.wostate == (int)EnumWorkOrderState.evaluate && p.score < 3) || p.wostate == (int)EnumWorkOrderState.deal).Count();    //评价
            string allsatisfiedrate = "", allnosatisfiedrate = "";
            if (allnums > 0)
            {
                allsatisfiedrate = Math.Round(((double)allsatisfied * 100 / allnums), 2) + "%";
                allnosatisfiedrate = Math.Round(((double)allnosatisfied * 100 / allnums), 2) + "%";
            }

            recordCount = wxlist.Count();
            var list = wxlist.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var pros = list.Select(p => p.projectid);
            var prolists = prolist.Where(p => pros.Contains(p.id)).ToList();
            var repairlists = repairlist.ToList();
            var modellist = list.Select(p =>
            {
                var pro = prolists.Where(q => q.id == p.projectid).FirstOrDefault();
                var userrepairs = repairlists.Where(q => q.dealuser.Contains(p.usercode));

                int allnum = userrepairs.Count(), satisfied = userrepairs.Count(q => q.wostate == (int)EnumWorkOrderState.evaluate && q.score >= 3), 
                nosatisfied = userrepairs.Count(q => (q.wostate == (int)EnumWorkOrderState.evaluate && q.score < 3) || q.wostate == (int)EnumWorkOrderState.deal);    //评价
                string satisfiedrate = "", nosatisfiedrate = "";
                if (allnum > 0)
                {
                    satisfiedrate = Math.Round(((double)satisfied * 100 / allnum), 2) + "%";   //满意率
                    nosatisfiedrate = Math.Round(((double)nosatisfied * 100 / allnum), 2) + "%";   //不满意率
                }
                return new
                {
                    p.usercode,
                    p.username,
                    projectname = pro != null ? pro.project_name : "",
                    province = pro != null ? pro.provincename : "",
                    city = pro != null ? pro.cityname : "",
                    protypename = pro != null ? pro.protypename : "",
                    satisfied,
                    nosatisfied,
                    satisfiedrate,
                    nosatisfiedrate
                };
            });

            var obj = new
            {
                list = modellist,
                allsatisfied,                //满意
                allnosatisfied,            //不满意
                allsatisfiedrate,        //满意率
                allnosatisfiedrate    //不满意率
            };
            return obj;

        }

        /// <summary>
        /// 人员维修及时率统计报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetUseRpairetimerateStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var prolist = from pro in _collection.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 //项目属性
                          };

            var repairlist = from repair in _collection_wo_repair_base.AsQueryable()
                             where repair.isdelete == 0 && repair.wostate == (int)EnumWorkOrderState.evaluate
                             select repair;

            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG");

            if (!string.IsNullOrEmpty(keyword))
                wxlist = wxlist.Where(it => it.usercode.Contains(keyword) || it.username.Contains(keyword));

            if (!string.IsNullOrEmpty(projectid))
            {
                prolist = prolist.Where(it => it.id.Equals(projectid));
                repairlist = repairlist.Where(it => it.projectid.Equals(projectid));
                wxlist = wxlist.Where(it => it.projectid.Equals(projectid));
            }
            if (!string.IsNullOrEmpty(start))
            {
                repairlist = repairlist.Where(p => p.createtime >= DateTime.Parse(start + " 00:00:00"));
            }
            if (!string.IsNullOrEmpty(end))
            {
                repairlist = repairlist.Where(p => p.createtime <= DateTime.Parse(end + " 23:59:59"));
            }
            if (userinfo.isallproject == 0)
            {
                prolist = prolist.Where(it => userinfo.projectlist.Contains(it.id));
                repairlist = repairlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wxlist = wxlist.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            var querylist = repairlist.ToList();
            //2小时内
            int twoHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 2).Count();
            //4小时内
            int fourHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 2 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 4).Count();
            //8小时内
            int eightHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 4 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 8).Count();
            //24小时内
            int tfourHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 8 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 24).Count();
            //24小时以上
            int tfourUpHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 24).Count();

            recordCount = wxlist.Count();
            var list = wxlist.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var pros = list.Select(p => p.projectid);
            var prolists = prolist.Where(p => pros.Contains(p.id)).ToList();
            var repairlists = repairlist.ToList();
            var modellist = list.Select(p =>
            {
                var pro = prolists.Where(q => q.id == p.projectid).FirstOrDefault();
                var userrepairs = repairlists.Where(q => q.dealuser.Contains(p.usercode));

                int istwohour = userrepairs.Count(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 2);
                int isfourhour = userrepairs.Count(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 2 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 4);
                int iseighthour = userrepairs.Count(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 4 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 8);
                int istfourhour = userrepairs.Count(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 8 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 24);
                int istfouruphour = userrepairs.Count(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 24);

                return new
                {
                    p.usercode,
                    p.username,
                    projectname = pro != null ? pro.project_name : "",
                    province = pro != null ? pro.provincename : "",
                    city = pro != null ? pro.cityname : "",
                    protypename = pro != null ? pro.protypename : "",
                    istwohour,
                    isfourhour,
                    iseighthour,
                    istfourhour,
                    istfouruphour
                };
            });

            var obj = new
            {
                list = modellist,
                twohournum = twoHourNum,        //2小时内
                fourhournum = fourHourNum,      //4小时内
                eighthournum = eightHourNum,    //8小时内
                tfourhournum = tfourHourNum,    //24小时内
                tfourupHournum = tfourUpHourNum //24小时以上
            };
            return obj;
        }

        /// <summary>
        /// 人员个人工作量统计报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetUseWorkStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var prolist = from pro in _collection.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 //项目属性
                          };

            var repairlist = from repair in _collection_wo_repair_base.AsQueryable()
                             where repair.isdelete == 0 && (repair.wostate == (int)EnumWorkOrderState.deal || repair.wostate == (int)EnumWorkOrderState.evaluate)
                             select repair;
            //保养工单列表
            var maintainlist = from maintain in _collection_wo_maintain_base.AsQueryable()
                               where maintain.isdelete == false && (maintain.wostate >= (int)EnumWoMaintainState.deal)
                               select maintain;
            //巡检工单列表
            var eqrunninglist = from running in _collection_equipmentrunning.AsQueryable()
                                where running.isdelete == 0 && (running.wostate == (int)EnumEquipmentRunningState.deal)
                                select running;

            //超时工单
            var wotimeoutlist = from timeout in _collection_wo_timeout.AsQueryable()
                                where timeout.isdelete == false && timeout.isover == true
                                select timeout;
            var wotimeoutlists = wotimeoutlist.ToList().Select(p =>
             {
                 var proid = string.Empty;
                 var wodealtime = p.createtime;
                 if (p.wotype == (int)EnumWoType.inspection)
                 {
                     var eqrunmodel = eqrunninglist.Where(e => e.id == p.woid).FirstOrDefault();
                     if (eqrunmodel != null)
                     {
                         proid = eqrunmodel.projectid;
                         wodealtime = eqrunmodel.dealtime;
                     }
                 }
                 if(p.wotype==(int)EnumWoType.maintain)
                 {
                     var eqmaintainmodel = maintainlist.Where(e => e.id == p.woid).FirstOrDefault();
                     if (eqmaintainmodel != null)
                     {
                         proid = eqmaintainmodel.projectid;
                         wodealtime = eqmaintainmodel.dealtime;
                     }
                 }
                 return new
                 {
                     p.id,
                     p.woid,
                     p.wocode,
                     p.wotype,
                     p.touser,
                     p.tousername,
                     p.times,
                     p.timeoutreason,
                     p.manager,
                     p.istimeout,
                     p.isover,
                     p.isdelete,
                     p.grade,
                     p.createtime,
                     proid,
                     wodealtime
                 };
             });

            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG" || p.rolecode == "YWZG");

            if (!string.IsNullOrEmpty(keyword))
                wxlist = wxlist.Where(it => it.usercode.Contains(keyword) || it.username.Contains(keyword));

            if (!string.IsNullOrEmpty(projectid))
            {
                prolist = prolist.Where(it => it.id.Equals(projectid));
                repairlist = repairlist.Where(it => it.projectid.Equals(projectid));
                maintainlist = maintainlist.Where(it => it.projectid.Equals(projectid));
                eqrunninglist = eqrunninglist.Where(it => it.projectid.Equals(projectid));
                wxlist = wxlist.Where(it => it.projectid.Equals(projectid));
                wotimeoutlists = wotimeoutlists.Where(it => it.proid.Equals(projectid));
            }
            if (!string.IsNullOrEmpty(start))
            {
                repairlist = repairlist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
                maintainlist = maintainlist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
                eqrunninglist = eqrunninglist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
                wotimeoutlists = wotimeoutlists.Where(p => p.wodealtime >= DateTime.Parse(start + " 00:00:00"));
            }
            if (!string.IsNullOrEmpty(end))
            {
                repairlist = repairlist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
                maintainlist = maintainlist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
                eqrunninglist = eqrunninglist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
                wotimeoutlists = wotimeoutlists.Where(p => p.wodealtime <= DateTime.Parse(end + " 23:59:59"));
            }
            if (userinfo.isallproject == 0)
            {
                prolist = prolist.Where(it => userinfo.projectlist.Contains(it.id));
                repairlist = repairlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                maintainlist = maintainlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                eqrunninglist = eqrunninglist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wxlist = wxlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wotimeoutlists = wotimeoutlists.Where(it => userinfo.projectlist.Contains(it.proid));
            }

            //维修统计
            int repairnum = 0;
            //维修满意统计
            int repairgoodnum = 0;
            //保养统计
            int maintainnum = 0;
            //巡检统计
            int equipmentrunningnum = 0;
            //超时工单统计
            int timeoutnum = 0;

            var trepairs = wxlist.ToList().Select(p => p.usercode);
            repairnum = repairlist.Count();
            repairgoodnum = repairlist.Where(p => p.score >= 3).Count();
            //maintainnum = maintainlist.Where(p => trepairs.Contains(p.dealby)).Count();
            maintainnum = maintainlist.Count();
            equipmentrunningnum = eqrunninglist.Where(p => trepairs.Contains(p.dealby)).Count();
            timeoutnum= wotimeoutlists.Count();

            recordCount = wxlist.Count();
            var list = wxlist.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();


            var pros = list.Select(p => p.projectid);
            var prolists = prolist.Where(p => pros.Contains(p.id)).ToList();
            var repairs = list.Select(p => p.usercode);
            var repairlists = repairlist.ToList();
            //var maintainlists = maintainlist.Where(p => repairs.Contains(p.dealby)).ToList();//保养
            var maintainlists = maintainlist.ToList();//保养
            var eqrunninglists = eqrunninglist.Where(p => repairs.Contains(p.dealby)).ToList();//巡检
            
            var modellist = list.Select(p =>
            {
                var pro = prolists.Where(q => q.id == p.projectid).FirstOrDefault();
                int repaircount = repairlists.Where(q => q.dealuser.Contains(p.usercode)).Count();
                int repairgoodcount = repairlists.Where(q => q.dealuser.Contains(p.usercode) && q.score >= 3).Count();
                //int maintaincount = maintainlists.Where(q => q.dealby == p.usercode).Count(); ;
                int maintaincount = maintainlists.Where(q => q.dealuser.Contains(p.usercode)).Count(); 
                int equipmentrunningcount = eqrunninglists.Where(q => q.dealby == p.usercode).Count(); 
                int timeoutcount = wotimeoutlists.Where(q => q.touser.Contains(p.usercode)).Count();
                return new
                {
                    projectid = pro != null ? pro.id : "",
                    p.rolecode,
                    p.usercode,
                    p.username,
                    projectname = pro != null ? pro.project_name : "",
                    provincename = pro != null ? pro.provincename : "",
                    cityname = pro != null ? pro.cityname : "",
                    protypename = pro != null ? pro.protypename : "",
                    repaircount,
                    repairgoodcount,
                    maintaincount,
                    equipmentrunningcount,
                    timeoutcount
                };
            });

            var obj = new
            {
                list = modellist,
                repairnum,                      //维修统计
                repairgoodnum,//维修满意统计
                maintainnum,                  //保养统计
                equipmentrunningnum,    //巡检统计
                timeoutnum  //超时工单统计
            };
            return obj;
        }

        /// <summary>
        /// 人员个人工作量统计报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetUseWorkCount(string keyword, string projectid, string start, string end, UserAccountInfoModel userinfo)
        {
            var repairlist = from repair in _collection_wo_repair_base.AsQueryable()
                             where repair.isdelete == 0 && (repair.wostate == (int)EnumWorkOrderState.deal || repair.wostate == (int)EnumWorkOrderState.evaluate)
                             select repair;
            //保养工单列表
            var maintainlist = from maintain in _collection_wo_maintain_base.AsQueryable()
                               where maintain.isdelete == false && (maintain.wostate >= (int)EnumWoMaintainState.deal)
                               select maintain;
            //巡检工单列表
            var eqrunninglist = from running in _collection_equipmentrunning.AsQueryable()
                                where running.isdelete == 0 && (running.wostate == (int)EnumEquipmentRunningState.deal)
                                select running;
            //超时工单
            var wotimeoutlist = from timeout in _collection_wo_timeout.AsQueryable()
                                where timeout.isdelete == false && timeout.isover == true
                                select timeout;
            var wotimeoutlists = wotimeoutlist.ToList().Select(p =>
            {
                var proid = string.Empty;
                var wodealtime = p.createtime;
                if (p.wotype == (int)EnumWoType.inspection)
                {
                    var eqrunmodel = eqrunninglist.Where(e => e.id == p.woid).FirstOrDefault();
                    if (eqrunmodel != null)
                    {
                        proid = eqrunmodel.projectid;
                        wodealtime = eqrunmodel.dealtime;
                    }
                }
                if (p.wotype == (int)EnumWoType.maintain)
                {
                    var eqmaintainmodel = maintainlist.Where(e => e.id == p.woid).FirstOrDefault();
                    if (eqmaintainmodel != null)
                    {
                        proid = eqmaintainmodel.projectid;
                        wodealtime = eqmaintainmodel.dealtime;
                    }
                }
                return new
                {
                    p.id,
                    p.woid,
                    p.wocode,
                    p.wotype,
                    p.touser,
                    p.tousername,
                    p.times,
                    p.timeoutreason,
                    p.manager,
                    p.istimeout,
                    p.isover,
                    p.isdelete,
                    p.grade,
                    p.createtime,
                    proid,
                    wodealtime
                };
            });

            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG" || p.rolecode == "YWZG");

            if (!string.IsNullOrEmpty(keyword))
                wxlist = wxlist.Where(it => it.usercode.Contains(keyword) || it.username.Contains(keyword));

            if (!string.IsNullOrEmpty(projectid))
            {
                repairlist = repairlist.Where(it => it.projectid.Equals(projectid));
                maintainlist = maintainlist.Where(it => it.projectid.Equals(projectid));
                eqrunninglist = eqrunninglist.Where(it => it.projectid.Equals(projectid));
                wxlist = wxlist.Where(it => it.projectid.Equals(projectid));
                wotimeoutlists = wotimeoutlists.Where(it => it.proid.Equals(projectid));
            }
            if (!string.IsNullOrEmpty(start))
            {
                repairlist = repairlist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
                maintainlist = maintainlist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
                eqrunninglist = eqrunninglist.Where(p => p.dealtime >= DateTime.Parse(start + " 00:00:00"));
                wotimeoutlists = wotimeoutlists.Where(p => p.wodealtime >= DateTime.Parse(start + " 00:00:00"));
            }
            if (!string.IsNullOrEmpty(end))
            {
                repairlist = repairlist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
                maintainlist = maintainlist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
                eqrunninglist = eqrunninglist.Where(p => p.dealtime <= DateTime.Parse(end + " 23:59:59"));
                wotimeoutlists = wotimeoutlists.Where(p => p.wodealtime <= DateTime.Parse(end + " 23:59:59"));
            }
            if (userinfo.isallproject == 0)
            {
                repairlist = repairlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                maintainlist = maintainlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                eqrunninglist = eqrunninglist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wxlist = wxlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wotimeoutlists = wotimeoutlists.Where(it => userinfo.projectlist.Contains(it.proid));
            }

            var modellist = wxlist.ToList().Select(p =>
            {
                int repaircount = repairlist.Where(q => q.dealuser.Contains(p.usercode)).Count();
                //int repairgoodcount = repairlist.Where(q => q.dealuser.Contains(p.usercode) && q.score >= 3).Count();
                int maintaincount = maintainlist.Where(q => q.dealuser.Contains(p.usercode)).Count(); 
                int equipmentrunningcount = eqrunninglist.Where(q => q.dealby == p.usercode).Count(); 
                int timeoutcount = wotimeoutlists.Where(q => q.touser.Contains(p.usercode)).Count();
                return new
                {
                    p.usercode,
                    p.username,
                    repaircount,
                    //repairgoodcount,
                    maintaincount,
                    equipmentrunningcount,
                    timeoutcount,
                    totalcount = repaircount+ maintaincount+ equipmentrunningcount
                };
            });

            return modellist;
        }

        /// <summary>
        /// 设备状态分析报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetEquipmentStateStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var queryrepair = from repair in _collection_wo_repair_base.AsQueryable()
                              where repair.isdelete == 0 && repair.wostate != (int)EnumWorkOrderState.cancle && repair.wostate >= (int)EnumWorkOrderState.deal
                               && repair.equipmentid != null
                              select repair;

            //关联查询
            var query = from p in _collection_eqp_equipment_info.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.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 : "",
                            p.buildid,
                            bulidingname = bldDefa.Count() > 0 ? bldDefa.First().buildname : "",
                            p.projectid,
                            projectname = projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
                            projectdelete = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().isdelete : 0,
                            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 : ""
                        };
            #region 查询条件
            query = query.Where(p => p.projectdelete == 0);
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.equipment_name.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
            {
                queryrepair = queryrepair.Where(it => it.projectid.Equals(projectid));
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                queryrepair = queryrepair.Where(p => p.createtime >= DateTime.Parse(start + " 00:00:00"));
            }
            if (!string.IsNullOrEmpty(end))
            {
                queryrepair = queryrepair.Where(p => p.createtime <= DateTime.Parse(end + " 23:59:59"));
            }

            if (userinfo.isallproject == 0)
            {
                queryrepair = queryrepair.Where(it => userinfo.projectlist.Contains(it.projectid));
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            int repaircount = queryrepair.Where(x => x.wostate != (int)EnumWorkOrderState.cancle).Count();
            //已维修
            int repairedcount = queryrepair.Where(x => x.wostate == (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.evaluate).Count();
            //未维修
            int norepaircount = queryrepair.Where(x => x.wostate < (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.hangup).Count();
            #endregion

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

            var modellist = list.ToList().Select(p => {
                var queryrepairlist = queryrepair.Where(x => x.equipmentid == p.id);
                int repairnum = queryrepairlist.Where(x => x.wostate != (int)EnumWorkOrderState.cancle).Count();
                //已维修
                int repairednum = queryrepairlist.Where(x => x.wostate == (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.evaluate).Count();
                //未维修
                int norepairnum = queryrepairlist.Where(x => x.wostate < (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.hangup).Count();
                return new
                {
                    p.id,
                    equipmentname = p.equipment_name,
                    p.projectname,
                    p.provincename,
                    p.cityname,
                    p.protypename,
                    p.systemname,
                    repairnum,
                    repairednum,
                    norepairnum
                };
            });

            var obj = new
            {
                list = modellist,
                repaircount = repaircount,   //维修次数
                repairedcount = repairedcount,
                norepaircount = norepaircount,
            };
            return obj;
        }

        /// <summary>
        /// 设备保养分析报表 - 列表/统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetEquipmentMaintainStatisticsByPage(string keyword, string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var querymaintain = from maintain in _collection_wo_maintain_base.AsQueryable() select maintain;
            //关联查询
            var query = from mat in _collection_matters.AsQueryable()
                        join proje in _collection.AsQueryable() on mat.projectid equals proje.id into projeDefa
                        where mat.isdelete == false && mat.checktype== (int)EnumWoType.maintain
                        select new {
                            mat.id,
                            mat.matter,
                            mat.projectid,
                            projectname= projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
                            provincecode = projeDefa.Count() > 0 ? projeDefa.First().project_province : "",
                            citycode= projeDefa.Count() > 0 ? projeDefa.First().project_city : "",
                            protypeid= projeDefa.Count() > 0 ? projeDefa.First().project_property : "",
                        };
            var provicemodels = from provice in _collection_sys_provinces.AsQueryable()
                               select provice;
            var citymodels = from city in _collection_sys_city.AsQueryable()
                            select city;
            var protypemodels = from dictype in _collection_sys_dictionaryvalue.AsQueryable()
                               select dictype;
            #region 查询条件
            //var queryList = query.ToList();
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(it => it.matter.Contains(keyword));
            if (!string.IsNullOrEmpty(projectid))
            {
                querymaintain = querymaintain.Where(it => it.projectid.Equals(projectid));
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                querymaintain = querymaintain.Where(p => p.createtime >= DateTime.Parse(start + " 00:00:00"));
            }
            if (!string.IsNullOrEmpty(end))
            {
                querymaintain = querymaintain.Where(p => p.createtime <= DateTime.Parse(end + " 23:59:59"));
            }

            if (userinfo.isallproject == 0)
            {
                querymaintain = querymaintain.Where(it => userinfo.projectlist.Contains(it.projectid));
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //int maintaincount = querymaintain.Where(x => x.wostate <= (int)EnumWoMaintainState.deal).Count();
            ////int isfinish = 0;
            ////已保养
            //int maintainedcount = querymaintain.Where(x => x.wostate < (int)EnumWoMaintainState.deal).Count();
            ////未保养
            //int nomaintaincount = querymaintain.Where(x => x.wostate == (int)EnumWoMaintainState.deal).Count();
            int maintaincount = 0;
            //int isfinish = 0;
            //已保养
            int maintainedcount = 0;
            //未保养
            int nomaintaincount = 0;
            #endregion
            var modellist = new List<Eqp_EquipmentMaintainDto>();
            foreach (var item in query.ToList())
            {
                //var querymaintainlist = querymaintain.Where(x => x.projectid == item.id);
                var querymaintainlist = querymaintain.Where(x => x.projectid == item.id).ToList();
                var newquerymaintainlist = new List<Wo_Maintain_Base>();
                #region 筛选设备后重新赋值
                if (!string.IsNullOrEmpty(item.id))
                {
                    foreach (var itemeq in querymaintainlist)
                    {
                        if (itemeq.matterids != null)
                        {
                            var eqid = string.Join(",", itemeq.matterids);
                            if (!string.IsNullOrWhiteSpace(eqid))
                            {
                                if (eqid.Contains(item.id))
                                {
                                    newquerymaintainlist.Add(itemeq);
                                }
                            }
                        }
                    }
                }
                else
                {
                    newquerymaintainlist = querymaintainlist;
                }
                #endregion
                //保养次数：已处理次数
                //int maintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipmentid == item.id).Count();
                int maintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal).Count();
                maintaincount += maintainnum;
                //int isfinish = 0;
                //已处理，设备正常数量
                //int maintainednum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipmentid == item.id & x.equipstate == (int)EnumWoMEquipmentState.normal).Count();
                int maintainednum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipstate == (int)EnumWoMEquipmentState.normal).Count();
                maintainedcount += maintainednum;
                //已处理，设备异常数量
                //int nomaintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipmentid == item.id & x.equipstate == (int)EnumWoMEquipmentState.abnormal).Count();
                int nomaintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipstate == (int)EnumWoMEquipmentState.abnormal).Count();
                nomaintaincount += nomaintainnum;
                var model = new Eqp_EquipmentMaintainDto();
                model.id = item.id;
                model.mattername = item.matter;
                //model.equipmentname = item.equipment_name;
                //model.projectid = projectid;
                model.projectname = item.projectname;

                var provicemodel = provicemodels.Where(v => v.provincecode == item.provincecode);
                model.provincename = provicemodel.Count() > 0 ? provicemodel.First().provincename : "";

                var citymodel = citymodels.Where(c => c.citycode == item.citycode);
                model.cityname = citymodel.Count() > 0 ? citymodel.First().cityname : "";

                var protypemodel = protypemodels.Where(t => t.id == item.protypeid);
                model.protypename = protypemodel.Count() > 0 ? protypemodel.First().name : "";
                
                model.maintainnum = maintainnum;    //保养次数
                model.maintainednum = maintainednum;
                model.nomaintainnum = nomaintainnum;
                modellist.Add(model);
            }
            recordCount = modellist.Count();
            var list = modellist.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var obj = new
            {
                list = list,
                maintainnum = maintaincount,   //保养次数
                maintainednum = maintainedcount,
                nomaintainnum = nomaintaincount,
            };
            return obj;
            #region
            //var querymaintain = from maintain in _collection_wo_maintain_base.AsQueryable() select maintain;
            ////关联查询
            //var query = from p in _collection_eqp_equipment_info.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.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 : "",
            //                p.buildid,
            //                bulidingname = bldDefa.Count() > 0 ? bldDefa.First().buildname : "",
            //                p.projectid,
            //                projectname = projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
            //                projectdelete = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().isdelete : 0,
            //                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 : ""
            //            };
            //#region 查询条件
            ////var queryList = query.ToList();
            //if (!string.IsNullOrEmpty(keyword))
            //    query = query.Where(it => it.equipment_name.Contains(keyword));
            //if (!string.IsNullOrEmpty(projectid))
            //{
            //    querymaintain = querymaintain.Where(it => it.projectid.Equals(projectid));
            //    query = query.Where(p => p.projectid == projectid);
            //}
            //if (!string.IsNullOrEmpty(start))
            //{
            //    querymaintain = querymaintain.Where(p => p.createtime >= DateTime.Parse(start + " 00:00:00"));
            //}
            //if (!string.IsNullOrEmpty(end))
            //{
            //    querymaintain = querymaintain.Where(p => p.createtime <= DateTime.Parse(end + " 23:59:59"));
            //}

            //if (userinfo.isallproject == 0)
            //{
            //    querymaintain = querymaintain.Where(it => userinfo.projectlist.Contains(it.projectid));
            //    query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            //}

            ////int maintaincount = querymaintain.Where(x => x.wostate <= (int)EnumWoMaintainState.deal).Count();
            //////int isfinish = 0;
            //////已保养
            ////int maintainedcount = querymaintain.Where(x => x.wostate < (int)EnumWoMaintainState.deal).Count();
            //////未保养
            ////int nomaintaincount = querymaintain.Where(x => x.wostate == (int)EnumWoMaintainState.deal).Count();
            //int maintaincount = 0;
            ////int isfinish = 0;
            ////已保养
            //int maintainedcount = 0;
            ////未保养
            //int nomaintaincount = 0;
            //#endregion
            //var modellist = new List<Eqp_EquipmentMaintainDto>();
            //foreach (var item in query.ToList())
            //{
            //    //var querymaintainlist = querymaintain.Where(x => x.projectid == item.id);
            //    var querymaintainlist = querymaintain.Where(x => x.projectid == item.id).ToList();
            //    var newquerymaintainlist = new List<Wo_Maintain_Base>();
            //    #region 筛选设备后重新赋值
            //    if (!string.IsNullOrEmpty(item.id))
            //    {
            //        foreach (var itemeq in querymaintainlist)
            //        {
            //            if (itemeq.equipmentid != null)
            //            {
            //                var eqid = string.Join(",", itemeq.equipmentid);
            //                if (!string.IsNullOrWhiteSpace(eqid))
            //                {
            //                    if (eqid.Contains(item.id))
            //                    {
            //                        newquerymaintainlist.Add(itemeq);
            //                    }
            //                }
            //            }
            //        }
            //    }
            //    else
            //    {
            //        newquerymaintainlist = querymaintainlist;
            //    }
            //    #endregion
            //    //保养次数：已处理次数
            //    //int maintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipmentid == item.id).Count();
            //    int maintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal).Count();
            //    maintaincount += maintainnum;
            //    //int isfinish = 0;
            //    //已处理，设备正常数量
            //    //int maintainednum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipmentid == item.id & x.equipstate == (int)EnumWoMEquipmentState.normal).Count();
            //    int maintainednum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipstate == (int)EnumWoMEquipmentState.normal).Count();
            //    maintainedcount += maintainednum;
            //    //已处理，设备异常数量
            //    //int nomaintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipmentid == item.id & x.equipstate == (int)EnumWoMEquipmentState.abnormal).Count();
            //    int nomaintainnum = querymaintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipstate == (int)EnumWoMEquipmentState.abnormal).Count();
            //    nomaintaincount += nomaintainnum;
            //    var model = new Eqp_EquipmentMaintainDto();
            //    model.id = item.id;
            //    model.equipmentname = item.equipment_name;
            //    //model.projectid = projectid;
            //    model.projectname = item.projectname;
            //    model.provincename = item.provincename;
            //    model.cityname = item.cityname;
            //    model.protypename = item.protypename;
            //    model.systemname = item.systemname;
            //    model.maintainnum = maintainnum;    //保养次数
            //    model.maintainednum = maintainednum;
            //    model.nomaintainnum = nomaintainnum;
            //    modellist.Add(model);
            //}
            //recordCount = modellist.Count();
            //var list = modellist.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            //var obj = new
            //{
            //    list = list,
            //    maintainnum = maintaincount,   //保养次数
            //    maintainednum = maintainedcount,
            //    nomaintainnum = nomaintaincount,
            //};
            //return obj;
            #endregion
        }


        /// <summary>
        /// 报修统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 保修统计详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetRepaireListAndStatisticsByPagePc(string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                join equ in _collection_eqp_equipment_info.AsQueryable() on repair.equipmentid equals equ.id into equDefa
                where repair.isdelete == 0 && repair.wostate != (int)EnumWorkOrderState.cancle
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.projectid,
                    repair.createtime,
                    repair.wocode,
                    repair.equipmentid,
                    equipmentname = equDefa != null && equDefa.Count() > 0 ? equDefa.First().equipment_name : null,
                    floorid = equDefa != null && equDefa.Count() > 0 ? equDefa.First().floorid : null,
                    repair.wostate
                };
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //已完成
            int completed = query.Where(x => x.wostate == (int)EnumWorkOrderState.evaluate).Count();
            //未完成
            int unfinished = query.Where(x => x.wostate < (int)EnumWorkOrderState.evaluate || x.wostate == (int)EnumWorkOrderState.hangup).Count();

            recordCount = query.Count();
            var querylist = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var flrs = querylist.Select(p => p.floorid);
            //获取设备列表 by 楼层foorid
            var queryfloor = (from floor in _collection_sys_floor.AsQueryable() where flrs.Contains(floor.id) select floor).ToList();

            var modellist = new List<Wo_Repair_BaseDto>();
            foreach (var item in querylist)
            {
                var modelFloor = queryfloor.FirstOrDefault(x => x.id == item.floorid);
                int isfinish = 0;
                if (item.wostate < (int)EnumWorkOrderState.evaluate || item.wostate == (int)EnumWorkOrderState.hangup)
                    isfinish = 0;
                else if (item.wostate == (int)EnumWorkOrderState.evaluate)
                    isfinish = 1;
                var model = new Wo_Repair_BaseDto();
                model.id = item.id;
                model.wocode = item.wocode;
                model.wostate = item.wostate;
                model.isfinish = isfinish;
                model.floorname = modelFloor != null ? modelFloor.floorname : "";
                modellist.Add(model);
            }

            var obj = new
            {
                list = modellist,
                completed = completed,
                unfinished = unfinished
            };
            return obj;
        }

        /// <summary>
        /// 耗材统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 耗材统计详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetMaterialListAndStatisticsByPagePc(string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                join pro in _collection.AsQueryable() on repair.projectid equals pro.id into proDefa
                join equ in _collection_eqp_equipment_info.AsQueryable() on repair.equipmentid equals equ.id into equDefa
                where repair.isdelete == 0 && (repair.ismaterials == 1 || repair.islosematerials == 1)
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.wocode,
                    repair.projectid,
                    projectname = proDefa != null && proDefa.Count() > 0 ? proDefa.First().project_name : null,
                    repair.equipmentid,
                    equipmentname = equDefa != null && equDefa.Count() > 0 ? equDefa.First().equipment_name : null,
                    repair.materials,
                    repair.losematerials,
                    repair.createtime
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

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

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

            return list;
        }

        /// <summary>
        /// 满意度统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 满意度统计详情）
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetRepairEvaluateListAndStatisticsByPagePc(string projectid, string start, string end, int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                where repair.isdelete == 0 && repair.wostate == (int)EnumWorkOrderState.evaluate
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.projectid,
                    repair.createtime,
                    repair.wocode,
                    repair.score,
                    issatisfied = repair.score >= 3 ? 1 : 0,
                    repair.wostate
                };
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //满意
            int satisfied = query.Where(x => x.issatisfied == 1).Count();
            //不满意
            int nosatisfied = query.Where(x => x.issatisfied == 0).Count();

            recordCount = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var obj = new
            {
                list = list,
                satisfied = satisfied,
                nosatisfied = nosatisfied
            };
            return obj;
        }

        /// <summary>
        /// 人员个人接单量统计报表（列表、统计） - 报表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="projectid"></param>
        /// <param name="type"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        public object GetUserAcceptCount(string keyword, string projectid, int type, string start, string end, UserAccountInfoModel userinfo)
        {
            var repairlist = from repair in _collection_wo_repair_base.AsQueryable()
                             where repair.isdelete == 0 && (repair.wostate >= (int)EnumWorkOrderState.assign && repair.wostate <= (int)EnumWorkOrderState.evaluate)
                             select repair;

            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.head_img,
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null,
                               p.idcardno,
                               p.remark
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG");

            if (!string.IsNullOrEmpty(projectid))
            {
                repairlist = repairlist.Where(it => it.projectid.Equals(projectid));
                wxlist = wxlist.Where(it => it.projectid.Equals(projectid));
            }
            if (userinfo.isallproject == 0)
            {
                repairlist = repairlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                wxlist = wxlist.Where(it => userinfo.projectlist.Contains(projectid));
            }

            DataTable dt = new DataTable();
            dt.Columns.Add("人员名称", typeof(string));

            //List<string> cols = new List<string> { "人员名称" };
            //List<ArrayList> rows = new List<ArrayList>();
            switch (type)
            {
                case 1://天
                    var stdate = DateTime.Parse(start + " 00:00:00");
                    var eddate = DateTime.Parse(end + " 23:59:59");
                    var coldate = stdate;
                    while (coldate < eddate)
                    {
                        //cols.Add(coldate.ToString("yyyy-MM-dd"));
                        dt.Columns.Add(coldate.ToString("yyyy年MM月dd日"), typeof(string));
                        coldate = coldate.AddDays(1);
                    }

                    foreach (var user in wxlist.ToList())
                    {
                        DataRow dr = dt.NewRow();
                        dr["人员名称"] = user.usercode + "-" + user.username;
                        //ArrayList row = new ArrayList { user.usercode + "-" + user.username };

                        var rdate = stdate;
                        while (rdate < eddate)
                        {
                            var n = repairlist.Count(p => p.createtime >= rdate && p.createtime < rdate.AddDays(1)
                              && (p.touser.Contains(user.usercode) || p.dealuser.Contains(user.usercode)));

                            //row.Add(n.ToString());
                            dr[rdate.ToString("yyyy年MM月dd日")] = n;
                            rdate = rdate.AddDays(1);
                        }
                        // rows.Add(row);
                        dt.Rows.Add(dr);
                    }

                    break;
                case 2://月
                    var stmdate = DateTime.Parse(start + "-01 00:00:00");
                    var edmdate = DateTime.Parse(end + "-01 23:59:59");
                    var colmdate = stmdate;
                    while (colmdate < edmdate)
                    {
                        //cols.Add(colmdate.ToString("yyyy-MM"));
                        dt.Columns.Add(colmdate.ToString("yyyy年MM月"), typeof(string));
                        colmdate = colmdate.AddMonths(1);
                    }

                    foreach (var user in wxlist.ToList())
                    {
                        DataRow dr = dt.NewRow();
                        dr["人员名称"] = user.usercode + "-" + user.username;
                        //ArrayList row = new ArrayList { user.usercode + "-" + user.username };

                        var rdate = stmdate;
                        while (rdate < edmdate)
                        {
                            var n = repairlist.Count(p => p.createtime >= rdate && p.createtime < rdate.AddMonths(1).AddDays(-1)
                             && (p.touser.Contains(user.usercode) || p.dealuser.Contains(user.usercode)));

                            //row.Add(n.ToString());
                            dr[rdate.ToString("yyyy年MM月")] = n;
                            rdate = rdate.AddMonths(1);
                        }
                        //rows.Add(row);
                        dt.Rows.Add(dr);
                    }
                    break;
                case 3://年
                    var stydate = DateTime.Parse(start + "-01-01 00:00:00");
                    var edydate = DateTime.Parse(end + "-01-01 23:59:59");
                    var colydate = stydate;
                    while (colydate < edydate)
                    {
                        //cols.Add(colydate.ToString("yyyy"));
                        dt.Columns.Add(colydate.ToString("yyyy年"), typeof(string));
                        colydate = colydate.AddYears(1);
                    }

                    foreach (var user in wxlist.ToList())
                    {
                        DataRow dr = dt.NewRow();
                        dr["人员名称"] = user.usercode + "-" + user.username;
                        //ArrayList row = new ArrayList { user.usercode + "-" + user.username };

                        var rdate = stydate;
                        while (rdate < edydate)
                        {
                            var n = repairlist.Count(p => p.createtime >= rdate && p.createtime < rdate.AddYears(1).AddDays(-1)
                             && (p.touser.Contains(user.usercode) || p.dealuser.Contains(user.usercode)));

                            //row.Add(n.ToString());
                            dr[rdate.ToString("yyyy年")] = n;
                            rdate = rdate.AddYears(1);
                        }
                        //rows.Add(row);
                        dt.Rows.Add(dr);
                    }
                    break;
            }

            //var obj = new
            //{
            //    cols,
            //    rows
            //};

            return dt;
        }

        #endregion

        #region App统计
        /// <summary>
        /// 设备巡检详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 设备巡检详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetRunningListAndStatisticsByPage(string projectid, string start, string end, string matterid,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from running in _collection_equipmentrunning.AsQueryable()
                where running.isdelete == 0 
                orderby running.createtime descending
                select new
                {
                    running.id,
                    running.wocode,
                    running.matterids,
                    //running.systemid,
                    //running.equipmentid,
                    running.projectid,
                    running.createtime,
                    running.wostate,
                    running.quipmenttype
                };
            #region
            //if (!string.IsNullOrEmpty(systemid))
            //{
            //    if (systemid == "0")
            //    {
            //        query = query.Where(p => (p.wostate >= (int)EnumEquipmentRunningState.deal) && p.equipmentid == null);
            //    }
            //    else if (systemid == "1")
            //    {
            //        query = query.Where(p => (p.wostate >= (int)EnumEquipmentRunningState.deal) && p.equipmentid != null);
            //    }
            //    else
            //    {
            //        query = query.Where(p => p.systemid == systemid);
            //    }
            //}
            #endregion
            if(!string.IsNullOrWhiteSpace(matterid))
            {
                query = query.Where(p => p.matterids.Contains(matterid));
            }
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //未完成
            int unfinish = query.Where(x => x.wostate != (int)EnumEquipmentRunningState.deal ).Count();
            //已巡检异常
            int abnormal = query.Where(x => x.wostate >= (int)EnumEquipmentRunningState.deal && x.quipmenttype==(int)EnumWoREquipmentState.abnormal).Count();

            recordCount = query.Count();
            var querylist = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            var modellist = new List<Wo_Running_BaseDto>();
            foreach (var item in querylist)
            {
                int isfinish = 0;
                if (item.wostate != (int)EnumEquipmentRunningState.deal)
                    isfinish = 0;
                else if (item.wostate == (int)EnumEquipmentRunningState.deal)
                    isfinish = 1;
                var model = new Wo_Running_BaseDto();
                model.id = item.id;
                model.wocode = item.wocode;
                model.projectid = item.projectid;
                model.wostate = item.wostate;
                model.isfinish = isfinish;
                model.isnormal = item.quipmenttype;
                modellist.Add(model);
            }

            var obj = new
            {
                list = modellist,
                unfinish,
                abnormal
            };
            return obj;
        }

        /// <summary>
        /// 设备保养详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 设备保养详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetMaintainListAndStatisticsByPage(string projectid, string start, string end, string matterid,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var querymaintain = from maintain in _collection_wo_maintain_base.AsQueryable() select maintain;
            //关联查询
            var query =
                from maintain in _collection_wo_maintain_base.AsQueryable()
                where maintain.isdelete == false
                orderby maintain.createtime descending
                select new
                {
                    maintain.id,
                    maintain.wocode,
                    maintain.matterids,
                    //maintain.systemid,
                    //maintain.equipmentid,
                    maintain.projectid,
                    maintain.createtime,
                    maintain.wostate,
                    maintain.equipstate
                };
            //if (!string.IsNullOrEmpty(systemid))
            //{
            //    if (systemid == "0")
            //    {
            //        query = query.Where(p => (p.wostate >= (int)EnumEquipmentRunningState.deal) && p.equipmentid == null);
            //    }
            //    else if (systemid == "1")
            //    {
            //        query = query.Where(p => (p.wostate >= (int)EnumEquipmentRunningState.deal) && p.equipmentid != null);
            //    }
            //    else
            //    {
            //        query = query.Where(p => p.systemid == systemid);
            //    }
            //}
            if (!string.IsNullOrWhiteSpace(matterid))
            {
                query = query.Where(p => p.matterids.Contains(matterid));
            }
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //未完成
            int unfinish = query.Where(x => x.wostate != (int)EnumWoMaintainState.deal).Count();
            //异常
            int abnormal = query.Where(x => x.wostate >= (int)EnumWoMaintainState.deal && x.equipstate == (int)EnumWoREquipmentState.abnormal).Count();

            recordCount = query.Count();
            var querylist = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            var modellist = new List<Wo_Maintain_ChartDto>();
            foreach (var item in querylist)
            {
                int isfinish = 0;
                if (item.wostate != (int)EnumWoMaintainState.deal)
                    isfinish = 0;
                else if (item.wostate == (int)EnumWoMaintainState.deal)
                    isfinish = 1;
                var model = new Wo_Maintain_ChartDto();
                model.id = item.id;
                model.wocode = item.wocode;
                model.projectid = item.projectid;
                model.wostate = item.wostate;
                model.isfinish = isfinish;
                model.isnormal = item.equipstate;
                modellist.Add(model);
            }

            var obj = new
            {
                list = modellist,
                unfinish,
                abnormal
            };
            return obj;
            
        }

        /// <summary>
        /// 设备状态详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 设备状态详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetRepairStateListAndStatisticsByPage(string projectid, string start, string end, string systemid,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {

            var queryrepair = from repair in _collection_wo_repair_base.AsQueryable()
                              where repair.isdelete == 0 && repair.equipmentid != null && repair.wostate != (int)EnumWorkOrderState.cancle
                              && (repair.wostate < (int)EnumWorkOrderState.deal || repair.wostate == (int)EnumWorkOrderState.hangup)
                              select repair;

            //关联查询
            var query = from p in _collection_eqp_equipment_info.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.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 : "",
                            p.buildid,
                            bulidingname = bldDefa.Count() > 0 ? bldDefa.First().buildname : "",
                            p.projectid,
                            projectname = projeDefa.Count() > 0 ? projeDefa.First().project_name : "",
                            projectdelete = projeDefa != null && projeDefa.Count() > 0 ? projeDefa.First().isdelete : 0,
                            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 : ""
                        };
            if (!string.IsNullOrEmpty(systemid))
            {
                queryrepair = queryrepair.Where(it => it.systemid.Equals(systemid));
                query = query.Where(it => it.systemid.Equals(systemid));
            }
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                queryrepair = queryrepair.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                queryrepair = queryrepair.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                queryrepair = queryrepair.Where(it => userinfo.projectlist.Contains(it.projectid));
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            int norepaircount = queryrepair.ToList().Select(p => p.equipmentid).Distinct().Count();

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

            var modellist = list.ToList().Select(p => {
                int norepairnum = queryrepair.Where(x => x.equipmentid == p.id).Count();
                return new
                {
                    p.id,
                    equipmentname = p.equipment_name,
                    p.projectname,
                    p.provincename,
                    p.cityname,
                    p.protypename,
                    p.systemname,
                    norepairnum
                };
            });

            var obj = new
            {
                list = modellist,
                zccount = recordCount - norepaircount,
                dxcount = norepaircount
            };
            return obj;
        }
        
        /// <summary>
        /// 维修工维修数量排名
        /// </summary>
        /// <param name="projectid">项目id</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        public object GetUserRepairCountReport(string projectid, string start, string end, int top, UserAccountInfoModel userinfo)
        {
            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.head_img,
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };

            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                where repair.isdelete == 0 && repair.wostate == (int)EnumWorkOrderState.evaluate
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.projectid,
                    repair.dealtime,
                    repair.wocode,
                    repair.dealuser,
                };

            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
                userlist = userlist.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.dealtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.dealtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
                userlist = userlist.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            var wxlist = userlist.Where(p => p.rolecode == "YWYG").ToList();
            var repairlist = query.ToList();
            var list = wxlist.Select(p => new
            {
                p.head_img,
                p.usercode,
                p.username,
                count = repairlist.Where(q => q.dealuser.Contains(p.usercode)).Count()
            }).ToList();
            list = list.Where(p => p.count != 0).OrderByDescending(p => p.count).ToList();

            if (top != 0)
            {
                return list.Take(top);
            }
            else
            {
                return list;
            }
        }

        /// <summary>
        /// 设备运维饼图
        /// </summary>
        /// <param name="datetype">日期类型</param>
        /// <returns></returns>
        public object GetEquipmentRoundReport(string projectid, string start, string end, UserAccountInfoModel userinfo)
        {
            var equiplist = from p in _collection_eqp_equipment_info.AsQueryable() where p.isdelete == 0 select p;
            var repairlist = from p in _collection_wo_repair_base.AsQueryable() where p.isdelete == 0 && p.wostate != (int)EnumWorkOrderState.cancle select p;
            var querymaintain = from maintain in _collection_wo_maintain_base.AsQueryable() select maintain;
            var queryrunning = from running in _collection_equipmentrunning.AsQueryable() where running.isdelete == 0 select running;
            if (!string.IsNullOrEmpty(projectid))
            {
                equiplist = equiplist.Where(p => p.projectid == projectid);
                repairlist = repairlist.Where(p => p.projectid == projectid);
                querymaintain = querymaintain.Where(p => p.projectid == projectid);
                queryrunning = queryrunning.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                var starttime = DateTime.Parse(start);
                repairlist = repairlist.Where(p => p.createtime >= starttime);
                querymaintain = querymaintain.Where(p => p.createtime >= starttime);
                queryrunning = queryrunning.Where(p => p.createtime >= starttime);
            }
            if (!string.IsNullOrEmpty(end))
            {
                var endtime = DateTime.Parse(end);
                repairlist = repairlist.Where(p => p.createtime <= endtime);
                querymaintain = querymaintain.Where(p => p.createtime <= endtime);
                queryrunning = queryrunning.Where(p => p.createtime <= endtime);
            }
            if (userinfo.isallproject == 0)
            {
                equiplist = equiplist.Where(it => userinfo.projectlist.Contains(it.projectid));
                repairlist = repairlist.Where(it => userinfo.projectlist.Contains(it.projectid));
                querymaintain = querymaintain.Where(it => userinfo.projectlist.Contains(it.projectid));
                queryrunning = queryrunning.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            var list = repairlist.ToList();
            var maintainlist = querymaintain.ToList();
            var runninglist = queryrunning.ToList();

            //工单来源统计
            int wxcount = list.Where(p => p.channel == (int)EnumWorkOrderChannel.wechat).Count();
            int pccount = list.Where(p => p.channel == (int)EnumWorkOrderChannel.pc).Count();
            int appcount = list.Where(p => p.channel == (int)EnumWorkOrderChannel.ios || p.channel == (int)EnumWorkOrderChannel.android).Count();
            //报修统计
            var repairedlist = list.Where(p => p.wostate >= (int)EnumWorkOrderState.deal);
            int sbcount = repairedlist.Where(p => p.equipmentid != null).Count();
            int rccount = repairedlist.Where(p => p.equipmentid == null).Count();
            //维修及时率统计
            var wxlist = list.Where(p => p.wostate == (int)EnumWorkOrderState.evaluate);
            //2小时内
            int hour2count = wxlist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 2).Count();
            //4小时内
            int hour4count = wxlist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 2 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 4).Count();
            //8小时内
            int hour8count = wxlist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 4 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 8).Count();
            //24小时内
            int hour24count = wxlist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 8 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 24).Count();
            //24小时以上
            int hour24scount = wxlist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 24).Count();
            //维修状态统计
            int ywxcount = list.Where(p => p.wostate == (int)EnumWorkOrderState.evaluate || p.wostate == (int)EnumWorkOrderState.deal).Count();
            int dwxcount = list.Where(p => p.wostate < (int)EnumWorkOrderState.deal || p.wostate == (int)EnumWorkOrderState.hangup).Count();
            //满意度统计
            int mycount = list.Where(p => p.score >= 3 && p.wostate == (int)EnumWorkOrderState.evaluate).Count();
            int nocount = list.Where(p => (p.score < 3 && p.wostate == (int)EnumWorkOrderState.evaluate)|| p.wostate == (int)EnumWorkOrderState.deal).Count();
            //耗材统计
            int hccount = list.Where(p => p.ismaterials == 1 && (p.wostate == (int)EnumWorkOrderState.deal || p.wostate == (int)EnumWorkOrderState.evaluate)).Count();
            int qqcount = list.Where(p => p.islosematerials == 1 && p.wostate == (int)EnumWorkOrderState.hangup).Count();
            //设备状态统计
            int dxcount = list.Where(p => (p.wostate < (int)EnumWorkOrderState.deal || p.wostate == (int)EnumWorkOrderState.hangup) && p.equipmentid != null).Select(p => p.equipmentid).Distinct().Count();
            int zccount = equiplist.Count() - dxcount;
            //设备保养统计 正常/异常 数量
            int mcount = maintainlist.Count();
            int mwcount=maintainlist.Where(x => x.wostate != (int)EnumWoMaintainState.deal).Count();
            int mabnormalcount = maintainlist.Where(x => x.wostate == (int)EnumWoMaintainState.deal & x.equipstate == (int)EnumWoMEquipmentState.abnormal).Count(); ;

            //设备巡检统计 工单总量/未巡检/异常
            int rcount = runninglist.Count();
            int rwcount = runninglist.Where(x => x.wostate != (int)EnumEquipmentRunningState.deal).Count();
            int ryycount = runninglist.Where(x => x.wostate >= (int)EnumEquipmentRunningState.deal && x.quipmenttype == (int)EnumWoREquipmentState.abnormal).Count();

            return new
            {
                source = new { wxcount, pccount, appcount },
                repair = new { sbcount, rccount },
                timely = new { hour2count, hour4count, hour8count, hour24count, hour24scount },
                state = new { ywxcount, dwxcount },
                satisfied = new { mycount, nocount },
                material = new { hccount, qqcount },
                equioment = new { dxcount, zccount },
                maintenance = new { mcount, mwcount, mabnormalcount },
                running = new { rcount, rwcount, ryycount }
            };
        }

        /// <summary>
        /// 来源报修统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 保修统计详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetSourceListAndStatisticsByPage(string projectid, string start, string end, string systemid,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                join equ in _collection_sys_floor.AsQueryable() on repair.floorid equals equ.id into equDefa
                where repair.isdelete == 0 && repair.wostate != (int)EnumWorkOrderState.cancle
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.channel,
                    repair.wocode,
                    repair.systemid,
                    repair.projectid,
                    repair.createtime,
                    floorname = equDefa != null && equDefa.Count() > 0 ? equDefa.First().floorname : null,
                    repair.wostate
                };
            if (!string.IsNullOrEmpty(systemid))
            {
                query = query.Where(p => p.systemid == systemid);
            }
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            int wxcount = query.Where(p => p.channel == (int)EnumWorkOrderChannel.wechat).Count();
            int pccount = query.Where(p => p.channel == (int)EnumWorkOrderChannel.pc).Count();
            int appcount = query.Where(p => p.channel == (int)EnumWorkOrderChannel.ios || p.channel == (int)EnumWorkOrderChannel.android).Count();

            recordCount = query.Count();
            var querylist = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var modellist = querylist.Select(p => new {
                p.id,
                p.wocode,
                p.wostate,
                p.channel
            });

            var obj = new
            {
                list = modellist,
                wxcount,
                pccount,
                appcount
            };
            return obj;
        }

        /// <summary>
        /// 报修统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 保修统计详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetListAndStatisticsByPage(string projectid, string start, string end, string systemid,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                join equ in _collection_sys_floor.AsQueryable() on repair.floorid equals equ.id into equDefa
                where repair.isdelete == 0 && repair.wostate != (int)EnumWorkOrderState.cancle
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.wocode,
                    repair.systemid,
                    repair.equipmentid,
                    repair.projectid,
                    repair.createtime,
                    floorname = equDefa != null && equDefa.Count() > 0 ? equDefa.First().floorname : null,
                    repair.wostate
                };
            if (!string.IsNullOrEmpty(systemid))
            {
                if (systemid == "0")
                {
                    query = query.Where(p => (p.wostate >= (int)EnumWorkOrderState.deal) && p.equipmentid == null);
                }
                else if (systemid == "1")
                {
                    query = query.Where(p => (p.wostate >= (int)EnumWorkOrderState.deal) && p.equipmentid != null);
                }
                else
                {
                    query = query.Where(p => p.systemid == systemid);
                }
            }
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //已完成
            int completed = query.Where(x => x.wostate == (int)EnumWorkOrderState.evaluate || x.wostate == (int)EnumWorkOrderState.deal).Count();
            //未完成
            int unfinished = query.Where(x => x.wostate < (int)EnumWorkOrderState.deal || x.wostate == (int)EnumWorkOrderState.hangup).Count();

            recordCount = query.Count();
            var querylist = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var modellist = new List<Wo_Repair_BaseDto>();
            foreach (var item in querylist)
            {
                int isfinish = 0;
                if (item.wostate < (int)EnumWorkOrderState.deal || item.wostate == (int)EnumWorkOrderState.hangup)
                    isfinish = 0;
                else if (item.wostate == (int)EnumWorkOrderState.evaluate || item.wostate == (int)EnumWorkOrderState.deal)
                    isfinish = 1;
                var model = new Wo_Repair_BaseDto();
                model.id = item.id;
                model.wocode = item.wocode;
                model.wostate = item.wostate;
                model.isfinish = isfinish;
                model.floorname = item.floorname;
                modellist.Add(model);
            }

            var obj = new
            {
                list = modellist,
                completed,
                unfinished
            };
            return obj;
        }

        /// <summary>
        /// 维修及时率统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 维修及时率统计详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetRepaireTimeRateReportByPage(string projectid, string start, string end, string systemid,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                where repair.isdelete == 0 && repair.wostate == (int)EnumWorkOrderState.evaluate
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.systemid,
                    repair.projectid,
                    repair.createtime,
                    repair.wocode,
                    repair.wostate,
                    repair.repairreplace,
                    repair.repairtime,
                    repair.arrivetime,
                    repair.dealtime
                };
            if (!string.IsNullOrEmpty(systemid))
            {
                query = query.Where(p => p.systemid == systemid);
            }
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            var querylist = query.ToList();

            //2小时内
            int twoHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 2).Count();
            //4小时内
            int fourHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 2 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 4).Count();
            //8小时内
            int eightHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 4 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 8).Count();
            //24小时内
            int tfourHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 8 && (x.arrivetime.Value - x.repairtime.Value).TotalHours <= 24).Count();
            //24小时以上
            int tfourUpHourNum = querylist.Where(x => (x.arrivetime.Value - x.repairtime.Value).TotalHours > 24).Count();

            //var modellist = new List<Wo_Repair_BaseRepaireTimeDto>();
            //foreach (var item in querylist)
            //{
            //    #region 查询条件
            //    int istwohour = 0, isfourhour = 0, iseighthour = 0, istfourhour = 0, istfouruphour = 0;
            //    //2小时内
            //    if ((item.arrivetime.Value - item.repairtime.Value).TotalHours <= 2)
            //        istwohour = 1;
            //    if ((item.arrivetime.Value - item.repairtime.Value).TotalHours > 2 && (item.arrivetime.Value - item.repairtime.Value).TotalHours <= 4)
            //        isfourhour = 1;
            //    if ((item.arrivetime.Value - item.repairtime.Value).TotalHours > 4 && (item.arrivetime.Value - item.repairtime.Value).TotalHours <= 8)
            //        iseighthour = 1;
            //    if ((item.arrivetime.Value - item.repairtime.Value).TotalHours > 8 && (item.arrivetime.Value - item.repairtime.Value).TotalHours <= 24)
            //        istfourhour = 1;
            //    if ((item.arrivetime.Value - item.repairtime.Value).TotalHours > 24)
            //        istfouruphour = 1;
            //    #endregion
            //    var model = new Wo_Repair_BaseRepaireTimeDto();
            //    model.id = item.id;
            //    model.wocode = item.wocode;
            //    //model.wostate = item.wostate;
            //    model.istwohour = istwohour;
            //    model.isfourhour = isfourhour;
            //    model.iseighthour = iseighthour;
            //    model.istfourhour = istfourhour;
            //    model.istfouruphour = istfouruphour;
            //    modellist.Add(model);
            //}

            var modellist = querylist.Select(p => {
                int istwohour = 0, isfourhour = 0, iseighthour = 0, istfourhour = 0, istfouruphour = 0;
                //2小时内
                if ((p.arrivetime.Value - p.repairtime.Value).TotalHours <= 2)
                    istwohour = 1;
                if ((p.arrivetime.Value - p.repairtime.Value).TotalHours > 2 && (p.arrivetime.Value - p.repairtime.Value).TotalHours <= 4)
                    isfourhour = 1;
                if ((p.arrivetime.Value - p.repairtime.Value).TotalHours > 4 && (p.arrivetime.Value - p.repairtime.Value).TotalHours <= 8)
                    iseighthour = 1;
                if ((p.arrivetime.Value - p.repairtime.Value).TotalHours > 8 && (p.arrivetime.Value - p.repairtime.Value).TotalHours <= 24)
                    istfourhour = 1;
                if ((p.arrivetime.Value - p.repairtime.Value).TotalHours > 24)
                    istfouruphour = 1;
                return new {
                    p.id,
                    p.wocode,
                    p.repairtime,
                    p.repairreplace,
                    istwohour,
                    isfourhour,
                    iseighthour,
                    istfourhour,
                    istfouruphour
                };
            });
            recordCount = modellist.Count();
            var list = modellist.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var obj = new
            {
                list,
                twohournum = twoHourNum,        //2小时内
                fourhournum = fourHourNum,      //4小时内
                eighthournum = eightHourNum,    //8小时内
                tfourhournum = tfourHourNum,    //24小时内
                tfourupHournum = tfourUpHourNum //24小时以上
            };
            return obj;
        }

        /// <summary>
        /// 耗材统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 耗材统计详情）
        /// </summary>
        /// <param name="sysnameid">报修类型 日常类、设备类</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetMaterialListAndStatisticsByPage(string projectid, string start, string end,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                join pro in _collection.AsQueryable() on repair.projectid equals pro.id into proDefa
                join equ in _collection_eqp_equipment_info.AsQueryable() on repair.equipmentid equals equ.id into equDefa
                where repair.isdelete == 0 && (repair.ismaterials == 1 || repair.islosematerials == 1)
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.wocode,
                    repair.projectid,
                    projectname = proDefa != null && proDefa.Count() > 0 ? proDefa.First().project_name : null,
                    repair.equipmentid,
                    equipmentname = equDefa != null && equDefa.Count() > 0 ? equDefa.First().equipment_name : null,
                    repair.materials,
                    repair.losematerials,
                    repair.createtime
                };
            #region 查询条件
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

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

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

            return list;
        }

        /// <summary>
        /// 满意度统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 满意度统计详情）
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetRepairEvaluateListAndStatisticsByPage(string projectid, string start, string end,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                where repair.isdelete == 0 && (repair.wostate == (int)EnumWorkOrderState.evaluate|| repair.wostate == (int)EnumWorkOrderState.deal)
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.projectid,
                    repair.createtime,
                    repair.wocode,
                    repair.score,
                    issatisfied = (repair.wostate == (int)EnumWorkOrderState.evaluate && repair.score >= 3) ? 1 : 0,
                    repair.wostate
                };
            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //满意
            int satisfied = query.Where(x => x.issatisfied == 1).Count();
            //不满意
            int nosatisfied = query.Where(x => x.issatisfied == 0).Count();

            recordCount = query.Count();
            var list = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var obj = new
            {
                list,
                satisfied,
                nosatisfied
            };
            return obj;
        }

        /// <summary>
        /// 满意度统计详情 - 列表/统计 （设备运维 -> 设备维修（饼） -> 满意度统计详情） - 项目主管
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public object GetUsersEvaluateListAndStatisticsByPage(string projectid, string start, string end,
            int pageIndex, int pageSize, out int recordCount, UserAccountInfoModel userinfo)
        {
            var userlist = from p in _collection_sys_user_account.AsQueryable()
                           join r in _collection_role_info.AsQueryable() on p.role_id equals r.id into roleinfo
                           where p.delete_flag == false
                           select new
                           {
                               p.usercode,
                               p.username,
                               projectid = p.projectlist != null && p.projectlist.Count() > 0 ? p.projectlist.First() : null,
                               roleid = p.role_id,
                               rolecode = roleinfo != null && roleinfo.Count() > 0 ? roleinfo.First().role_code : null
                           };
            var wxlist = userlist.Where(p => p.rolecode == "YWYG");

            //关联查询
            var query =
                from repair in _collection_wo_repair_base.AsQueryable()
                where repair.isdelete == 0 && (repair.wostate == (int)EnumWorkOrderState.evaluate || repair.wostate == (int)EnumWorkOrderState.deal)
                orderby repair.createtime descending
                select new
                {
                    repair.id,
                    repair.projectid,
                    repair.createtime,
                    repair.wocode,
                    repair.dealuser,
                    repair.score,
                    issatisfied = (repair.wostate == (int)EnumWorkOrderState.evaluate && repair.score >= 3) ? 1 : 0,
                    repair.wostate
                };

            if (!string.IsNullOrEmpty(projectid))
            {
                query = query.Where(p => p.projectid == projectid);
                userlist = userlist.Where(p => p.projectid == projectid);
            }
            if (!string.IsNullOrEmpty(start))
            {
                query = query.Where(p => p.createtime >= DateTime.Parse(start));
            }
            if (!string.IsNullOrEmpty(end))
            {
                query = query.Where(p => p.createtime <= DateTime.Parse(end));
            }

            if (userinfo.isallproject == 0)
            {
                query = query.Where(it => userinfo.projectlist.Contains(it.projectid));
                userlist = userlist.Where(it => userinfo.projectlist.Contains(it.projectid));
            }

            //满意
            int allsatisfied = query.Where(x => x.issatisfied == 1).Count();
            //不满意
            int allnosatisfied = query.Where(x => x.issatisfied == 0).Count();

            recordCount = wxlist.Count();
            var list = wxlist.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var modellist = list.Select(p =>
            {
                var userrepairs = query.Where(q => q.dealuser.Contains(p.usercode));

                int satisfied = userrepairs.Count(q => q.issatisfied == 1), nosatisfied = userrepairs.Count(q => q.issatisfied == 0);    //评价
                return new
                {
                    p.usercode,
                    satisfied,
                    nosatisfied
                };
            });

            var obj = new
            {
                list = modellist,
                allsatisfied,
                allnosatisfied
            };
            return obj;
        }

        #endregion
        
    }
}