using Hotline.CallCenter.Calls;
using Hotline.Orders;
using Hotline.Permissions;
using Hotline.Settings;
using Hotline.Settings.CommonOpinions;
using Hotline.Share.Dtos.Settings;
using Hotline.Share.Enums.FlowEngine;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using SqlSugar;
using System.Reflection.Metadata;
using Hotline.Application.CallCenter;
using Hotline.CallCenter.Configs;
using Hotline.FlowEngine.Workflows;
using Hotline.Settings.TimeLimits;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Enums.Order;
using Microsoft.Extensions.Options;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;
using Hotline.Configurations;
using Hotline.Share.Dtos.Order;
using System.Runtime.InteropServices;
using Lucene.Net.Util;
using NPOI.Util;
using XF.Domain.Entities;
using Hotline.SeedData;
using Hotline.Authentications;

namespace Hotline.Api.Controllers
{
	/// <summary>
	/// 常用意见接口
	/// </summary>
	public class CommonPController : BaseController
	{
		private readonly ISystemCommonOpinionDomainService _commonOpinionDomainService;
		private readonly ISystemAreaDomainService _systemAreaDomainService;
		private readonly IMapper _mapper;
		private readonly ISessionContext _sessionContext;
		// private readonly IRepository<TrCallRecord> _trCallRecordRepository;
		private readonly IOrderRepository _orderRepository;
		private readonly IOrderDelayRepository _orderDelayRepository;
		private readonly ITimeLimitDomainService _timeLimitDomainService;
		private readonly IOrderScreenRepository _orderScreenRepository;
		private readonly IRepository<OrderVisitDetail> _orderVisitedDetailRepository;
		private readonly ICallApplication _callApplication;
		private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
		private readonly IOrderDomainService _orderDomainService;
		private readonly IRepository<OrderVisit> _orderVisitRepository;
		private readonly IRepository<OrderSendBackAudit> _orderSendBackAuditRepository;

		public CommonPController(
			ISystemCommonOpinionDomainService commonOpinionDomainService,
			ISystemAreaDomainService systemAreaDomainService,
			ISessionContext sessionContext,
			// IRepository<TrCallRecord> trCallRecordRepository,
			IOrderRepository orderRepository,
			IMapper mapper,
			IOrderDelayRepository orderDelayRepository,
			ITimeLimitDomainService timeLimitDomainService,
			IOrderScreenRepository orderScreenRepository,
			IRepository<OrderVisitDetail> orderVisitedDetailRepository,
			ICallApplication callApplication,
			IOptionsSnapshot<AppConfiguration> appOptions,
			IOrderDomainService orderDomainService,
			IRepository<OrderVisit> orderVisitRepository,
			IRepository<OrderSendBackAudit> orderSendBackAuditRepository)
		{
			_commonOpinionDomainService = commonOpinionDomainService;
			_systemAreaDomainService = systemAreaDomainService;
			_mapper = mapper;
			_sessionContext = sessionContext;
			// _trCallRecordRepository = trCallRecordRepository;
			_orderRepository = orderRepository;
			_orderDelayRepository = orderDelayRepository;
			_timeLimitDomainService = timeLimitDomainService;
			_orderScreenRepository = orderScreenRepository;
			_orderVisitedDetailRepository = orderVisitedDetailRepository;
			_callApplication = callApplication;
			_appOptions = appOptions;
			_orderDomainService = orderDomainService;
			_orderVisitRepository = orderVisitRepository;
			_orderSendBackAuditRepository = orderSendBackAuditRepository;
		}


		#region 省市区

		/// <summary>
		/// 获取省市区树形
		/// </summary>
		/// <returns></returns>
		[HttpGet("tree-area")]
		[Obsolete("请调用sys/area/tree")]
		public async Task<List<SystemArea>> GetAearTree()
		{
			return await _systemAreaDomainService.GetAreaTree(_appOptions.Value.IsZiGong ? 6 : 0);
		}

		#endregion

        /// <summary>
        /// 首页基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("home_data")]
        public async Task<Object> GetHomeData()
        {
            var tadayTime = DateTime.Now.ToString("yyyy-MM-dd");
            //中心
            if (_sessionContext.OrgIsCenter)
            {
                var orderQuery = _orderRepository.Queryable(false, false, false)
                    .Includes(o => o.Workflow, w => w.Steps);
                //今日来电
                //  var tadayCalls = await _trCallRecordRepository.Queryable()
                //      .Where(x => x.CallDirection == Share.Enums.CallCenter.ECallDirection.In && tadayTime.Equals(x.CreatedTime.ToString("yyyy-MM-dd"))).ToListAsync();
                //  var callNum = tadayCalls.Count();
                //  var validCallNum = tadayCalls.Where(x => x.Duration > 0 || x.QueueTims > 0 || x.RingTimes > 0).Count();
                //  //今日接通率
                //  var answeredNum = tadayCalls.Where(x => x.Duration > 0).Count();
                // var answeredRate = validCallNum > 0 ? Math.Round((double.Parse(answeredNum.ToString()) / double.Parse(validCallNum.ToString())) * 100, 2) + "%" : "-";

                int callNum = 0, validCallNum = 0, answeredNum = 0;
                var answeredRate = string.Empty;
                var today = DateTime.Today.Date;
                if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.TianRun)
                {
                    var calls = await _callApplication.QueryTianrunCallsAsync(
                        direction: ECallDirection.In,
                        callStartTimeStart: today,
                        callStartTimeEnd: today.AddDays(1).AddSeconds(-1),
                        cancellationToken: HttpContext.RequestAborted);
                    callNum = calls.Count();
                    validCallNum = calls.Where(x => x.Duration > 0 || x.QueueTims > 0 || x.RingTimes > 0).Count();
                    //今日接通率
                    answeredNum = calls.Where(x => x.Duration > 0).Count();
                    answeredRate = validCallNum > 0
                        ? Math.Round((double.Parse(answeredNum.ToString()) / double.Parse(validCallNum.ToString())) * 100, 2) + "%"
                        : "-";
                }
                else if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.XingTang)
                {
                    var calls = await _callApplication.QueryCallsAsync(
                        callStartTimeStart: today,
                        callStartTimeEnd: today.AddDays(1).AddSeconds(-1),
                        cancellationToken: HttpContext.RequestAborted);
                    callNum = calls.Count();
                    validCallNum = calls.Where(x => x.Duration > 0 || x.WaitDuration > 0 || x.RingDuration > 0).Count();
                    //今日接通率
                    answeredNum = calls.Where(x => x.Duration > 0).Count();
                    answeredRate = validCallNum > 0
                        ? Math.Round((double.Parse(answeredNum.ToString()) / double.Parse(validCallNum.ToString())) * 100, 2) + "%"
                        : "-";
                }

                //今日受理工单
                var tadayOrders = await orderQuery
                    .Where(o => tadayTime.Equals(o.CreationTime.ToString("yyyy-MM-dd"))).ToListAsync();
                var orderNum = tadayOrders.Count();
                var directlyNum = tadayOrders.Where(o => o.ProcessType == Share.Enums.Order.EProcessType.Zhiban).Count();
                return new
                {
                    CallNum = callNum, ValidCallNum = validCallNum, AnsweredNum = answeredNum, AnsweredRate = answeredRate, OrderNum = orderNum,
                    DirectlyNum = directlyNum
                };
            }

            //部门
            //今日待办 tasksOkNum
            //var time = DateTime.Parse(tadayTime);
            //工单
            var order = await _orderRepository.Queryable(hasHandled: false)
	            .Includes(d => d.OrderSpecials)
	            .Where(d => d.Status != EOrderStatus.WaitForAccept && d.Status != EOrderStatus.BackToUnAccept && d.Status != EOrderStatus.SpecialToUnAccept && d.Status !=  EOrderStatus.HandOverToUnAccept)
				.Where(d => d.Source < ESource.MLSQ || d.Source > ESource.WZSC)
	            .Where(d => d.Status != EOrderStatus.BackToProvince && d.Status < EOrderStatus.Filed)
	            .Where(d => d.OrderSpecials.Any() == false || d.OrderSpecials.Any(s => s.State > 0))
				.GroupBy(o => new { o.Id,o.Status })
                .Select(o => new
                {
                    aboutExpire = SqlFunc.AggregateSum(SqlFunc.IIF(DateTime.Now > o.NearlyExpiredTime!.Value && DateTime.Now < o.ExpiredTime!.Value,
                        1, 0)),
                    havExpired = SqlFunc.AggregateSum(SqlFunc.IIF(DateTime.Now > o.ExpiredTime!.Value , 1, 0)),
                    countersignHandle = SqlFunc.AggregateSum(SqlFunc.IIF(o.Status == EOrderStatus.Countersigning, 1, 0)),
                }).ToListAsync();
            var aboutExpire = order?.Sum(x=>x.aboutExpire) ?? 0;
            var havExpired = order?.Sum(x=>x.havExpired) ?? 0;
            var countersignHandle = order?.Sum(x=> x.countersignHandle) ?? 0;
            //延期
            var delay = await _orderDelayRepository.Queryable(hasHandled: false)
                .Where(d => d.DelayState == EDelayState.Examining).CountAsync();
            //甄别
            var screenAudit = await _orderScreenRepository.Queryable(hasHandled: false)
                .Where(x=>x.CreationTime < DateTime.Now && x.CreationTime > DateTime.Now.AddMonths(-2))
                .Where(x => (x.Status == EScreenStatus.Apply || x.Status == EScreenStatus.Approval || (x.Status == EScreenStatus.SendBack && x.SendBackApply == false)))
                //.Where(d => d.Status == EScreenStatus.Apply)
                .CountAsync();
            //var workTime = _timeLimitDomainService.CalcWorkTimeReduce(DateTime.Now, 5);
            var screenHandle = await _orderVisitedDetailRepository.Queryable(false, true)
                .Includes(x => x.OrderVisit)
                .Includes(x => x.OrderScreens)
				.Where(x => x.OrderScreens.Any(s => s.Status == EScreenStatus.SendBack && s.SendBackApply == true) || x.OrderScreens.Any(s => (s.Status != EScreenStatus.SendBack && s.SendBackApply != true)) == false)
                .Where(x => x.OrderVisit.VisitState == EVisitState.Visited && x.OrderVisit.IsCanHandle)
                .Where(x=> x.VisitTarget == EVisitTarget.Org && x.VisitOrgCode == _sessionContext.OrgId && (
                    SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2" ||
                    SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "1" || SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2")).CountAsync();
            return new
            {
                AboutExpire = aboutExpire, HavExpired = havExpired, CountersignHandle = countersignHandle, ScreenAudit = screenAudit, Delay = delay,
                ScreenHandle = screenHandle
            };
        }

		/// <summary>
		/// 首页基础数据
		/// </summary>
		/// <returns></returns>
		[HttpGet("home_data_new")]
		public async Task<Object> GetHomeDataNew()
		{
			var allList = new List<HomeOrderDto>();
			var allNum = 0;
			var isAdmin = _orderDomainService.IsCheckAdmin();
			var IsCenter = _sessionContext.OrgIsCenter;
			if (_sessionContext.OrgIsCenter)
			{
				//待办
				var waitedDataList = await _orderRepository
					.Queryable(hasHandledStep: false, isAdmin: isAdmin)
					.Includes(d => d.OrderSpecials)
					.WhereIF(_appOptions.Value.IsZiGong, d => SqlFunc.Subqueryable<OrderDelay>().Where(od => od.OrderId == d.Id && od.DelayState == EDelayState.Examining).NotAny())
					.WhereIF(_appOptions.Value.IsZiGong, d => SqlFunc.Subqueryable<OrderSendBackAudit>().Where(osba => osba.OrderId == d.Id && osba.State == ESendBackAuditState.Apply).NotAny())
					.Where(d => d.Status != EOrderStatus.WaitForAccept && d.Status != EOrderStatus.BackToUnAccept && d.Status != EOrderStatus.SpecialToUnAccept && d.Status != EOrderStatus.HandOverToUnAccept)
					.Where(d => d.Source < ESource.MLSQ || d.Source > ESource.WZSC)
					.Where(d => d.Status != EOrderStatus.BackToProvince && d.Status < EOrderStatus.Filed)
					.Where(d => d.OrderSpecials.Any() == false || d.OrderSpecials.Any(s => s.State > 0))
					.OrderByDescending(d => new { d.IsUrgent, d.StartTime })
					.Select(d => new HomeOrderDto
					{
						No = d.No,
						OrderId = d.Id,
						Title = d.Title,
						AcceptType = d.AcceptType,
						HotspotName = d.HotspotName,
						Type = "Waited",
						Time = d.ExpiredTime,
						Status = d.Status,
						ActualHandleTime = d.ActualHandleTime,
						NearlyExpiredTime = d.NearlyExpiredTime,
						CounterSignType = d.CounterSignType
					})
					.ToListAsync();
				var waitedList = waitedDataList.Where(x => x.Status != EOrderStatus.Countersigning && 
				x.Time > DateTime.Now && x.Status < EOrderStatus.Filed &&  DateTime.Now < x.NearlyExpiredTime 
				).OrderBy(x=> x.Time).Take(40).ToList();
				waitedList = waitedList.Count > 0 ? waitedList.Copy() : waitedList;
				//allNum += waitedList.Count > 40 ? 40 : waitedList.Count;
				//allList.AddRange(waitedList);
				// 已超期
				var waitedExpiredDataList = waitedDataList.Where(x => (x.Time < DateTime.Now && x.Status < EOrderStatus.Filed) ||
				                                                      (x.Time < x.ActualHandleTime && x.Status >= EOrderStatus.Filed)).OrderBy(x=>x.Time).Take(40).ToList();
				waitedExpiredDataList = waitedExpiredDataList.Count > 0 ? waitedExpiredDataList.Copy() : waitedExpiredDataList;
				waitedExpiredDataList.ForEach(x => x.Type = "WaitedExpired");
				//allNum += waitedExpiredDataList.Count;
				//allList.AddRange(waitedExpiredDataList);
				//回访待办
				var visitDataList = await _orderVisitRepository.Queryable()
					.Includes(d => d.Order)
					.Where(d => d.VisitState == EVisitState.WaitForVisit || d.VisitState == EVisitState.NoSatisfiedWaitForVisit)
					.Where(d => d.EmployeeId == _sessionContext.RequiredUserId)
					.OrderByDescending(x => x.PublishTime)
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "Visit",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					})
					.Take(40)
					.ToListAsync();
				//allNum += visitDataList.Count;
				//allList.AddRange(visitDataList);
				//会签待办
				var signDataList = waitedDataList.Where(x => x.Status == EOrderStatus.Countersigning).OrderBy(x => x.Time).Take(40).ToList();
				signDataList = signDataList.Count > 0 ? signDataList.Copy() : signDataList;
				signDataList.ForEach(x => x.Type = "Sign");
				//allNum += signDataList.Count;
				//allList.AddRange(signDataList);
				//延期待审批
				var delayDataList = await _orderDelayRepository.Queryable(hasHandledStep: false, isAdmin: isAdmin)
					.Includes(d => d.Order)
					.Where(d => d.DelayState == EDelayState.Examining)
					.OrderByDescending(d => d.ApplyDelayTime)
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "Delay",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					}).Take(40)
					.ToListAsync();
				//allNum += delayDataList.Count;
				//allList.AddRange(delayDataList);
				//部门即将超期
				var nearlyExpiredDataList = await _orderRepository.Queryable(canView: !IsCenter)
					.Includes(d => d.OrderDelays)
					.Where(d => SqlFunc.Subqueryable<WorkflowStep>()
						.Where(step => step.ExternalId == d.Id && step.Status != EWorkflowStepStatus.Handled &&
						               ((step.FlowAssignType == EFlowAssignType.User && !string.IsNullOrEmpty(step.HandlerId) && step.HandlerId == _sessionContext.RequiredUserId) ||
						                (step.FlowAssignType == EFlowAssignType.Org && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId) ||
						                (step.FlowAssignType == EFlowAssignType.Role && !string.IsNullOrEmpty(step.RoleId) && _sessionContext.Roles.Contains(step.RoleId))))
						.Any())
					.Where(d => d.Status < EOrderStatus.Filed && DateTime.Now > d.NearlyExpiredTime && DateTime.Now < d.ExpiredTime)
					.OrderBy(d => d.NearlyExpiredTime)
					.Select(d => new HomeOrderDto
					{
						No = d.No,
						OrderId = d.Id,
						Title = d.Title,
						AcceptType = d.AcceptType,
						HotspotName = d.HotspotName,
						Type = "NearlyExpired",
						Time = d.ExpiredTime,
						Status = d.Status,
						CounterSignType = d.CounterSignType
					}).Take(40)
					.ToListAsync();
				//allNum += nearlyExpiredDataList.Count;
				//allList.AddRange(nearlyExpiredDataList);
				//甄别待审批
				var screenDataList = await _orderScreenRepository.Queryable(hasHandledStep: false, isAdmin: isAdmin)
					.Includes(d => d.Order)
					.Includes(d => d.ScreenDetails.Where(sd => sd.AuditUserId == _sessionContext.UserId).OrderByDescending(sd => sd.AuditTime).Take(1).ToList())
					.Where(d => (d.Status == EScreenStatus.Apply || d.Status == EScreenStatus.Approval || (d.Status == EScreenStatus.SendBack && d.SendBackApply == false)))
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "Screen",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					}).Take(40)
					.ToListAsync();
				//allNum += screenDataList.Count;
				//allList.AddRange(screenDataList);
				//退回待审批
				var sendBackAuditDataList = await _orderSendBackAuditRepository.Queryable()
					.Includes(d => d.Order)
					.Where(d => d.State == ESendBackAuditState.Apply)
					.WhereIF(_sessionContext.Roles.Contains("role_sysadmin") == false, x => x.SendBackOrgId == _sessionContext.OrgId) // 123 系统管理员;
					.OrderByDescending(d => d.CreationTime)
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "SendBackAudit",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					}).Take(40)
					.ToListAsync();
				//allNum += sendBackAuditDataList.Count;
				//allList.AddRange(sendBackAuditDataList);
				return new
				{
					//AllNum = allNum,
					//AllList = allList,
					WaitedNum = waitedList.Count > 40 ? 40 : waitedList.Count,
					WaitedList = waitedList.Take(40).ToList(),
					WaitedExpiredNum = waitedExpiredDataList.Count,
					WaitedExpiredList = waitedExpiredDataList,
					VisitListNum = visitDataList.Count,
					VisitList = visitDataList,
					SignDataNum = signDataList.Count,
					SignDataList = signDataList,
					DelayNum = delayDataList.Count,
					DelayDataList = delayDataList,
					NearlyExpiredNum = nearlyExpiredDataList.Count,
					NearlyExpiredList = nearlyExpiredDataList,
					ScreenNum = screenDataList.Count,
					ScreenList = screenDataList,
					SendBackAuditNum = sendBackAuditDataList.Count,
					SendBackAuditList = sendBackAuditDataList
				};
			}
			else
			{
				//待办
				var waitedDataList = await _orderRepository
					.Queryable(hasHandledStep: false, isAdmin: isAdmin)
					.Includes(d => d.OrderSpecials)
					.Where(d => SqlFunc.Subqueryable<OrderDelay>().Where(od => od.OrderId == d.Id && od.DelayState == EDelayState.Examining).NotAny())
					.Where(d => SqlFunc.Subqueryable<OrderSendBackAudit>().Where(osba => osba.OrderId == d.Id && osba.State == ESendBackAuditState.Apply).NotAny())
					.Where(d => d.Status != EOrderStatus.WaitForAccept && d.Status != EOrderStatus.BackToUnAccept && d.Status != EOrderStatus.SpecialToUnAccept && d.Status != EOrderStatus.HandOverToUnAccept)
					.Where(d => d.Source < ESource.MLSQ || d.Source > ESource.WZSC)
					.Where(d => d.Status != EOrderStatus.BackToProvince && d.Status < EOrderStatus.Filed)
					.Where(d => d.OrderSpecials.Any() == false || d.OrderSpecials.Any(s => s.State > 0))
					.OrderByDescending(d => new { d.IsUrgent, d.StartTime })
					.Select(d => new HomeOrderDto
					{
						No = d.No,
						OrderId = d.Id,
						Title = d.Title,
						AcceptType = d.AcceptType,
						HotspotName = d.HotspotName,
						Type = "Waited",
						Time = d.ExpiredTime,
						Status = d.Status,
						ActualHandleTime = d.ActualHandleTime,
						NearlyExpiredTime = d.NearlyExpiredTime,
						CounterSignType = d.CounterSignType
					})
					.ToListAsync();
				var waitedList = waitedDataList.Where(x => x.Status != EOrderStatus.Countersigning &&
				 x.Time > DateTime.Now && x.Status < EOrderStatus.Filed && DateTime.Now < x.NearlyExpiredTime
				).OrderBy(x=>x.Time).ToList();
				waitedList = waitedList.Count > 0 ? waitedList.Copy() : waitedList;
				//allNum += waitedList.Count > 40 ? 40 : waitedList.Count;
				//allList.AddRange(waitedList);
				//已超期
				var waitedExpiredDataList = waitedDataList.Where(x => (x.Time < DateTime.Now && x.Status < EOrderStatus.Filed) ||
				                                                      (x.Time < x.ActualHandleTime && x.Status >= EOrderStatus.Filed))
														  .OrderBy(x=> x.Time).ToList();
				waitedExpiredDataList = waitedExpiredDataList.Count > 0 ? waitedExpiredDataList.Copy() : waitedExpiredDataList;
				waitedExpiredDataList.ForEach(x => x.Type = "WaitedExpired");
				//allNum += waitedExpiredDataList.Count;
				//allList.AddRange(waitedExpiredDataList);
				//会签待办
				var signDataList = waitedDataList.Where(x => x.Status == EOrderStatus.Countersigning).OrderBy(x => x.Time).ToList();
				signDataList = signDataList.Count > 0 ? signDataList.Copy() : signDataList;
				signDataList.ForEach(x => x.Type = "Sign");
				
				//allNum += signDataList.Count;
				//allList.AddRange(signDataList);
				//甄别待审批
				var screenDataList = await _orderScreenRepository.Queryable(hasHandledStep: false, isAdmin: isAdmin)
					.Includes(d => d.Order)
					.Includes(d => d.ScreenDetails.Where(sd => sd.AuditUserId == _sessionContext.UserId).OrderByDescending(sd => sd.AuditTime).Take(1).ToList())
					.Where(d => (d.Status == EScreenStatus.Apply || d.Status == EScreenStatus.Approval || (d.Status == EScreenStatus.SendBack && d.SendBackApply == false)))
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "Screen",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					})
					.ToListAsync();
				//allNum += screenDataList.Count;
				//allList.AddRange(screenDataList);
				//延期待审批
				var delayDataList = await _orderDelayRepository.Queryable(hasHandledStep: false, isAdmin: isAdmin)
					.Includes(d => d.Order)
					.Where(d => d.DelayState == EDelayState.Examining)
					.OrderByDescending(d => d.ApplyDelayTime)
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "Delay",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					})
					.ToListAsync();
				//allNum += delayDataList.Count;
				//allList.AddRange(delayDataList);
				//甄别待申请
				var screenApplyDataList = await _orderVisitedDetailRepository.Queryable(false, true)
				.Includes(x => x.OrderVisit)
				.Includes(x => x.OrderVisit, y => y.Order)
				.Includes(x => x.OrderVisit, y => y.Employee)
				.Includes(x => x.OrderScreens)
				.Where(x => x.OrderScreens.Any(s => s.Status == EScreenStatus.SendBack && s.ScreenType ==  EOrderScreenType.Org && s.SendBackApply == true) || x.OrderScreens.Any() == false)
                .Where(x => x.OrderVisit.Order.ReceiveProvinceNo.StartsWith("ZGZFW") == false || string.IsNullOrEmpty(x.OrderVisit.Order.ReceiveProvinceNo))
                .Where(x => x.OrderVisit.VisitState == EVisitState.Visited && x.OrderVisit.IsCanHandle)
				.Where(x => x.VisitTarget == EVisitTarget.Org && x.VisitOrgCode == _sessionContext.OrgId && (
					SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1" ||
					SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2" ||
					SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "1" ||
					SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2"
				))
				.OrderByDescending(x => x.CreationTime)
				.Select(x => new HomeOrderDto
				{
					No = x.OrderVisit.Order.No,
					OrderId = x.OrderVisit.Order.Id,
					Title = x.OrderVisit.Order.Title,
					AcceptType = x.OrderVisit.Order.AcceptType,
					HotspotName = x.OrderVisit.Order.HotspotName,
					Type = "ScreenApply",
					Time = x.OrderVisit.Order.ExpiredTime,
					Status = x.OrderVisit.Order.Status,
					CounterSignType = x.OrderVisit.Order.CounterSignType
				}).ToListAsync();
				//allNum += screenApplyDataList.Count;
				//allList.AddRange(screenApplyDataList);
				//退回待审批
				var sendBackAuditDataList = await _orderSendBackAuditRepository.Queryable()
					.Includes(d => d.Order)
					.Where(d => d.State == ESendBackAuditState.Apply)
					.WhereIF(_sessionContext.Roles.Contains("role_sysadmin") == false, x => x.SendBackOrgId == _sessionContext.OrgId) // 123 系统管理员;
					.OrderByDescending(d => d.CreationTime)
					.Select(d => new HomeOrderDto
					{
						No = d.Order.No,
						OrderId = d.Order.Id,
						Title = d.Order.Title,
						AcceptType = d.Order.AcceptType,
						HotspotName = d.Order.HotspotName,
						Type = "SendBackAudit",
						Time = d.Order.ExpiredTime,
						Status = d.Order.Status,
						CounterSignType = d.Order.CounterSignType
					})
					.ToListAsync();
				//allNum += sendBackAuditDataList.Count;
				//allList.AddRange(sendBackAuditDataList);
				//部门即将超期
				var nearlyExpiredDataList = await _orderRepository.Queryable(canView: !IsCenter)
					.Includes(d => d.OrderDelays)
					.Where(d => SqlFunc.Subqueryable<WorkflowStep>()
						.Where(step => step.ExternalId == d.Id && step.Status != EWorkflowStepStatus.Handled &&
						               ((step.FlowAssignType == EFlowAssignType.User && !string.IsNullOrEmpty(step.HandlerId) && step.HandlerId == _sessionContext.RequiredUserId) ||
						                (step.FlowAssignType == EFlowAssignType.Org && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId) ||
						                (step.FlowAssignType == EFlowAssignType.Role && !string.IsNullOrEmpty(step.RoleId) && _sessionContext.Roles.Contains(step.RoleId))))
						.Any())
					.Where(d => d.Status < EOrderStatus.Filed && DateTime.Now > d.NearlyExpiredTime && DateTime.Now < d.ExpiredTime)
					.OrderBy(d => d.NearlyExpiredTime)
					.Select(d => new HomeOrderDto
					{
						No = d.No,
						OrderId = d.Id,
						Title = d.Title,
						AcceptType = d.AcceptType,
						HotspotName = d.HotspotName,
						Type = "NearlyExpired",
						Time = d.ExpiredTime,
						Status = d.Status,
						CounterSignType = d.CounterSignType
					})
					.ToListAsync();
				return new
				{
					//AllNum = allNum,
					//AllList = allList,
					WaitedNum = waitedList.Count,
					WaitedList = waitedList.ToList(),
					WaitedExpiredNum = waitedExpiredDataList.Count,
					WaitedExpiredList = waitedExpiredDataList,
					SignDataNum = signDataList.Count,
					SignDataList = signDataList,
					ScreenNum = screenDataList.Count,
					ScreenList = screenDataList,
					DelayNum = delayDataList.Count,
					DelayDataList = delayDataList,
					ScreenApplyNum = screenApplyDataList.Count,
					ScreenApplyList = screenApplyDataList,
					SendBackAuditNum = sendBackAuditDataList.Count,
					SendBackAuditList = sendBackAuditDataList,
					NearlyExpiredNum = nearlyExpiredDataList.Count,
					NearlyExpiredList = nearlyExpiredDataList,
				};
			}
		}


		/// <summary>
		/// 省件退回中心弹窗提示  type  0  工单坐席待办 1 工单待办   需求变更 接口作废
		/// </summary>
		/// <returns></returns>
		[HttpGet("home_province_sendback")]
		public async Task<object> GetProvinceSendBack() {

			//if (_sessionContext.RequiredOrgId == OrgSeedData.CenterId)
			//{
			//	var msg = "工单编码为{0}的工单，已被退回，请及时处理！";
			//	var orders = await _orderSendBackAuditRepository.Queryable().Includes(x => x.Order)
			//		.Where(x => x.Order.IsProvince)
			//		.Where(x => x.ApplyOrgId.Length == 6 && x.SendBackOrgId == OrgSeedData.CenterId && x.State == ESendBackAuditState.End)
			//		.Where(x => SqlFunc.Subqueryable<WorkflowStep>()
			//		.Where(step => step.ExternalId == x.OrderId && (
			//					   (step.FlowAssignType == EFlowAssignType.User && step.HandlerId == _sessionContext.RequiredUserId)
			//					   || (step.FlowAssignType == EFlowAssignType.Role && _sessionContext.Roles.Contains(step.RoleId))
			//					   )).Any()
			//		).OrderByDescending(x=>x.AuditTime).ToListAsync();
			//	if (orders != null && orders.Any())
			//	{
			//		var order = orders.FirstOrDefault();
			//		msg = string.Format(msg, order.Order.No);
			//		var type = order.Order.Status < EOrderStatus.Handling ? 0 : 1;
			//		return new { count = orders.Count, msg = msg, type = type };
			//	}
			//}
			return new { count = 0, msg = string.Empty, type = -1 };
		}
	}
}