using DocumentFormat.OpenXml.Drawing.Diagrams;
using DocumentFormat.OpenXml.Office.CustomUI;
using DocumentFormat.OpenXml.Office2010.CustomUI;
using DocumentFormat.OpenXml.Spreadsheet;
using DotNetCore.CAP;
using FluentValidation;
using Hotline.Application.FlowEngine;
using Hotline.Application.OrderApp.OrderVisitApp;
using Hotline.Application.Quality;
using Hotline.Article;
using Hotline.Authentications;
using Hotline.Caching.Interfaces;
using Hotline.Configurations;
using Hotline.File;
using Hotline.FlowEngine.Definitions;
using Hotline.FlowEngine.Notifications;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.Identity.Roles;
using Hotline.KnowledgeBase;
using Hotline.Orders;
using Hotline.OrderTranspond;
using Hotline.Push.Notifies;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Repository.SqlSugar.Ts;
using Hotline.Schedulings;
using Hotline.SeedData;
using Hotline.Settings;
using Hotline.Settings.Hotspots;
using Hotline.Settings.TimeLimitDomain;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.File;
using Hotline.Share.Dtos.FlowEngine;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Order.Publish;
using Hotline.Share.Dtos.Push;
using Hotline.Share.Dtos.Settings;
using Hotline.Share.Dtos.Users;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Push;
using Hotline.Share.Enums.Quality;
using Hotline.Share.Enums.Settings;
using Hotline.Share.Mq;
using Hotline.Share.Requests;
using Hotline.Share.Tools;
using Hotline.Snapshot.IRepository;
using Hotline.Statistics;
using Hotline.Tools;
using Hotline.Users;
using Hotline.Validators.FlowEngine;
using Mapster;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using NPOI.SS.Formula.Functions;
using PanGu;
using SqlSugar;
using System.Data;
using System.Dynamic;
using System.Threading;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;
using WordInfo = PanGu.WordInfo;

namespace Hotline.Application.OrderApp;

public class OrderApplication : IOrderApplication, IScopeDependency
{
    private readonly IOrderSnapshotRepository _orderSnapshotRepository;
    private readonly IMediator _mediator;
    private readonly IRepository<TranspondCityRawData> _transpondCityRawDataRepository;
    private readonly ISessionContextProvider _sessionContextProvider;
    private readonly ISystemDicDataCacheManager _sysDicDataCacheManager;
    private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
    private readonly IRepository<OrderVisitDetail> _orderVisitedDetailRepository;
    private readonly IOrderDomainService _orderDomainService;
    private readonly IWorkflowDomainService _workflowDomainService;
    private readonly ISessionContext _sessionContext;
    private readonly IOrderRepository _orderRepository;

    //private readonly ITimeLimitDomainService _timeLimitDomainService;
    private readonly IMapper _mapper;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;
    private readonly IRepository<OrderWord> _orderWrodRepository;
    private readonly IRepositoryTextSearch<OrderTs> _repositoryts;
    private readonly IFileRepository _fileRepository;
    private readonly IRepository<OrderVisit> _orderVisitRepository;
    private readonly IRepository<OrderVisitDetail> _orderVisitDetailRepository;
    private readonly IRepository<OrderVisitRecord> _orderVisitRecordRepository;
    private readonly IQualityApplication _qualityApplication;
    private readonly ICapPublisher _capPublisher;
    private readonly IRepository<SystemOrganize> _systemOrganizeRepository;
    private readonly IRepository<WorkflowCountersign> _workflowCountersignRepository;
    private readonly IRepository<OrderSpecialDetail> _orderSpecialDetailRepository;
    private readonly IRepository<SystemArea> _systemAreaRepository;
    private readonly IRepository<Hotspot> _hotspotRepository;
    private readonly IRepository<WorkflowStep> _workflowStepRepository;
    private readonly IRepository<WorkflowTrace> _workflowTraceRepository;
    private readonly IRepository<SystemDicData> _systemDicDataRepository;
    private readonly IRepository<OrderPublish> _orderPublishRepository;
    private readonly IOrderScreenRepository _orderScreenRepository;
    private readonly IRepository<OrderSendBackAudit> _orderSendBackAuditRepository;
    private readonly ICalcExpireTime _expireTime;
    private readonly IRepository<OrderObserve> _orderObserveRepository;
    private readonly IOrderTerminateRepository _orderTerminateRepository;
    private readonly IRepository<OrderPublishHistory> _orderPublishHistoryRepository;
    private readonly IOrderDelayRepository _orderDelayRepository;
    private readonly IRepository<OrderSecondaryHandling> _orderSecondaryHandlingRepository;
    private readonly IRepository<SchedulingUser> _schedulingUserRepository;
    private readonly IRepository<StatisticsHotspotSatisfied> _statisticsHotspotSatisfiedRepository;
    private readonly IRepository<StatisticsDepartSatisfied> _statisticsDepartSatisfiedRepository;
    private readonly IRepository<OrderTsDetails> _orderTsDetailsRepository;
    private readonly IRepository<KnowledgeQuote> _knowledgeQuoteRepository;
    private readonly IRepository<OrderSpecial> _orderSpecialRepository;
    private readonly IRepository<User> _userRepository;
    private readonly IRepository<Role> _roleRepository;
    private readonly IWorkflowApplication _workflowApplication;
    private readonly ICircularRecordDomainService _circularRecordDomainService;
    private readonly ISessionContextManager _sessionContextManager;
    private readonly IOrderVisitApplication _orderVisitApplication;
    private readonly IRepository<OrderVisitDetailCopy> _orderVisitDetailCopyRepository;
    private readonly IRepository<OrderDelayAutomatic> _orderDelayAutomaticRepository;
    private readonly IRepository<Hotline.Orders.ObservationPiece> _observationPieceRepository;

    public OrderApplication(
        IOrderDomainService orderDomainService,
        IOrderRepository orderRepository,
        IWorkflowDomainService workflowDomainService,
        //ITimeLimitDomainService timeLimitDomainService,
        ISystemSettingCacheManager systemSettingCacheManager,
        IMapper mapper,
        IRepository<OrderWord> orderWrodRepository,
        IRepositoryTextSearch<OrderTs> repositoryts,
        IFileRepository fileRepository,
        ISessionContext sessionContext,
        IRepository<OrderVisit> orderVisitRepository,
        IRepository<OrderVisitDetail> orderVisitDetailRepository,
        IRepository<OrderVisitRecord> orderVisitRecordRepository,
        IQualityApplication qualityApplication,
        ICapPublisher capPublisher,
        IRepository<SystemOrganize> systemOrganizeRepository,
        IRepository<WorkflowCountersign> workflowCountersignRepository,
        IRepository<OrderSpecialDetail> orderSpecialDetailRepository,
        IRepository<SystemArea> systemAreaRepository,
        IRepository<Hotspot> hotspotRepository,
        IRepository<WorkflowStep> workflowStepRepository,
        IRepository<SystemDicData> systemDicDataRepository,
        IRepository<WorkflowTrace> workflowTraceRepository,
        IRepository<OrderPublish> orderPublishRepository,
        IOrderScreenRepository orderScreenRepository,
        IRepository<OrderSendBackAudit> orderSendBackAuditRepository,
        ICalcExpireTime expireTime,
        IMediator mediator,
        IRepository<OrderVisitDetail> orderVisitedDetailRepository,
        IOptionsSnapshot<AppConfiguration> appOptions,
        ISystemDicDataCacheManager sysDicDataCacheManager,
        ISessionContextProvider sessionContextProvider,
        IRepository<TranspondCityRawData> transpondCityRawDataRepository,
        IRepository<OrderObserve> orderObserveRepository,
        IOrderTerminateRepository orderTerminateRepository,
        IRepository<OrderPublishHistory> orderPublishHistoryRepository,
        IRepository<OrderSecondaryHandling> orderSecondaryHandlingRepository,
        IRepository<SchedulingUser> schedulingUserRepository,
        IRepository<StatisticsHotspotSatisfied> statisticsHotspotSatisfiedRepository,
        IRepository<StatisticsDepartSatisfied> statisticsDepartSatisfiedRepository,
        IOrderDelayRepository orderDelayRepository,
        IRepository<OrderTsDetails> orderTsDetailsRepository,
        IRepository<KnowledgeQuote> knowledgeQuoteRepository,
        IRepository<OrderSpecial> orderSpecialRepository,
        IRepository<User> userRepository,
        IWorkflowApplication workflowApplication,
        ICircularRecordDomainService circularRecordDomainService,
        ISessionContextCreator sessionContextCreator,
        ISessionContextManager sessionContextManager,
        IOrderVisitApplication orderVisitApplication,
        IRepository<Role> roleRepository,
        IRepository<OrderVisitDetailCopy> orderVisitDetailCopyRepository,
        IRepository<OrderDelayAutomatic> orderDelayAutomaticRepository,
        IRepository<Hotline.Orders.ObservationPiece> observationPieceRepository
,
        IOrderSnapshotRepository orderSnapshotRepository)
    {
        _orderDomainService = orderDomainService;
        _workflowDomainService = workflowDomainService;
        _orderRepository = orderRepository;
        //_timeLimitDomainService = timeLimitDomainService;
        _mapper = mapper;
        _systemSettingCacheManager = systemSettingCacheManager;
        _orderWrodRepository = orderWrodRepository;
        _repositoryts = repositoryts;
        _fileRepository = fileRepository;
        _orderVisitRepository = orderVisitRepository;
        _orderVisitRecordRepository = orderVisitRecordRepository;
        _orderVisitDetailRepository = orderVisitDetailRepository;
        _qualityApplication = qualityApplication;
        _capPublisher = capPublisher;
        _systemOrganizeRepository = systemOrganizeRepository;
        _workflowCountersignRepository = workflowCountersignRepository;
        _orderSpecialDetailRepository = orderSpecialDetailRepository;
        _systemAreaRepository = systemAreaRepository;
        _hotspotRepository = hotspotRepository;
        _workflowStepRepository = workflowStepRepository;
        _systemDicDataRepository = systemDicDataRepository;
        _workflowTraceRepository = workflowTraceRepository;
        _orderScreenRepository = orderScreenRepository;
        _orderPublishRepository = orderPublishRepository;
        _orderSendBackAuditRepository = orderSendBackAuditRepository;
        _expireTime = expireTime;
        _mediator = mediator;
        _orderVisitedDetailRepository = orderVisitedDetailRepository;
        _appOptions = appOptions;
        _sysDicDataCacheManager = sysDicDataCacheManager;
        _sessionContextProvider = sessionContextProvider;
        _transpondCityRawDataRepository = transpondCityRawDataRepository;
        _orderObserveRepository = orderObserveRepository;
        _orderTerminateRepository = orderTerminateRepository;
        _orderPublishHistoryRepository = orderPublishHistoryRepository;
        _sessionContext = sessionContext;
        _orderDelayRepository = orderDelayRepository;
        _orderSecondaryHandlingRepository = orderSecondaryHandlingRepository;
        _schedulingUserRepository = schedulingUserRepository;
        _statisticsHotspotSatisfiedRepository = statisticsHotspotSatisfiedRepository;
        _statisticsDepartSatisfiedRepository = statisticsDepartSatisfiedRepository;
        _orderTsDetailsRepository = orderTsDetailsRepository;
        _knowledgeQuoteRepository = knowledgeQuoteRepository;
        _orderSpecialRepository = orderSpecialRepository;
        _userRepository = userRepository;
        _workflowApplication = workflowApplication;
        _circularRecordDomainService = circularRecordDomainService;
        _sessionContextManager = sessionContextManager;
        _orderVisitApplication = orderVisitApplication;
        _roleRepository = roleRepository;
        _orderVisitDetailCopyRepository = orderVisitDetailCopyRepository;
        _orderDelayAutomaticRepository = orderDelayAutomaticRepository;
        _observationPieceRepository = observationPieceRepository;
        _orderSnapshotRepository = orderSnapshotRepository;
    }

    /// <summary>
    /// 更新工单办理期满时间(延期调用，其他不调用)
    /// 1.更新工单 2.更新流程 3.推送省平台
    /// </summary>
    /// <returns></returns>
    public async Task DelayOrderExpiredTimeAsync(string orderId, int timeCount, ETimeType timeType, bool IsProDelay,
        CancellationToken cancellationToken)
    {
        var order = await _orderDomainService.GetOrderAsync(orderId, cancellationToken: cancellationToken);
        var expiredTimeBase = DateTime.Now;
        if (_appOptions.Value.IsZiGong)
        {
            expiredTimeBase = order.ExpiredTime.Value;
        }

        var startTime = DateTime.Now;
        if (order.CenterToOrgTime.HasValue)
        {
            startTime = order.CenterToOrgTime!.Value;
        }

        var expiredTimeConfig =
            // _timeLimitDomainService.CalcEndTime(DateTime.Now, new TimeConfig(timeCount, timeType), order.AcceptTypeCode);
            await _expireTime.CalcEndTime(expiredTimeBase, startTime, new TimeConfig(timeCount, timeType), order.AcceptTypeCode);
        //order.TimeLimit = expiredTimeConfig.TimeText;
        //order.TimeLimitCount = expiredTimeConfig.Count;
        //order.TimeLimitUnit = expiredTimeConfig.TimeType;
        order.ExpiredTime = expiredTimeConfig.ExpiredTime;
        order.NearlyExpiredTime = expiredTimeConfig.NearlyExpiredTime;
        order.NearlyExpiredTimeOne = expiredTimeConfig.NearlyExpiredTimeOne;
        //TODO发送短信即将超期
        //_capPublisher.PublishDelay(expiredTimeConfig.NearlyExpiredTime - DateTime.Now, EventNames.HotlineOrderNearlyExpiredTimeSms, new PublishNearlyExpiredTimeSmsDto() { OrderId = order.Id });
        if (IsProDelay)
        {
            order.ExpiredTimeProvince = expiredTimeConfig.ExpiredTime;
        }
        //if (string.IsNullOrEmpty(order.WorkflowId))
        //    throw new UserFriendlyException("该工单流程id异常");
        //var workflow = await _workflowDomainService.GetWorkflowAsync(order.WorkflowId, cancellationToken: cancellationToken);
        //await _workflowDomainService.UpdateExpiredTimeAsync(workflow, expiredTimeConfig.ExpiredTime,
        //    expiredTimeConfig.TimeText, expiredTimeConfig.Count, expiredTimeConfig.TimeType, expiredTimeConfig.NearlyExpiredTime, cancellationToken);

        if (string.IsNullOrEmpty(order.WorkflowId))
            throw new UserFriendlyException("该工单流程id异常");
        await _workflowDomainService.UpdateUnhandleExpiredTimeAsync(order.WorkflowId, expiredTimeConfig.ExpiredTime, cancellationToken);

        await _orderRepository.UpdateAsync(order, cancellationToken);

        var orderDto = _mapper.Map<OrderDto>(order);
        await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderExpiredTimeUpdate, orderDto,
            cancellationToken: cancellationToken);
    }

    // /// <summary>
    // /// 新增工单办理流程记录
    // /// </summary>
    // public async Task AddOrderTracesAsync(string orderId, ICollection<WorkflowTraceDto> traces, CancellationToken cancellationToken)
    // {
    //     var order = await _orderRepository.GetAsync(orderId, cancellationToken);
    //     if (order is null)
    //         throw new UserFriendlyException("工单不存在");
    //     if (string.IsNullOrEmpty(order.WorkflowId))
    //         throw new UserFriendlyException("工单未开启流程");
    //     await _workflowDomainService.AddTracesAsync(order.WorkflowId, _mapper.Map<List<WorkflowTrace>>(traces),
    //         cancellationToken);
    // }

    /// <summary>
    /// 撤销工单
    /// </summary>
    public async Task CancelOrderAsync(string orderId, string opinion, CancellationToken cancellationToken)
    {
        var order = await _orderRepository.GetAsync(orderId, cancellationToken);
        if (order is null)
            throw new UserFriendlyException("工单不存在");
        if (!string.IsNullOrEmpty(order.WorkflowId))
        {
            //结束流程
            await _workflowDomainService.TerminateAsync(new TerminateDto
            {
                WorkflowId = order.WorkflowId,
                Opinion = opinion
            }, cancellationToken);
        }

        //归档工单
        var now = DateTime.Now;
        var handleDuration = order.StartTime.HasValue
            ? //_timeLimitDomainService.CalcWorkTime(
            await _expireTime.CalcWorkTime(
                order.StartTime.Value,
                now, order.ProcessType is EProcessType.Zhiban)
            : 0;
        var fileDuration = order.CenterToOrgTime.HasValue
            ? // _timeLimitDomainService.CalcWorkTime(
            await _expireTime.CalcWorkTime(
                order.CenterToOrgTime.Value,
                now, order.ProcessType is EProcessType.Zhiban)
            : 0;
        var allDuration = order.StartTime.HasValue
            ?
            //_timeLimitDomainService.CalcWorkTime(
            await _expireTime.CalcWorkTime(
                order.StartTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
            : 0;
        var creationTimeHandleDurationWorkday = order.ActualHandleTime.HasValue
            ?
            // _timeLimitDomainService.CalcWorkTime(
            await _expireTime.CalcWorkTime(
                order.CreationTime, now,
                order.ProcessType is EProcessType.Zhiban)
            : 0;
        var centerToOrgHandleDurationWorkday = order.ActualHandleTime.HasValue && order.CenterToOrgTime.HasValue
            ?
            // _timeLimitDomainService.CalcWorkTime(
            await _expireTime.CalcWorkTime(
                order.CenterToOrgTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
            : 0;

        creationTimeHandleDurationWorkday = creationTimeHandleDurationWorkday <= 0 ? 10 : creationTimeHandleDurationWorkday;
        centerToOrgHandleDurationWorkday = centerToOrgHandleDurationWorkday <= 0 ? 10 : centerToOrgHandleDurationWorkday;

        order.File(now, handleDuration, fileDuration, allDuration, creationTimeHandleDurationWorkday, centerToOrgHandleDurationWorkday, null, null);
        await _orderRepository.UpdateAsync(order, cancellationToken);
    }

    /// <summary>
    /// 工单即将超期列表(优化版本v1)
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> GetAboutToExpireAsync(AboutToExpireListDto dto)
    {
        DateTime? dateTime = DateTime.Now;
        var IsCenter = _sessionContext.OrgIsCenter;
        int orgLevel = _sessionContext.OrgLevel;
        var orgCode = _sessionContext.OrgId;
        var query = _orderRepository.Queryable();
        if (IsCenter == true)
            query = _orderRepository.Queryable(canView: !IsCenter);
        return query
            .Includes(d => d.OrderDelays)
            .WhereIF(orgLevel == 3, 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())
            .WhereIF(orgLevel == 2 || orgLevel == 1, d => SqlFunc.Subqueryable<WorkflowStep>()
                .Where(step => step.ExternalId == d.Id &&
                               step.Status != EWorkflowStepStatus.Handled &&
                               (!string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId.StartsWith(orgCode)))
                .Any())
            .WhereIF(dto.IsProvince.HasValue, d => d.IsProvince == dto.IsProvince)
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No!))
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Title.Contains(dto.Title!))
            .WhereIF(dto.Delay.HasValue && dto.Delay == 1, d => d.OrderDelays.Any() == true)
            .WhereIF(dto.Delay.HasValue && dto.Delay == 2, d => d.OrderDelays.Any() == false)
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.HotspotName), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.HotspotName))
            .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
            .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepCode), d => d.CurrentStepCode == dto.CurrentStepCode) //当前办理节点
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
                                                                                                                       //&& stTime >= d.ExpiredTime.Value && stTime2 <= d.ExpiredTime.Value
                                                                                                                       //.Where(d => d.ExpiredTime != null &&
                                                                                                                       //         d.Status != EOrderStatus.Filed && d.Status != EOrderStatus.Published && d.Status != EOrderStatus.Visited && stTime >= d.ExpiredTime.Value && stTime2 <= d.ExpiredTime.Value)
            .Where(d => d.Status < EOrderStatus.Filed && dateTime > d.NearlyExpiredTime && dateTime < d.ExpiredTime)
            .OrderByIF(dto is { SortField: "no", SortRule: 0 }, x => x.No, OrderByType.Asc) //工单编号升序
            .OrderByIF(dto is { SortField: "no", SortRule: 1 }, x => x.No, OrderByType.Desc) //工单编号降序
            .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 0 }, x => x.IsProvince, OrderByType.Asc) //是否省工单升序
            .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 1 }, x => x.IsProvince, OrderByType.Desc) //是否省工单降序
            .OrderByIF(dto is { SortField: "currentStepName", SortRule: 0 }, x => x.CurrentStepName, OrderByType.Asc) //当前节点升序
            .OrderByIF(dto is { SortField: "currentStepName", SortRule: 1 }, x => x.CurrentStepName, OrderByType.Desc) //当前节点降序
            .OrderByIF(dto is { SortField: "delayText", SortRule: 0 }, x => x.OrderDelays.Count, OrderByType.Asc) //是否延期升序
            .OrderByIF(dto is { SortField: "delayText", SortRule: 1 }, x => x.OrderDelays.Count, OrderByType.Desc) //是否延期升序
            .OrderByIF(dto is { SortField: "statusText", SortRule: 0 }, x => x.Status, OrderByType.Asc) //工单状态升序
            .OrderByIF(dto is { SortField: "statusText", SortRule: 1 }, x => x.Status, OrderByType.Desc) //工单状态升序
            .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc) //受理时间升序
            .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc) //受理时间降序
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, x => x.ExpiredTime, OrderByType.Asc) //期满时间升序
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, x => x.ExpiredTime, OrderByType.Desc) //期满时间降序
            .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 0 }, x => x.ActualHandleOrgName, OrderByType.Asc) // 接办部门升序
            .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 1 }, x => x.ActualHandleOrgName, OrderByType.Desc) // 接办部门降序
            .OrderByIF(dto is { SortField: "acceptType", SortRule: 0 }, x => x.AcceptTypeCode, OrderByType.Asc) //受理类型升序
            .OrderByIF(dto is { SortField: "acceptType", SortRule: 1 }, x => x.AcceptTypeCode, OrderByType.Desc) //受理类型降序
            .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 0 }, x => x.CounterSignType, OrderByType.Asc) //是否会签升序
            .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 1 }, x => x.CounterSignType, OrderByType.Desc) //是否会签降序
            .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 0 }, x => x.OrgLevelOneName, OrderByType.Asc) //一级部门升序
            .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 1 }, x => x.OrgLevelOneName, OrderByType.Desc) //一级部门降序
            .OrderByIF(dto is { SortField: "hotspotName", SortRule: 0 }, x => x.HotspotId, OrderByType.Asc) //热点升序
            .OrderByIF(dto is { SortField: "hotspotName", SortRule: 1 }, x => x.HotspotId, OrderByType.Desc) //热点降序
            .OrderByIF(dto is { SortField: "acceptorName", SortRule: 0 }, x => x.AcceptorName, OrderByType.Asc) // 受理人升序
            .OrderByIF(dto is { SortField: "acceptorName", SortRule: 1 }, x => x.AcceptorName, OrderByType.Desc); // 受理人升序
    }

    /// <summary>
    /// 即将超期列表
    /// 25年1月14日: 因为查询时间太久,注释了;
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    //public ISugarQueryable<Order> GetAboutToExpireAsync(AboutToExpireListDto dto)
    //{
    //    //var setting = _systemSettingCacheManager.GetSetting(SettingConstants.OrderAboutToExpire);
    //    //var value = setting?.SettingValue[0];
    //    //value = string.IsNullOrEmpty(value) ? "0" : value;
    //    //DateTime stTime = DateTime.Now.AddDays(int.Parse(value));
    //    //stTime = _timeLimitDomainService.WorkDay(stTime);
    //    //DateTime stTime2 = _timeLimitDomainService.WorkDay(DateTime.Now);
    //    DateTime? dateTime = DateTime.Now;
    //    var IsCenter = _sessionContext.OrgIsCenter;
    //    int orgLevel = _sessionContext.OrgLevel;
    //    var orgCode = _sessionContext.OrgId;
    //    //var query = _orderRepository.Queryable();
    //    //if (IsCenter == true)
    //    //    query = _orderRepository.Queryable(canView: !IsCenter);
    //    //return query.Includes(d => d.OrderDelays)
    //    return _orderRepository.Queryable(canView: !IsCenter)
    //        .Includes(d => d.OrderDelays)
    //        .WhereIF(orgLevel == 3, 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())
    //         .WhereIF(orgLevel == 2 || orgLevel == 1, d => SqlFunc.Subqueryable<WorkflowStep>()
    //            .Where(step => step.ExternalId == d.Id &&
    //                           step.Status != EWorkflowStepStatus.Handled &&
    //                           (!string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId.StartsWith(orgCode)))
    //            .Any())
    //        .WhereIF(dto.IsProvince.HasValue, d => d.IsProvince == dto.IsProvince)
    //        .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No!))
    //        .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Title.Contains(dto.Title!))
    //        .WhereIF(dto.Delay.HasValue && dto.Delay == 1, d => d.OrderDelays.Any() == true)
    //        .WhereIF(dto.Delay.HasValue && dto.Delay == 2, d => d.OrderDelays.Any() == false)
    //        .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
    //        .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
    //        .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
    //        .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
    //        .WhereIF(!string.IsNullOrEmpty(dto.HotspotName), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.HotspotName))
    //        .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
    //        .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
    //        .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门
    //                                                                                                                               //&& stTime >= d.ExpiredTime.Value && stTime2 <= d.ExpiredTime.Value
    //                                                                                                                               //.Where(d => d.ExpiredTime != null &&
    //                                                                                                                               // d.Status != EOrderStatus.Filed && d.Status != EOrderStatus.Published && d.Status != EOrderStatus.Visited && stTime >= d.ExpiredTime.Value && stTime2 <= d.ExpiredTime.Value)
    //        .Where(d => d.Status < EOrderStatus.Filed && dateTime > d.NearlyExpiredTime && dateTime < d.ExpiredTime)
    //        .OrderByIF(dto is { SortField: "no", SortRule: 0 }, x => x.No, OrderByType.Asc) //工单编号升序
    //        .OrderByIF(dto is { SortField: "no", SortRule: 1 }, x => x.No, OrderByType.Desc) //工单编号降序
    //        .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 0 }, x => x.IsProvince, OrderByType.Asc)//是否省工单升序
    //        .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 1 }, x => x.IsProvince, OrderByType.Desc)//是否省工单降序
    //        .OrderByIF(dto is { SortField: "currentStepName", SortRule: 0 }, x => x.CurrentStepName, OrderByType.Asc)//当前节点升序
    //        .OrderByIF(dto is { SortField: "currentStepName", SortRule: 1 }, x => x.CurrentStepName, OrderByType.Desc)//当前节点降序
    //        .OrderByIF(dto is { SortField: "delayText", SortRule: 0 }, x => x.OrderDelays.Count, OrderByType.Asc) //是否延期升序
    //        .OrderByIF(dto is { SortField: "delayText", SortRule: 1 }, x => x.OrderDelays.Count, OrderByType.Desc) //是否延期升序
    //        .OrderByIF(dto is { SortField: "statusText", SortRule: 0 }, x => x.Status, OrderByType.Asc) //工单状态升序
    //        .OrderByIF(dto is { SortField: "statusText", SortRule: 1 }, x => x.Status, OrderByType.Desc) //工单状态升序
    //        .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc) //受理时间升序
    //        .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc) //受理时间降序
    //        .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, x => x.ExpiredTime, OrderByType.Asc) //期满时间升序
    //        .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, x => x.ExpiredTime, OrderByType.Desc) //期满时间降序
    //        .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 0 }, x => x.ActualHandleOrgName, OrderByType.Asc)// 接办部门升序
    //        .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 1 }, x => x.ActualHandleOrgName, OrderByType.Desc)// 接办部门降序
    //        .OrderByIF(dto is { SortField: "acceptType", SortRule: 0 }, x => x.AcceptTypeCode, OrderByType.Asc) //受理类型升序
    //        .OrderByIF(dto is { SortField: "acceptType", SortRule: 1 }, x => x.AcceptTypeCode, OrderByType.Desc) //受理类型降序
    //        .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 0 }, x => x.CounterSignType, OrderByType.Asc) //是否会签升序
    //        .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 1 }, x => x.CounterSignType, OrderByType.Desc) //是否会签降序
    //        .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 0 }, x => x.OrgLevelOneName, OrderByType.Asc) //一级部门升序
    //        .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 1 }, x => x.OrgLevelOneName, OrderByType.Desc)//一级部门降序
    //        .OrderByIF(dto is { SortField: "hotspotName", SortRule: 0 }, x => x.HotspotId, OrderByType.Asc) //热点升序
    //        .OrderByIF(dto is { SortField: "hotspotName", SortRule: 1 }, x => x.HotspotId, OrderByType.Desc) //热点降序
    //        .OrderByIF(dto is { SortField: "acceptorName", SortRule: 0 }, x => x.AcceptorName, OrderByType.Asc)// 受理人升序
    //        .OrderByIF(dto is { SortField: "acceptorName", SortRule: 1 }, x => x.AcceptorName, OrderByType.Desc);// 受理人升序
    //}

    // /// <summary>
    // /// 即将超期节点列表
    // /// </summary>
    // /// <param name="dto"></param>
    // /// <param name="cancellationToken"></param>
    // /// <returns></returns>
    //public async Task<PagedDto<WorkflowOrderDto>> GetAboutToExpireNodeAsync(AboutToExpireListDto dto, CancellationToken cancellationToken)
    //{
    //	var setting = _systemSettingCacheManager.GetSetting(SettingConstants.OrderAboutToExpire);
    //	var value = setting?.SettingValue[0];
    //	value = string.IsNullOrEmpty(value) ? "0" : value;
    //	DateTime stTime = DateTime.Now.AddDays(int.Parse(value));
    //	stTime = _timeLimitDomainService.WorkDay(DateTime.Now);
    //	DateTime stTime2 = _timeLimitDomainService.WorkDay(DateTime.Now);
    //	RefAsync<int> total = 0;
    //	var items = await Db.Queryable<Workflow>()
    //		.LeftJoin<Order>((x, o) => x.ExternalId == o.Id)
    //		.Where(x => x.ModuleCode == "OrderHandle")
    //		.WhereIF(dto.IsProvince.HasValue, (x, o) => o.IsProvince == dto.IsProvince)
    //		.WhereIF(!string.IsNullOrEmpty(dto.Keyword), (x, o) => o.Title.Contains(dto.Keyword!) || o.No.Contains(dto.Keyword!))
    //		.Where((x, o) => (int)x.Status < 20 && stTime >= x.ExpiredTime && stTime2 <= x.ExpiredTime)
    //		.Select((x, o) => new WorkflowOrder { Order = o }, true)
    //		.OrderByDescending(x => x.CreationTime)
    //		.ToPageListAsync(dto.PageIndex, dto.PageSize, total, cancellationToken);
    //	return new PagedDto<WorkflowOrderDto>(total, _mapper.Map<IReadOnlyList<WorkflowOrderDto>>(items));
    //}

    /// <summary>
    /// 已超期列表
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> GetToExpireAsync(AboutToExpireListDto dto)
    {
        // DateTime stTime = _timeLimitDomainService.WorkDay(DateTime.Now);
        DateTime stTime = _expireTime.WorkDay(DateTime.Now).GetAwaiter().GetResult();
        var IsCenter = _sessionContext.OrgIsCenter;
        int orgLevel = _sessionContext.OrgLevel;
        var orgCode = _sessionContext.OrgId;
        return _orderRepository.Queryable(canView: false).Includes(d => d.OrderDelays)
            .WhereIF(orgLevel == 3, 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())
            // .WhereIF(orgLevel == 2 || orgLevel == 1, d =>  d.ActualHandleOrgCode.StartsWith(orgCode))
            .WhereIF(orgLevel == 2 || orgLevel == 1, d => SqlFunc.Subqueryable<WorkflowStep>()
                .Where(step => step.ExternalId == d.Id &&
                               step.Status != EWorkflowStepStatus.Handled &&
                               (!string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId.StartsWith(orgCode)))
                .Any())
            .WhereIF(dto.IsProvince.HasValue, d => d.IsProvince == dto.IsProvince)
            //.WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.Contains(dto.Keyword!) || d.No.Contains(dto.Keyword!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.No.Contains(dto.No))
            .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Title.Contains(dto.Title!))
            .WhereIF(dto.Delay.HasValue && dto.Delay == 1, d => d.OrderDelays.Any() == true)
            .WhereIF(dto.Delay.HasValue && dto.Delay == 2, d => d.OrderDelays.Any() == false)
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.HotspotName), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.HotspotName))
            .WhereIF(dto.FiledTimeStart.HasValue, d => d.FiledTime >= dto.FiledTimeStart) //办结时间开始
            .WhereIF(dto.FiledTimeEnd.HasValue, d => d.FiledTime <= dto.FiledTimeEnd) //办结时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门
            .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status) //工单状态
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepCode), d => d.CurrentStepCode == dto.CurrentStepCode) //当前办理节点
            .Where(d => d.Status < EOrderStatus.Filed)
            .Where(d => d.ExpiredTime != null &&
                        (((d.Status == EOrderStatus.Filed || d.Status == EOrderStatus.Published || d.Status == EOrderStatus.Visited) &&
                          d.FiledTime >= d.ExpiredTime) ||
                         ((d.Status != EOrderStatus.Filed && d.Status != EOrderStatus.Published && d.Status != EOrderStatus.Visited) &&
                          stTime >= d.ExpiredTime.Value)))
            .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, x => x.CreationTime, OrderByType.Asc) //受理时间升序
            .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, x => x.CreationTime, OrderByType.Desc) //受理时间降序
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, x => x.ExpiredTime, OrderByType.Asc) //期满时间升序
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, x => x.ExpiredTime, OrderByType.Desc); //期满时间降序
    }

    //     /// <summary>
    //     /// 已超期节点列表
    //     /// </summary>
    //     /// <param name="dto"></param>
    //     /// <param name="cancellationToken"></param>
    //     /// <returns></returns>
    //     public async Task<PagedDto<WorkflowOrderDto>> GetToExpireNodeAsync(AboutToExpireListDto dto, CancellationToken cancellationToken)
    //     {
    //      DateTime stTime = _timeLimitDomainService.WorkDay(DateTime.Now);
    //RefAsync<int> total = 0;
    //var  items= await Db.Queryable<Workflow>()
    //             .LeftJoin<Order>((x,o)=>x.ExternalId == o.Id)
    //             .Where(x => x.ModuleCode == "OrderHandle")
    //             .WhereIF(dto.IsProvince.HasValue, (x, o) => o.IsProvince == dto.IsProvince)
    //             .WhereIF(!string.IsNullOrEmpty(dto.Keyword), (x, o) => o.Title.Contains(dto.Keyword!) || o.No.Contains(dto.Keyword!))
    //             .Where((x,o) => (((int)x.Status >= 20 && x.EndTime >= x.ExpiredTime) || ((int)x.Status < 20 && stTime >= x.ExpiredTime)))
    //             .Select((x, o) => new WorkflowOrder { Order = o }, true)
    //             .OrderByDescending(x => x.CreationTime)
    //             .ToPageListAsync(dto.PageIndex, dto.PageSize, total, cancellationToken);
    //      return new PagedDto<WorkflowOrderDto>(total, _mapper.Map<IReadOnlyList<WorkflowOrderDto>>(items));
    //     }

    /// <summary>
    /// 工单关键字分词
    /// </summary>
    /// <param name="inputStr"></param>
    /// <param name="orderId"></param>
    /// <param name="no"></param>
    /// <param name="title"></param>
    /// <param name="time"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task OrderParticiple(string inputStr, string orderId, string no, string title, DateTime time, CancellationToken cancellationToken)
    {
        var seg = new Segment();
        ICollection<WordInfo> splitWords = seg.DoSegment(inputStr);
        var words = new List<string>();
        for (int i = 0; i < splitWords.Count; i++)
        {
            var word = splitWords.ElementAt(i);
            if (word is { WordType: WordType.SimplifiedChinese, Word.Length: > 1 })
                words.Add(splitWords.ElementAt(i).Word);
        }

        if (words.Any())
        {
            var vector = await _repositoryts.SearchAsync(orderId, cancellationToken);
            if (vector != null && vector.Any()) await _repositoryts.UpdateVectorAsync(orderId, words, cancellationToken);
            else await _repositoryts.AddVectorAsync(orderId, time, words, cancellationToken);

            //是否开启分词
            var isOpenWordSegmentation = _systemSettingCacheManager.GetSetting(SettingConstants.IsOpenWordSegmentation)?.SettingValue[0];
            if (!string.IsNullOrEmpty(isOpenWordSegmentation) && isOpenWordSegmentation == "true")
            {
                //先删除历史数据，在添加新数据
                await _orderTsDetailsRepository.RemoveAsync(p => p.OrderId == orderId, false, cancellationToken);
                List<OrderTsDetails> orderTsDetails = new();
                List<string> listWord = words.Distinct().ToList();
                foreach (var item in listWord)
                {
                    orderTsDetails.Add(new OrderTsDetails
                    {
                        Terms = item,
                        OrderId = orderId,
                        Title = title,
                        No = no
                    });
                }

                if (orderTsDetails != null && orderTsDetails.Count > 0)
                    await _orderTsDetailsRepository.AddRangeAsync(orderTsDetails, cancellationToken);
            }
        }
        // 结巴分词
        //var segmenter = new JiebaSegmenter();
        //var segments1 = segmenter.Cut(inputStr, cutAll: true);
        //var b = segments1;


        //var words = await _orderWrodRepository.Queryable().Where(x => x.IsEnable == 1 && x.Classify.Contains("普通标签")).Select(x => x.Tag).ToListAsync(cancellationToken);
        //var res = new List<string>();
        //if (words.Any()) res = ParticipleTool.SegMMDouble(inputStr, ref words);
        //var participles = await _orderWrodRepository.Queryable().In(x => x.Tag, res).ToListAsync(cancellationToken);
        //if (participles.Any())
        //{
        //    //关键词
        //    var tags = participles.Select(x => x.Tag).ToList();
        //    var tagsStr = string.Join(",", tags);
        //    await _orderRepository.Updateable().SetColumns(x => x.TagNames == tagsStr).Where(x => x.Id == orderId).ExecuteCommandAsync(cancellationToken);
        //    List<string> synonyms = participles.Select(x => x.Synonym).ToList();
        //    if (synonyms.Any())
        //    {
        //        var synonymsStr = string.Join(",", synonyms);
        //        synonyms = synonymsStr.Split(",").Distinct().ToList();
        //        tags.AddRange(synonyms);
        //    }
        //    var vector = await _orderRepository.Queryable().Where(x => x.Id == orderId).ToListAsync(cancellationToken);
        //    if (vector.Any()) await _repositoryts.UpdateVectorAsync(orderId, tags, cancellationToken);
        //    else await _repositoryts.AddVectorAsync(orderId, DateTime.Now, tags, cancellationToken);
        //}
    }

    public async Task OrderSensitiveParticiple(string inputStr, string orderId, CancellationToken cancellationToken)
    {
        var words = await _orderWrodRepository.Queryable().Where(x => x.IsEnable == 1 && x.Classify.Contains("敏感标签")).Select(x => x.Tag)
            .ToListAsync(cancellationToken);
        var res = new List<string>();
        if (words.Any()) res = ParticipleTool.SegMMDouble(inputStr, ref words);
        if (res.Any())
        {
            var intersect = words.Intersect(res).ToList();
            await _orderRepository.Updateable().SetColumns(o => new Order() { Sensitive = intersect }).Where(o => o.Id == orderId)
                .ExecuteCommandAsync(cancellationToken);
        }
    }

    /// <summary>
    /// 接收外部平台工单
    /// </summary>
    public async Task<AddOrderResponse> ReceiveOrderFromExternalAsync(AddOrderDto dto, CancellationToken cancellationToken)
    {
        switch (dto.Source)
        {
            case ESource.ProvinceStraight:
                //SessionContextCreator.CreateSessionContext(_sessionContextProvider, "province");
                //await _sessionContextCreator.CreateSessionContextAsync("province", cancellationToken);
                _sessionContextManager.ChangeSessionContext("province");

                return await ReceiveOrderFromProvinceAsync(dto, dto.Files, cancellationToken);
            case ESource.Police110:
            case ESource.CityDataExchangeLz:
            case ESource.CityDataExchangeYB:
            case ESource.CityDataExchangeZG:
            case ESource.CityDataExchangeNJ:
            case ESource.WebPortal:
            case ESource.ConvergenceMedia:
            case ESource.IYIBIN:
            case ESource.ZHYB:
            case ESource.ZZPT:
            case ESource.WLLZ:
            case ESource.YBS:
            case ESource.APP:
            case ESource.WeChat:
            case ESource.ZGGC:
            case ESource.ZGTFTB:
            case ESource.YBHumanSocietyAPP:
                return await ReceiveOrderFromOtherPlatformAsync(dto, dto.Files, cancellationToken);
            case ESource.Hotline:
            case ESource.HotlineImport:
            default:
                return await ReceiveOrderFromOtherPlatformAsync(dto, dto.Files, cancellationToken);
        }
    }

    /// <summary>
    /// 接收外部平台修改工单附件
    /// </summary>
    public async Task UpdateOrderFilesAnonymousAsync(UpdateOrderFilesDto dto, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(dto.Id) && string.IsNullOrEmpty(dto.OrderNo))
            throw new UserFriendlyException("工单外部编号不能为空");

        var order = await _orderRepository.Queryable()
            .FirstAsync(d => d.Id == dto.Id || d.No == dto.OrderNo, cancellationToken);

        if (order != null && dto.Files != null && dto.Files.Any())
        {
            List<FileJson> file = order.FileJson;
            List<FileJson> fileNew = await _fileRepository.AddFileAsync(dto.Files, order.Id, cancellationToken);
            if (file != null)
            {
                file.AddRange(fileNew);
                order.FileJson = file;
            }
            else
            {
                order.FileJson = fileNew;
            }
            await _orderRepository.UpdateAsync(order, cancellationToken);
        }
    }

    /// <summary>
    /// 获取待发布列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> GetPublishOrderList(QueryOrderPublishDto dto)
    {
        var query = _orderRepository.Queryable().Includes(d => d.OrderTags);
        if (_appOptions.Value.IsLuZhou)
            query = query.Includes(d => d.FwCallRecord);
        //.Includes(d => d.OrderPublish)
        return query.Where(d => d.Status == EOrderStatus.Filed)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.StartsWith(dto.Keyword!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No))
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Title.Contains(dto.Title))
            //.WhereIF(dto.PubState == EPubState.Pub, d => d.Status >= EOrderStatus.Published)
            //.WhereIF(dto.PubState == EPubState.NoPub, d => d.Status == EOrderStatus.Filed)
            .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.SourceChannelCode == dto.Channel)
            //.WhereIF(!string.IsNullOrEmpty(dto.OrderTag), d => d.OrderTagCode == dto.OrderTag!) //工单标签
            .WhereIF(!string.IsNullOrEmpty(dto.OrderTag), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTag)) //工单标签
            .WhereIF(!string.IsNullOrEmpty(dto.CenterToOrgHandlerName), d => d.CenterToOrgHandlerName.Contains(dto.CenterToOrgHandlerName)) //派单人
            .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo),
                d => d.AcceptorName.Contains(dto.NameOrNo) || d.AcceptorStaffNo.Contains(dto.NameOrNo)) //受理人/坐席
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.Hotspot))
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone == dto.FromPhone) //来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.Contact), d => d.Contact == dto.Contact) //联系电话
                                                                                        //.WhereIF(!string.IsNullOrEmpty(dto.PubMan),
                                                                                        //    d => d.AcceptorName.Contains(dto.PubMan!) || d.AcceptorStaffNo.Contains(dto.PubMan!))
                                                                                        //.WhereIF(dto.PubRange == EPublicState.Pub, d => d.OrderPublish.PublishState)
                                                                                        //.WhereIF(dto.PubRange == EPublicState.NoPub, d => !d.OrderPublish.PublishState)
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true, d => d.IsProvince == true)
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false, d => d.IsProvince == false)
            //.WhereIF(dto.FiledType != null && dto.FiledType == FiledType.CenterFiled, d => d.ProcessType == EProcessType.Zhiban)
            //.WhereIF(dto.FiledType != null && dto.FiledType == FiledType.OrgFiled, d => d.ProcessType == EProcessType.Jiaoban)
            .WhereIF(dto.FiledType != null && dto.FiledType == FiledType.CenterFiled, d => d.FileOrgIsCenter == true)
            .WhereIF(dto.FiledType != null && dto.FiledType == FiledType.OrgFiled, d => d.FileOrgIsCenter == false)
            .WhereIF(dto.IsCountersign != null && dto.IsCountersign == true, d => d.CounterSignType != null)
            .WhereIF(dto.IsCountersign != null && dto.IsCountersign == false, d => d.CounterSignType == null)
            .WhereIF(dto.AcceptTypes.Any(), d => dto.AcceptTypes.Contains(d.AcceptType))
            .WhereIF(dto.HotspotIds.Any(), d => dto.HotspotIds.Contains(d.HotspotId))
            //.WhereIF(dto.Resolve.HasValue, d => d.OrderPublish.Resolve == dto.Resolve)
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart)
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd)
            .WhereIF(dto.FiledTimeStart.HasValue, d => d.FiledTime >= dto.FiledTimeStart)
            .WhereIF(dto.FiledTimeEnd.HasValue, d => d.FiledTime <= dto.FiledTimeEnd)
            .WhereIF(dto.ExpiredTimeProvinceStart.HasValue, d => d.ExpiredTimeProvince >= dto.ExpiredTimeProvinceStart) //省期满时间开始
            .WhereIF(dto.ExpiredTimeProvinceEnd.HasValue, d => d.ExpiredTimeProvince <= dto.ExpiredTimeProvinceEnd) //省期满时间结束
            .WhereIF(dto.Iszgzfw.HasValue && dto.Iszgzfw == true, d => d.ReceiveProvinceNo.StartsWith("ZGZFW"))
            .WhereIF(dto.Isgjzwfwpt.HasValue && dto.Isgjzwfwpt == true, d => d.ReceiveProvinceNo.StartsWith("GJZWFWPT"))
            .WhereIF(dto.QuerySelf.HasValue && dto.QuerySelf.Value, d => d.WaitForPublisherId == _sessionContext.RequiredUserId)
            .WhereIF(dto.IdentityType != null, d => d.IdentityType == dto.IdentityType) //来电主体
            .WhereIF(dto.IsOverTime == true,
                d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                     (d.ExpiredTime < d.ActualHandleTime && d.Status >= EOrderStatus.Filed)) //是 超期
            .WhereIF(dto.IsOverTime == false,
                d => (d.ExpiredTime > DateTime.Now && d.Status < EOrderStatus.Filed) ||
                     (d.ExpiredTime > d.ActualHandleTime && d.Status >= EOrderStatus.Filed)) //否 超期
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Source == ESource.ProvinceStraight &&
                d.SourceChannelCode == "SZMHD" && d.IsProvince == false) //政民互动直派
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Source == ESource.ProvinceStraight &&
                d.SourceChannelCode == "SZMHD" && d.IsProvince == true) //政民互动
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Source == ESource.ProvinceStraight &&
                d.SourceChannelCode == "S12345" && d.IsProvince == true) //省12345
            .OrderBy(d => new { IsUrgent = d.IsUrgent }, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.IsUrgent, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "filedTime" }, d => d.FiledTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "filedTime" }, d => d.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "actualHandleTime" }, d => d.ActualHandleTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "actualHandleTime" }, d => d.ActualHandleTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "creationTime" }, d => d.CreationTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "creationTime" }, d => d.CreationTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "expiredTimeProvince" }, d => d.ExpiredTimeProvince, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "expiredTimeProvince" }, d => d.ExpiredTimeProvince, OrderByType.Desc);
    }

    /// <summary>
    /// 获取临时待发布列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> GetPublishTempOrderList(QueryOrderPublishDto dto)
    {
        var query = _orderRepository.Queryable().Includes(d => d.OrderTags);
        if (_appOptions.Value.IsLuZhou)
            query = query.Includes(d => d.FwCallRecord);
        query = query.RightJoin<OrderPublishTemp>((d, p) => d.No == p.No);

        return query.Where(d => d.Status == EOrderStatus.Filed)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.StartsWith(dto.Keyword!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No))
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Title.Contains(dto.Title))
            //.WhereIF(dto.PubState == EPubState.Pub, d => d.Status >= EOrderStatus.Published)
            //.WhereIF(dto.PubState == EPubState.NoPub, d => d.Status == EOrderStatus.Filed)
            .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.SourceChannelCode == dto.Channel)
            //.WhereIF(!string.IsNullOrEmpty(dto.OrderTag), d => d.OrderTagCode == dto.OrderTag!) //工单标签
            .WhereIF(!string.IsNullOrEmpty(dto.OrderTag), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTag)) //工单标签
            .WhereIF(!string.IsNullOrEmpty(dto.CenterToOrgHandlerName), d => d.CenterToOrgHandlerName.Contains(dto.CenterToOrgHandlerName)) //派单人
            .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo),
                d => d.AcceptorName.Contains(dto.NameOrNo) || d.AcceptorStaffNo.Contains(dto.NameOrNo)) //受理人/坐席
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.Hotspot))
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone == dto.FromPhone) //来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.Contact), d => d.Contact == dto.Contact) //联系电话
                                                                                        //.WhereIF(!string.IsNullOrEmpty(dto.PubMan),
                                                                                        //    d => d.AcceptorName.Contains(dto.PubMan!) || d.AcceptorStaffNo.Contains(dto.PubMan!))
                                                                                        //.WhereIF(dto.PubRange == EPublicState.Pub, d => d.OrderPublish.PublishState)
                                                                                        //.WhereIF(dto.PubRange == EPublicState.NoPub, d => !d.OrderPublish.PublishState)
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true, d => d.IsProvince == true)
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false, d => d.IsProvince == false)
            //.WhereIF(dto.FiledType != null && dto.FiledType == FiledType.CenterFiled, d => d.ProcessType == EProcessType.Zhiban)
            //.WhereIF(dto.FiledType != null && dto.FiledType == FiledType.OrgFiled, d => d.ProcessType == EProcessType.Jiaoban)
            .WhereIF(dto.FiledType != null && dto.FiledType == FiledType.CenterFiled, d => d.FileOrgIsCenter == true)
            .WhereIF(dto.FiledType != null && dto.FiledType == FiledType.OrgFiled, d => d.FileOrgIsCenter == false)
            .WhereIF(dto.IsCountersign != null && dto.IsCountersign == true, d => d.CounterSignType != null)
            .WhereIF(dto.IsCountersign != null && dto.IsCountersign == false, d => d.CounterSignType == null)
            .WhereIF(dto.AcceptTypes.Any(), d => dto.AcceptTypes.Contains(d.AcceptType))
            .WhereIF(dto.HotspotIds.Any(), d => dto.HotspotIds.Contains(d.HotspotId))
            //.WhereIF(dto.Resolve.HasValue, d => d.OrderPublish.Resolve == dto.Resolve)
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart)
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd)
            .WhereIF(dto.FiledTimeStart.HasValue, d => d.FiledTime >= dto.FiledTimeStart)
            .WhereIF(dto.FiledTimeEnd.HasValue, d => d.FiledTime <= dto.FiledTimeEnd)
            .WhereIF(dto.ExpiredTimeProvinceStart.HasValue, d => d.ExpiredTimeProvince >= dto.ExpiredTimeProvinceStart) //省期满时间开始
            .WhereIF(dto.ExpiredTimeProvinceEnd.HasValue, d => d.ExpiredTimeProvince <= dto.ExpiredTimeProvinceEnd) //省期满时间结束
            .WhereIF(dto.Iszgzfw.HasValue && dto.Iszgzfw == true, d => d.ReceiveProvinceNo.StartsWith("ZGZFW"))
            .WhereIF(dto.Isgjzwfwpt.HasValue && dto.Isgjzwfwpt == true, d => d.ReceiveProvinceNo.StartsWith("GJZWFWPT"))
            .WhereIF(dto.QuerySelf.HasValue && dto.QuerySelf.Value, d => d.WaitForPublisherId == _sessionContext.RequiredUserId)
            .WhereIF(dto.IdentityType != null, d => d.IdentityType == dto.IdentityType) //来电主体
            .WhereIF(dto.IsOverTime == true,
                d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                     (d.ExpiredTime < d.ActualHandleTime && d.Status >= EOrderStatus.Filed)) //是 超期
            .WhereIF(dto.IsOverTime == false,
                d => (d.ExpiredTime > DateTime.Now && d.Status < EOrderStatus.Filed) ||
                     (d.ExpiredTime > d.ActualHandleTime && d.Status >= EOrderStatus.Filed)) //否 超期
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Source == ESource.ProvinceStraight &&
                d.SourceChannelCode == "SZMHD" && d.IsProvince == false) //政民互动直派
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Source == ESource.ProvinceStraight &&
                d.SourceChannelCode == "SZMHD" && d.IsProvince == true) //政民互动
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Source == ESource.ProvinceStraight &&
                d.SourceChannelCode == "S12345" && d.IsProvince == true) //省12345
            .OrderBy(d => new { IsUrgent = d.IsUrgent }, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.IsUrgent, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "filedTime" }, d => d.FiledTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "filedTime" }, d => d.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "actualHandleTime" }, d => d.ActualHandleTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "actualHandleTime" }, d => d.ActualHandleTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "creationTime" }, d => d.CreationTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "creationTime" }, d => d.CreationTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "expiredTimeProvince" }, d => d.ExpiredTimeProvince, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "expiredTimeProvince" }, d => d.ExpiredTimeProvince, OrderByType.Desc);
    }

    public ISugarQueryable<OrderPublish> GetPublishedOrder(PublishedPagedRequest dto)
    {
        return _orderPublishRepository.Queryable()
            .Includes(x => x.Order)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Order.Title.StartsWith(dto.Keyword!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Order.No.Contains(dto.No!))
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title!))
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart)
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd)
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.Order.FromPhone == dto.FromPhone) //来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName),
                d => d.Order.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot))
            .WhereIF(!string.IsNullOrEmpty(dto.PublishName), d => d.CreatorName.Contains(dto.PublishName!))
            .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo),
                d => d.Order.AcceptorName.Contains(dto.NameOrNo) || d.Order.AcceptorStaffNo.Contains(dto.NameOrNo)) //受理人/坐席
            .WhereIF(dto.StartTime.HasValue, d => d.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, d => d.CreationTime <= dto.EndTime)
            .WhereIF(dto.Resolve.HasValue, x => x.Resolve == dto.Resolve)
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.Order.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
            .WhereIF(dto.IdentityType != null, d => d.Order.IdentityType == dto.IdentityType) //来电主体
            .WhereIF(dto.IsOverTime == true,
                d => (d.Order.ExpiredTime < DateTime.Now && d.Order.Status < EOrderStatus.Filed) ||
                     (d.Order.ExpiredTime < d.Order.ActualHandleTime && d.Order.Status >= EOrderStatus.Filed)) //是 超期
            .WhereIF(dto.IsOverTime == false,
                d => (d.Order.ExpiredTime > DateTime.Now && d.Order.Status < EOrderStatus.Filed) ||
                     (d.Order.ExpiredTime > d.Order.ActualHandleTime && d.Order.Status >= EOrderStatus.Filed)) //否 超期
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Order.Source == ESource.ProvinceStraight &&
                d.Order.SourceChannelCode == "SZMHD" && d.Order.IsProvince == false) //政民互动直派
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Order.Source == ESource.ProvinceStraight &&
                d.Order.SourceChannelCode == "SZMHD" && d.Order.IsProvince == true) //政民互动
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Order.Source == ESource.ProvinceStraight &&
                d.Order.SourceChannelCode == "S12345" && d.Order.IsProvince == true) //省12345
            .WhereIF(dto.PublishState.HasValue, d => d.PublishState == dto.PublishState.Value) //发布范围 是否公开
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "creationTime" }, d => d.Order.CreationTime, OrderByType.Asc)   //受理时间
            .OrderByIF(dto is { SortRule: 1, SortField: "creationTime" }, d => d.Order.CreationTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "filedTime" }, d => d.Order.FiledTime, OrderByType.Asc)  //办结时间
            .OrderByIF(dto is { SortRule: 1, SortField: "filedTime" }, d => d.Order.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "publishTime" }, d => d.CreationTime, OrderByType.Asc) //发布时间
            .OrderByIF(dto is { SortRule: 1, SortField: "publishTime" }, d => d.CreationTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "lastModificationTime" }, d => d.LastModificationTime, OrderByType.Asc) //更新时间
            .OrderByIF(dto is { SortRule: 1, SortField: "lastModificationTime" }, d => d.LastModificationTime, OrderByType.Desc);
    }

    /// <summary>
    /// 发布量统计(按账号)
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="UserFriendlyException"></exception>
    public async Task<(int, IList<PublishedOrderStatisticsDto>)> QueryPublishedOrderAsync(QueryOrderPublishStatisticsDto dto, bool isFull)
    {
        var orders = await _orderRepository.Queryable()
            .LeftJoin<User>((order, user) => order.WaitForPublisherId == user.Id)
            .Where((order, user) => !string.IsNullOrEmpty(order.WaitForPublisherId))
            .WhereIF(dto.ProcessType != null && dto.ProcessType == EProcessType.Zhiban, (order, user) => order.FileOrgIsCenter == true)
            .WhereIF(dto.ProcessType != null && dto.ProcessType == EProcessType.Jiaoban, (order, user) => order.FileOrgIsCenter == false)
            .GroupBy((order, user) => new { order.WaitForPublisherId, user.Name })
            .Select((order, user) => new PublishedOrderStatisticsDto
            {
                Id = order.WaitForPublisherId,
                Name = user.Name,
                WaitCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.Status == EOrderStatus.Filed, 1, 0)),
            }).ToListAsync();

        var query = _orderRepository.Queryable()
            .Includes(order => order.OrderPublish)
            .LeftJoin<User>((order, user) => order.WaitForPublisherId == user.Id)
            .Where((order, user) => order.OrderPublish.CreationTime >= dto.StartTime && order.OrderPublish.CreationTime <= dto.EndTime &&
                                    !string.IsNullOrEmpty(order.WaitForPublisherId))
            //  .WhereIF(dto.ProcessType != null, (order, user) => order.ProcessType == dto.ProcessType)
            .WhereIF(dto.ProcessType != null && dto.ProcessType == EProcessType.Zhiban, (order, user) => order.FileOrgIsCenter == true)
            .WhereIF(dto.ProcessType != null && dto.ProcessType == EProcessType.Jiaoban, (order, user) => order.FileOrgIsCenter == false)
            .GroupBy((order, user) => new { order.WaitForPublisherId, user.Name })
            .Select((order, user) => new PublishedOrderStatisticsDto
            {
                Id = order.WaitForPublisherId,
                Name = user.Name,
                //TotalCount = SqlFunc.AggregateCount(order.Id),
                WaitCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.Status == EOrderStatus.Filed, 1, 0)),
                PublicCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.OrderPublish.PublishState == true, 1, 0)),
                PrivateCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.OrderPublish.PublishState == false, 1, 0))
            });

        var total = 0;
        var items = new List<PublishedOrderStatisticsDto>();
        if (isFull)
        {
            items = await query.ToListAsync();
        }
        else
        {
            (total, items) = await query.ToPagedListAsync(dto.PageIndex, dto.PageSize);
        }

        var res = (from t1 in items
                   join t2 in orders on t1.Name equals t2.Name into t1_t2
                   from item in t1_t2.DefaultIfEmpty()
                   select new PublishedOrderStatisticsDto
                   {
                       Name = t1.Name,
                       PublishTime = t1.PublishTime,
                       WaitCount = t1_t2.Select(x => x.WaitCount).FirstOrDefault(),
                       PublicCount = t1.PublicCount,
                       PrivateCount = t1.PrivateCount
                   }).ToList();

        return (total, res);
    }

    /// <summary>
    /// 发布量统计(部门)
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="UserFriendlyException"></exception>
    public async Task<(int, IList<PublishedOrderStatisticsDto>)> QueryPublishedOrderDepartmentAsync(QueryOrderPublishStatisticsAllDto dto,
        bool isFull)
    {
        var total = 0;
        var items = new List<PublishedOrderStatisticsDto>();

        var orders = await _orderRepository.Queryable()
            .Where(order => order.ActualHandleOrgName != null)
            .GroupBy(order => new { Name = order.ActualHandleOrgName })
            .Select(order => new PublishedOrderStatisticsDto
            {
                Name = order.ActualHandleOrgName,
                WaitCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.Status == EOrderStatus.Filed, 1, 0)),
            }).ToListAsync();

        var query = _orderRepository.Queryable()
            .Includes(order => order.OrderPublish)
            .Where(order => order.OrderPublish.CreationTime >= dto.StartTime && order.OrderPublish.CreationTime <= dto.EndTime &&
                            order.ActualHandleOrgName != null)
            .GroupBy(order => new { Name = order.ActualHandleOrgName, PublishTime = order.CreationTime.ToString("YYYY-MM-DD") })
            .Select(order => new PublishedOrderStatisticsDto
            {
                Name = order.ActualHandleOrgName,
                PublishTime = order.CreationTime.ToString("YYYY-MM-DD"),
                // TotalCount = SqlFunc.AggregateCount(order.Id),
                WaitCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.Status == EOrderStatus.Filed, 1, 0)),
                PublicCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.OrderPublish.PublishState == true, 1, 0)),
                PrivateCount = SqlFunc.AggregateSum(SqlFunc.IIF(order.OrderPublish.PublishState == false, 1, 0))
            });
        if (isFull)
        {
            items = await query.ToListAsync();
        }
        else
        {
            (total, items) = await query.ToPagedListAsync(dto.PageIndex, dto.PageSize);
        }

        var res = (from t1 in items
                   join t2 in orders on t1.Name equals t2.Name into t1_t2
                   from item in t1_t2.DefaultIfEmpty()
                   select new PublishedOrderStatisticsDto
                   {
                       Name = t1.Name,
                       PublishTime = t1.PublishTime,
                       WaitCount = t1_t2.Select(x => x.WaitCount).FirstOrDefault(),
                       PublicCount = t1.PublicCount,
                       PrivateCount = t1.PrivateCount
                   }).ToList();

        return (total, res);
    }

    /// <summary>
    /// 回访来源统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task<IList<OrderVisitSourceChannelDto>> QueryOrderVisitSourceChannelAsync(QueryOrderVisitSourceChannelDto dto)
    {
        var result = await _orderVisitRepository.Queryable()
            .LeftJoin<Order>((visit, order) => order.Id == visit.OrderId)
            .Where((visit, order) => visit.VisitTime >= dto.StartTime && visit.VisitTime <= dto.EndTime)
            .Where((visit, order) => visit.VisitState == EVisitState.Visited)
            .GroupBy((visit, order) => new { order.SourceChannel })
            .Select((visit, order) => new OrderVisitSourceChannelDto
            {
                Count = SqlFunc.AggregateCount(visit.OrderId),
                SourceChannel = order.SourceChannel
            })
            .ToListAsync();
        return result;
    }

    /// <summary>
    /// 工单回访
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task OrderVisitWeb(OrderVisitWebDto dto, CancellationToken cancellationToken)
    {
        var visit = await _orderVisitRepository.Queryable()
            .Includes(x => x.Order)
            .Includes(x => x.OrderVisitDetails)
            .FirstAsync(x => x.Id == dto.Id);
        if (visit != null)
        {
            var first = dto.OrderVisitDetailDto.FirstOrDefault(x => x.VisitTarget == EVisitTarget.Org);

            if (first != null)
            {
                visit.NowEvaluate = first.OrgProcessingResults;
                visit.Order.Visited(first.OrgProcessingResults.Key, first.OrgProcessingResults.Value);
            }

            visit.VisitState = EVisitState.Visited;
            visit.VisitTime = dto.VisitTime;
            visit.VisitType = dto.VisitType;

            for (int i = 0; i < visit.OrderVisitDetails.Count; i++)
            {
                var detail = visit.OrderVisitDetails[i];
                var detaildto = dto.OrderVisitDetailDto.FirstOrDefault(x => x.Id == detail.Id);
                if (detaildto != null)
                {
                    _mapper.Map(detaildto, visit.OrderVisitDetails[i]);
                }
            }

            var seat = visit.OrderVisitDetails.FirstOrDefault(x => x.VisitTarget == EVisitTarget.Seat);
            seat.SeatEvaluate = ESeatEvaluate.DefaultSatisfied;
            seat.VoiceEvaluate = EVoiceEvaluate.DefaultSatisfied;

            await _orderVisitRepository.UpdateAsync(visit, cancellationToken);
            await _orderVisitDetailRepository.UpdateRangeAsync(visit.OrderVisitDetails, cancellationToken);
            await _orderVisitedDetailRepository.UpdateAsync(seat, cancellationToken);
            await _orderRepository.UpdateAsync(visit.Order, cancellationToken);
            var orderDto = _mapper.Map<OrderDto>(visit.Order);
            if (first != null)
            {
                //推省上
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderVisited,
                    new PublishVisitDto()
                    {
                        Order = orderDto,
                        No = visit.No,
                        VisitType = visit.VisitType,
                        VisitName = visit.CreatorName,
                        VisitTime = visit.VisitTime,
                        VisitRemark = string.IsNullOrEmpty(first.VisitContent) ? first.OrgProcessingResults?.Value : first.VisitContent,
                        AreaCode = visit.Order.AreaCode!,
                        SubjectResultSatifyCode = first.OrgProcessingResults.Key,
                        FirstSatisfactionCode = visit.Order.FirstVisitResultCode!,
                        ClientGuid = ""
                    }, cancellationToken: cancellationToken);
            }

            //写入质检
            await _qualityApplication.AddQualityAsync(EQualitySource.Visit, orderDto.Id, visit.Id,
                cancellationToken);
        }
    }

    /// <summary>
    /// 保存工单办理时页面填写的数据
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<Order> SaveOrderWorkflowInfo(NextWorkflowDto<OrderHandleFlowDto> dto, CancellationToken cancellationToken)
    {
        var order = await _orderRepository.Queryable().Includes(d => d.OrderExtension)
                        .FirstAsync(d => d.Id == dto.Data.OrderId, cancellationToken)
                    ?? throw UserFriendlyException.SameMessage("无效工单编号");
        if (await _orderSendBackAuditRepository.AnyAsync(x => x.OrderId == order.Id && x.State == ESendBackAuditState.Apply,
                cancellationToken))
        {
            throw UserFriendlyException.SameMessage("该工单存在正在审核中的退回，不能办理");
        }

        if (await _orderSpecialRepository.AnyAsync(x => x.OrderId == order.Id && x.State == 0,
                cancellationToken))
        {
            throw UserFriendlyException.SameMessage("该工单存在正在审核中的特提，不能办理");
        }

        ExpiredTimeWithConfig? expiredTimeConfig = null;
        var settingBase = _systemSettingCacheManager.GetSetting(SettingConstants.CityBaseConfiguration)?.SettingValue[0];
        CityBaseConfiguration cityBase = System.Text.Json.JsonSerializer.Deserialize<CityBaseConfiguration>(settingBase);
        if (dto.Workflow.NextHandlers.Any(d => d.Key == cityBase.CityProvince.OrgId || d.Key == cityBase.CityProvinceAssign.OrgId))
        {
            if (dto.Workflow.NextHandlers.Any(d => d.Key == cityBase.CityProvince.OrgId) && order.OrderExtension is null)
            {
                throw UserFriendlyException.SameMessage("该工单不存在拓展信息,不能推送至全国12315平台!");
            }

            var startTime = order.CenterToOrgTime ?? DateTime.Now;

            TimeResult? timeResult;
            if (_appOptions.Value.IsLuZhou)
            {
                timeResult = await _expireTime.CalcEndTime(DateTime.Now, startTime, ETimeType.Day, 60, 70, 50);
                expiredTimeConfig = new ExpiredTimeWithConfig
                {
                    Count = 60,
                    TimeType = ETimeType.Day,
                    TimeText = "60个自然日",
                    ExpiredTime = timeResult.EndTime,
                    NearlyExpiredTime = timeResult.NearlyExpiredTime,
                    NearlyExpiredTimeOne = timeResult.NearlyExpiredTimeOne
                };
            }
            else if (_appOptions.Value.IsZiGong)
            {
                timeResult = await _expireTime.CalcEndTime(DateTime.Now, startTime, ETimeType.WorkDay, 5, 80, 50);
                expiredTimeConfig = new ExpiredTimeWithConfig
                {
                    Count = 5,
                    TimeType = ETimeType.WorkDay,
                    TimeText = "5个工作日",
                    ExpiredTime = timeResult.EndTime,
                    NearlyExpiredTime = timeResult.NearlyExpiredTime,
                    NearlyExpiredTimeOne = timeResult.NearlyExpiredTimeOne
                };
            }
            else if (_appOptions.Value.IsYiBin)
            {
                timeResult = await _expireTime.CalcEndTime(DateTime.Now, startTime, ETimeType.WorkDay, 45, 80, 50);
                expiredTimeConfig = new ExpiredTimeWithConfig
                {
                    Count = 45,
                    TimeType = ETimeType.WorkDay,
                    TimeText = "45个工作日",
                    ExpiredTime = timeResult.EndTime,
                    NearlyExpiredTime = timeResult.NearlyExpiredTime,
                    NearlyExpiredTimeOne = timeResult.NearlyExpiredTimeOne
                };
            }
            else
            {
                throw new UserFriendlyException("暂不支持该方案");
            }

            var canUpdateOrderSender = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.CanUpdateOrderSender).SettingValue[0]);
            order.CenterToOrg(
                expiredTimeConfig.TimeText, expiredTimeConfig.Count,
                expiredTimeConfig.TimeType, expiredTimeConfig.ExpiredTime,
                expiredTimeConfig.NearlyExpiredTime, expiredTimeConfig.NearlyExpiredTimeOne, dto.Workflow.Opinion,
                _sessionContext.RequiredUserId, _sessionContext.UserName,
                canUpdateOrderSender);
            //TODO发送短信即将超期
            //_capPublisher.PublishDelay(expiredTimeConfig.NearlyExpiredTime - DateTime.Now, EventNames.HotlineOrderNearlyExpiredTimeSms, new PublishNearlyExpiredTimeSmsDto() { OrderId = order.Id });
            ////自动延期订阅
            //var enabled = _systemSettingCacheManager.GetSetting(SettingConstants.EnabledAutomaticDelay)?.SettingValue[0];
            //if (bool.Parse(enabled))
            //{
            //    //自动延期催办短信发送
            //    await _capPublisher.PublishDelayAsync(expiredTimeConfig.ExpiredTime - DateTime.Now.AddHours(2),
            //        EventNames.HotlineOrderAutomaticSendSmsDelay, new PublishAutomaticDelayDto() { OrderId = order.Id }, cancellationToken: cancellationToken);

            //    await _capPublisher.PublishDelayAsync(
            //        expiredTimeConfig.ExpiredTime - DateTime.Now.AddHours(1),
            //        EventNames.HotlineOrderAutomaticDelay,
            //        new PublishAutomaticDelayDto() { OrderId = order.Id },
            //        cancellationToken: cancellationToken);
            //}
        }
        else if (dto.Workflow.FlowDirection is EFlowDirection.CenterToOrg)
        {
            if (_appOptions.Value.IsLuZhou)
            {
                expiredTimeConfig = await _expireTime.CalcEndTime(DateTime.Now, DateTime.Now,
                    new TimeConfig() { Count = dto.Data.TimeLimit, TimeType = dto.Data.TimeLimitUnit.Value }, order.AcceptTypeCode);
            }
            else
            {
                expiredTimeConfig =
                    await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToOrg, order.Adapt<OrderTimeClacInfo>());
            }

            var canUpdateOrderSender = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.CanUpdateOrderSender).SettingValue[0]);
            order.CenterToOrg(
                expiredTimeConfig.TimeText, expiredTimeConfig.Count,
                expiredTimeConfig.TimeType, expiredTimeConfig.ExpiredTime,
                expiredTimeConfig.NearlyExpiredTime, expiredTimeConfig.NearlyExpiredTimeOne, dto.Workflow.Opinion,
                _sessionContext.RequiredUserId, _sessionContext.UserName,
                canUpdateOrderSender);
            //TODO发送短信即将超期
            //_capPublisher.PublishDelay(expiredTimeConfig.NearlyExpiredTime - DateTime.Now, EventNames.HotlineOrderNearlyExpiredTimeSms, new PublishNearlyExpiredTimeSmsDto() { OrderId = order.Id });
            //自动延期订阅
            //var enabled = _systemSettingCacheManager.GetSetting(SettingConstants.EnabledAutomaticDelay)?.SettingValue[0];
            //if (bool.Parse(enabled))
            //{
            //    //自动延期催办短信发送
            //    await _capPublisher.PublishDelayAsync(expiredTimeConfig.ExpiredTime - DateTime.Now.AddHours(2),
            //        EventNames.HotlineOrderAutomaticSendSmsDelay, new PublishAutomaticDelayDto() { OrderId = order.Id }, cancellationToken: cancellationToken);

            //    _capPublisher.PublishDelay(expiredTimeConfig.ExpiredTime - DateTime.Now.AddHours(1), EventNames.HotlineOrderAutomaticDelay,
            //        new PublishAutomaticDelayDto() { OrderId = order.Id });
            //}
        }
        else if (dto.Workflow.FlowDirection is EFlowDirection.CenterToCenter)
        {
            if (_appOptions.Value.IsZiGong == false)
            {
                expiredTimeConfig = await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToCenter,
                    order.Adapt<OrderTimeClacInfo>());
                order.CenterToCenter(expiredTimeConfig.TimeText, expiredTimeConfig.Count,
                    expiredTimeConfig.TimeType, expiredTimeConfig.ExpiredTime, expiredTimeConfig.NearlyExpiredTime,
                    expiredTimeConfig.NearlyExpiredTimeOne);
                //TODO发送短信即将超期
                //_capPublisher.PublishDelay(expiredTimeConfig.NearlyExpiredTime - DateTime.Now, EventNames.HotlineOrderNearlyExpiredTimeSms, new PublishNearlyExpiredTimeSmsDto() { OrderId = order.Id });
                //自动延期订阅
                //var enabled = _systemSettingCacheManager.GetSetting(SettingConstants.EnabledAutomaticDelay)?.SettingValue[0];
                //if (bool.Parse(enabled))
                //{
                //    //自动延期催办短信发送
                //    await _capPublisher.PublishDelayAsync(expiredTimeConfig.ExpiredTime - DateTime.Now.AddHours(2),
                //        EventNames.HotlineOrderAutomaticSendSmsDelay, new PublishAutomaticDelayDto() { OrderId = order.Id }, cancellationToken: cancellationToken);

                //    _capPublisher.PublishDelay(expiredTimeConfig.ExpiredTime - DateTime.Now.AddHours(1), EventNames.HotlineOrderAutomaticDelay,
                //        new PublishAutomaticDelayDto() { OrderId = order.Id });
                //}
            }
        }
        else if (dto.Workflow.FlowDirection is EFlowDirection.CenterToFile) //中心直接归档，中心意见为实际办理意见
        {
            order.CenterToOrgOpinion = dto.Workflow.Opinion;
            await _orderRepository.UpdateAsync(order, cancellationToken);
        }

        //更新会签状态
        if (_appOptions.Value.IsZiGong)
        {
            if (dto.Workflow.FlowDirection == EFlowDirection.CenterToOrg)
            {
                order.CounterSignType = dto.Workflow.NextHandlers.Count > 1 ? ECounterSignType.Center : null;
            }
            else if (dto.Workflow.FlowDirection == EFlowDirection.OrgToOrg)
            {
                order.CounterSignType = dto.Workflow.NextHandlers.Count > 1 ? ECounterSignType.Department : null;
            }
        }


        if (dto.Data.LeaderSMSKey != null)
        {
            var dic = _sysDicDataCacheManager.LeaderSMS.First(m => m.Id == dto.Data.LeaderSMSKey);
            _capPublisher.Publish(EventNames.HotlineLeaderSMS, new PublishLeaderSMSDto(order.Id, dic.DicDataName, dic.DicDataValue));
        }

        _mapper.Map(dto.Data, order);

        if (expiredTimeConfig is not null)
            _mapper.Map(expiredTimeConfig, order);

        await _orderRepository.UpdateAsync(order, cancellationToken);

        return order;
    }

    /// <summary>
    /// 回访保存
    /// 调用本方法前, 先调用 _callApplication.GetOrSetCallIdAsync 转换 CallId
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task SaveOrderVisit(VisitDto dto, CancellationToken cancellationToken)
    {
        var visit = await _orderVisitRepository.Queryable()
            .Includes(d => d.Order)
            .Includes(d => d.OrderVisitDetails)
            .FirstAsync(d => d.Id == dto.Id, cancellationToken);
        if (visit is null)
            throw UserFriendlyException.SameMessage("未知回访信息");

        if (_appOptions.Value.IsYiBin && visit.VisitState == EVisitState.Visited)
            throw UserFriendlyException.SameMessage("已回访，不能重复回访");

        bool exisNoSatisfiedSeat = false;
        bool exisNoSatisfiedOrg = false;


        //是否观察件
        if (dto.IsObservationPiece.HasValue && dto.IsObservationPiece.Value == true)
        {
            Hotline.Orders.ObservationPiece observationPiece = new Hotline.Orders.ObservationPiece
            {
                No = visit.No,
                OrderId = visit.OrderId,
                ObserveOrgId = visit.Order.ActualHandleOrgCode,
                State = EDelayState.Examining
            };
            await _observationPieceRepository.AddAsync(observationPiece, cancellationToken);
        }

        //记录修改历史
        try
        {
            if (dto.IsUpdate.HasValue && dto.IsUpdate == true)
            {
                if (visit.OrderVisitDetails != null && visit.OrderVisitDetails.Count > 0)
                {
                    var guid = Guid.NewGuid().ToString();
                    var visitDetailsCopy = _mapper.Map<List<OrderVisitDetailCopy>>(visit.OrderVisitDetails);
                    foreach (var item in visitDetailsCopy)
                    {
                        item.BacthId = guid;
                    }
                    await _orderVisitDetailCopyRepository.AddRangeAsync(visitDetailsCopy, cancellationToken);
                    visit.IsUpdate = true;
                }

                //#  再次回访处理之前的甄别记录
                //## 若用户将语音评价结果修改为了满意，此时甄别类型为中心话务甄别的工单，需从甄别待审批中删除；部门办件甄别的工单需保留
                if (visit.OrderVisitDetails != null && visit.OrderVisitDetails.Count > 0)
                {
                    // 坐席
                    // 判断老数据是否是不满意
                    var visitDataSeat = visit.OrderVisitDetails.Where(x => x.VisitTarget == EVisitTarget.Seat).FirstOrDefault();
                    if (visitDataSeat != null)
                    {
                        if (visitDataSeat.VoiceEvaluate == EVoiceEvaluate.NoSatisfied ||
                            visitDataSeat.VoiceEvaluate == EVoiceEvaluate.VeryNoSatisfied)
                        {
                            exisNoSatisfiedSeat = true;
                        }
                    }

                    // 部门
                    // 判断老数据是否是不满意
                    var visitDataOrg = visit.OrderVisitDetails.Where(x => x.VisitTarget == EVisitTarget.Org).FirstOrDefault();
                    if (visitDataOrg != null)
                    {
                        if (visitDataOrg.OrgProcessingResults?.Value == "不满意" ||
                            visitDataOrg.OrgProcessingResults?.Value == "非常不满意")
                        {
                            exisNoSatisfiedOrg = true;
                        }
                    }
                }
            }
        }
        catch (Exception)
        { }

        var first = dto.VisitDetails.FirstOrDefault(x => x.VisitTarget == EVisitTarget.Org);

        visit.IsPutThrough = dto.IsPutThrough;
        visit.AgainState = dto.IsAgain ? EAgainState.NeedAgain : EAgainState.NoAgain;
        //任务 314 关于修改回访结果后回访人更新的问题
        if (_appOptions.Value.IsZiGong == true)
        {
            if (string.IsNullOrEmpty(visit.EmployeeId))
                visit.EmployeeId = _sessionContext.UserId;
        }
        else
        {
            visit.EmployeeId = _sessionContext.UserId;
        }

        visit.CallId = dto.CallId;
        if (first != null)
        {
            visit.NowEvaluate = first.OrgProcessingResults;
        }

        visit.VisitState = Share.Enums.Order.EVisitState.Visited;
        visit.VisitTime = DateTime.Now;
        if (!string.IsNullOrEmpty(visit.CallId))
        {
            visit.VisitType = EVisitType.CallVisit;
        }

        if (visit.VisitType is null)
        {
            visit.VisitType = EVisitType.ArtificialVisit;
        }

        if (first != null)
        {
            visit.Order.Visited(first.OrgProcessingResults.Key, first.OrgProcessingResults.Value);
        }

        visit.OrgJudge = dto.OrgJudge;
        visit.SeatJudge = dto.SeatJudge;

        if (visit.OrgJudge == true || visit.SeatJudge == true)
        {
            visit.JudgeState = EJudgeState.Judging;
        }

        for (int i = 0; i < visit.OrderVisitDetails.Count; i++)
        {
            var detail = visit.OrderVisitDetails[i];
            var detaildto = dto.VisitDetails.FirstOrDefault(x => x.Id == detail.Id);
            if (detaildto != null)
            {
                if (visit.Order.SourceChannelCode != "RGDH" && detaildto.VisitTarget == EVisitTarget.Seat)
                {
                    detaildto.SeatEvaluate = ESeatEvaluate.DefaultSatisfied;
                }

                _mapper.Map(detaildto, visit.OrderVisitDetails[i]);
                //计算甄别提起时限
                visit.OrderVisitDetails[i].ScreenByEndTime = await _orderDomainService.GetScreenByEndTime();
            }
        }
        if (dto.IsTransact.HasValue && dto.IsTransact.Value)
        {
            visit.Order.VisitReTransactNum = visit.Order.VisitReTransactNum is null ? 1 : visit.Order.VisitReTransactNum + 1;
        }

        await _orderVisitRepository.UpdateAsync(visit, cancellationToken);
        await _orderVisitedDetailRepository.UpdateRangeAsync(visit.OrderVisitDetails, cancellationToken);
        await _orderRepository.UpdateAsync(visit.Order, cancellationToken);

        //handle visit trace
        //上面取得当前操作人，需求变动前暂时可以这样写
        var visitor = new Share.Dtos.FlowEngine.UserInfo(
            _sessionContext.UserId,
            _sessionContext.UserName,
            _sessionContext.OrgId,
            _sessionContext.OrgName);
        await _workflowDomainService.HandleVisitTraceAsync(visit.Id, visitor, visit.VisitTime ?? DateTime.Now, cancellationToken);

        var isOpenSendEndSms = _systemSettingCacheManager.GetSetting(SettingConstants.IsOpenSendEndSms)?.SettingValue[0];
        if (isOpenSendEndSms == "true")
        {
            try
            {
                if (_appOptions.Value.IsZiGong)
                {
                    if (visit.Order.Source != ESource.ProvinceStraight)
                    {
                        if (visit.Order.FileOrgIsCenter.Value == false || (visit.Order.FileOrgIsCenter.Value == true && visit.Order.CounterSignType != null))
                        {
                            //发送查询短信
                            var messageDto = new Share.Dtos.Push.MessageDto
                            {
                                PushBusiness = EPushBusiness.SearchSms,
                                ExternalId = visit.Id,
                                OrderId = visit.Order.Id,
                                PushPlatform = EPushPlatform.Sms,
                                Remark = visit.Order.Title,
                                Name = visit.Order.FromName,
                                TemplateCode = "1021",
                                Params = new List<string>() { visit.Order.No, visit.Order.Password },
                                TelNumber = visit.Order.Contact,
                            };
                            await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        var orderDto = _mapper.Map<OrderDto>(visit.Order);
        if (first != null)
        {
            //推省上
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderVisited,
                new PublishVisitDto()
                {
                    Order = orderDto,
                    No = visit.No,
                    VisitType = visit.VisitType,
                    VisitName = visit.CreatorName,
                    VisitTime = visit.VisitTime,
                    VisitRemark = string.IsNullOrEmpty(first.VisitContent) ? first.OrgProcessingResults?.Value : first.VisitContent,
                    AreaCode = visit.Order.AreaCode!,
                    SubjectResultSatifyCode = first.OrgProcessingResults.Key,
                    FirstSatisfactionCode = visit.Order.FirstVisitResultCode!,
                    ClientGuid = ""
                }, cancellationToken: cancellationToken);

            //推门户
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderVisitedWeb, new PublishVisitAllDto()
            {
                Id = visit.Id,
                Order = orderDto,
                OrderVisitDetails = _mapper.Map<List<VisitDetailDto>>(visit.OrderVisitDetails),
                VisitName = _sessionContext.UserName,
                VisitTime = visit.VisitTime,
                VisitType = visit.VisitType,
                VisitState = visit.VisitState,
                PublishTime = visit.PublishTime,
            }, cancellationToken: cancellationToken);
        }

        try
        {
            if (_appOptions.Value.IsZiGong == true)
            {
                //#  再次回访处理之前的甄别记录
                //## 若用户将语音评价结果修改为了满意，此时甄别类型为中心话务甄别的工单，需从甄别待审批中删除；部门办件甄别的工单需保留
                if (dto.IsUpdate.HasValue && dto.IsUpdate == true)
                {
                    // 坐席
                    // 判断老数据是否是不满意
                    if (exisNoSatisfiedSeat)
                    {
                        // 判断更新数据是否是满意
                        var visitData = dto.VisitDetails.Where(x => x.VisitTarget == EVisitTarget.Seat).FirstOrDefault();
                        if (visitData != null)
                        {
                            if (visitData.VoiceEvaluate != EVoiceEvaluate.NoSatisfied &&
                                visitData.VoiceEvaluate != EVoiceEvaluate.VeryNoSatisfied &&
                                visitData.SeatEvaluate != ESeatEvaluate.NoSatisfied &&
                                visitData.SeatEvaluate != ESeatEvaluate.VeryNoSatisfied)
                            {
                                await _orderScreenRepository.RemoveAsync(x => x.VisitId == visitData.VisitId);
                            }
                        }
                    }

                    // 部门
                    // 判断老数据是否是不满意
                    if (exisNoSatisfiedOrg)
                    {
                        // 判断更新数据是否是满意
                        var visitData = dto.VisitDetails.Where(x => x.VisitTarget == EVisitTarget.Org).FirstOrDefault();
                        if (visitData != null)
                        {
                            if (visitData.OrgProcessingResults != null)
                            {
                                if (visitData.OrgProcessingResults.Value != "非常不满意" &&
                                    visitData.OrgProcessingResults.Value != "不满意")
                                {
                                    await _orderScreenRepository.RemoveAsync(x => x.VisitId == visitData.VisitId);
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception)
        { }

        if (first != null)
        {
            //写入质检
            await _qualityApplication.AddQualityAsync(EQualitySource.Visit, visit.Order.Id, visit.Id, cancellationToken);

            if (_appOptions.Value.IsZiGong == true)
            {
                //回访成功后，写入回访记录信息
                await _orderVisitApplication.AddOrderVisitRecordAsync(new OrderVisitRecordDto()
                {
                    No = visit.No,
                    OrderId = visit.OrderId,
                    VisitType = visit.VisitType,
                    EmployeeId = visit.EmployeeId,
                    VisitTime = visit.VisitTime
                }, cancellationToken);

                //回访成功后结果不满意发送甄别提醒短信
                var isSendDissatisfiedScreenSms = _systemSettingCacheManager.IsSendDissatisfiedScreenSms;
                if (isSendDissatisfiedScreenSms)
                {
                    try
                    {
                        if (first.VisitOrgCode != OrgSeedData.CenterId &&
                            (first.OrgProcessingResults.Value == "不满意" || first.OrgProcessingResults.Value == "非常不满意"))
                        {
                            var roleJingBanRen = _systemSettingCacheManager.GetSetting(SettingConstants.AcceptSmsRoleIds)?.SettingValue;
                            var userList = await _userRepository
                                            .Queryable()
                                            .Where(d => d.OrgId == first.VisitOrgCode &&
                                                   d.Roles.Any(x => roleJingBanRen.Contains(x.Id)) &&
                                                   string.IsNullOrEmpty(d.PhoneNo) == false)
                                            .ToListAsync();

                            foreach (var item in userList)
                            {
                                var messageDto = new Share.Dtos.Push.MessageDto
                                {
                                    PushBusiness = EPushBusiness.DissatisfiedScreen,
                                    ExternalId = first.VisitId,
                                    OrderId = visit.Order.Id,
                                    PushPlatform = EPushPlatform.Sms,
                                    Remark = visit.Order.Title,
                                    Name = item.Name,
                                    TemplateCode = "1020",
                                    Params = new List<string>() { visit.Order.No },
                                    TelNumber = item.PhoneNo,
                                };
                                await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
    }

    /// <summary>
    /// 发送回访短信
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task VisitPushSMSAsync(VisitSmsInDto dto, CancellationToken cancellationToken)
    {
        var orderVisitList = await _orderVisitRepository.Queryable()
            .Includes(d => d.Order)
            .Where(d => dto.Ids.Contains(d.Id) && (d.VisitState == EVisitState.WaitForVisit || d.VisitState == EVisitState.NoSatisfiedWaitForVisit || d.VisitState == EVisitState.SMSUnsatisfied))
            .Select(d => new { d.Id, d.Order.SourceChannelCode, d.Order.Contact, d.Order.Password, d.No, d.OrderId, d.Order.Title, d.Order.FromName })
            .ToListAsync(cancellationToken);

        foreach (var item in orderVisitList)
        {
            var code = "1013";
            if (_systemSettingCacheManager.Snapshot && item.SourceChannelCode == "ZGSSP")
            {
                await _orderSnapshotRepository.Queryable().Where(m => m.Id == item.OrderId)
                    .Select(m => m.IndustryName)
                    .FirstAsync()
                    .Then(name => 
                    {
                        if (name.Trim() == "电气焊作业申报") code = "1012";
                    });
            }
            var messageDto = new Share.Dtos.Push.MessageDto
            {
                PushBusiness = EPushBusiness.VisitSms,
                ExternalId = item.Id,
                OrderId = item.OrderId,
                PushPlatform = EPushPlatform.Sms,
                Remark = item.Title,
                Name = item.FromName,
                TemplateCode = code,
                Params = new List<string>() { item.No, item.Password },
                TelNumber = item.Contact,
            };
            await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
            await _orderVisitRepository.Updateable()
                .Where(m => m.Id == item.Id)
                .SetColumns(m => m.VisitState == EVisitState.SMSVisiting)
                //.SetColumns(m => m.IsPutThrough == true)
                .SetColumns(m => m.EmployeeId == _sessionContext.RequiredUserId)
                .ExecuteCommandAsync(cancellationToken);

            // 发送短信后推送一个 48小时的延迟消息队列. 当消息队列收到消息时, 判断用户是否回复了, 如果未回复短信就 默认满意
            var delaySecond = _systemSettingCacheManager.DefaultVisitSmsDelaySecond;
            await _capPublisher.PublishDelayAsync(
                TimeSpan.FromSeconds(delaySecond),
                EventNames.UpdateVisitDelaySms,
                messageDto,
                cancellationToken: cancellationToken);
        }
    }

    //public async Task<List<OrderDto>> QueryOrdersAsync(QueryOrderDto dto, int queryIndex)
    //{
    //    var query = QueryOrders(dto);
    //    var items = await query.ToFixedListAsync(queryIndex);

    //    var dtoItems = new List<OrderDto>();
    //    foreach (var item in items)
    //    {
    //        var orderDto = item.Adapt<OrderDto>();
    //        var visitEntity = item.OrderVisits
    //                        .OrderByDescending(m => m.CreationTime)
    //                        .FirstOrDefault();
    //        if (visitEntity != null)
    //        {
    //            var now = visitEntity?.NowEvaluate;
    //            if (now != null) 
    //            {
    //                orderDto.OrgEvaluate = now;
    //                orderDto.OrgEvaluateValue = now.Value;
    //            }
    //            orderDto.SeatEvaluate = visitEntity.OrderVisitDetails.Where(m => m.VisitTarget == EVisitTarget.Seat)
    //                .FirstOrDefault()?.SeatEvaluate;
    //        }

    //        orderDto.OrderVisits = null;
    //        dtoItems.Add(orderDto);
    //    }
    //    return dtoItems;
    //}

    public ISugarQueryable<Order> QueryOrders(QueryOrderDto dto)
    {
        var isCenter = _sessionContext.OrgIsCenter;

        var query = _orderRepository.Queryable(canView: false);
        if (!isCenter)
        {
            query.Where(d => SqlFunc.Subqueryable<WorkflowStep>()
                .Where(step => step.ExternalId == d.Id &&
                               !string.IsNullOrEmpty(step.HandlerOrgId) &&
                               step.HandlerOrgId.StartsWith(_sessionContext.RequiredOrgId)).Any());
        }

        query = query.Includes(d => d.OrderScreens).Includes(d => d.OrderTags);

        //if (!_appOptions.Value.IsYiBin)
        //{
        //    query = query.Includes(x => x.OrderVisits.Where(m => m.VisitState == EVisitState.Visited).ToList())
        // .Includes(x => x.OrderVisits.Where(m => m.VisitState == EVisitState.Visited).ToList(), ovd => ovd.OrderVisitDetails);
        //}

        query = query
                .WhereIF(!string.IsNullOrEmpty(dto.PoliticalIdentityValue), d => d.PoliticalIdentityValue == dto.PoliticalIdentityValue)//政治身份查询
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.Contains(dto.Keyword!)) //标题
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceNo), d => d.ProvinceNo.Contains(dto.ProvinceNo)) //省本地编号
                .WhereIF(!string.IsNullOrEmpty(dto.ReceiveProvinceNo), d => d.ReceiveProvinceNo.Contains(dto.ReceiveProvinceNo)) //省编号
                .WhereIF(dto.IsSecret.HasValue, d => d.IsSecret == dto.IsSecret.Value)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value, d => d.ReTransactNum > 0)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value == false, d => d.ReTransactNum == null || d.ReTransactNum == 0)
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No)) //工单编码
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
                                                                                                         //.WhereIF(dto.AcceptTypes.Any(), d => dto.AcceptTypes.Contains(d.AcceptTypeCode)) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.SourceChannelCode == dto.Channel)
                //.WhereIF(dto.Channels.Any(), d => dto.Channels.Contains(d.SourceChannelCode)) //来源渠道
                //.WhereIF(dto.HotspotIds.Any(), d => dto.HotspotIds.Contains(d.HotspotId)) //热点类型
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.Hotspot))
                .WhereIF(!string.IsNullOrEmpty(dto.TransferPhone), d => d.TransferPhone == dto.TransferPhone!) //转接号码
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => d.Workflow.Assigns.Any(s => dto.OrgCodes.Contains(s.OrgCode)))
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => dto.OrgCodes.Contains(d.ActualHandleOrgCode)) //接办部门
                                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrgId), d => d.CurrentHandleOrgId == dto.OrgId)//接办部门
                .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgCode), d => d.ActualHandleOrgCode.StartsWith(dto.ActualHandleOrgCode)) //接办部门（综合查询模糊）
                .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo), d => d.AcceptorName == dto.NameOrNo! || d.AcceptorStaffNo == dto.NameOrNo!) //受理人/坐席
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(dto.StartTimeStart.HasValue, d => d.StartTime >= dto.StartTimeStart) //流程开启时间开始
                .WhereIF(dto.StartTimeEnd.HasValue, d => d.StartTime <= dto.StartTimeEnd) //流程开启时间结束
                                                                                          //.WhereIF(dto.EmergencyLevels.Any(), d => dto.EmergencyLevels.Contains(d.EmergencyLevel))  //紧急程度
                .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
                .WhereIF(!string.IsNullOrEmpty(dto.PhoneNo), d => d.Contact.Contains(dto.PhoneNo)) //联系电话
                                                                                                   //.WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), d => d.PushTypeCode == dto.PushTypeCode) //推送分类
                .WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), x => x.OrderPushTypes.Any(opt => opt.PushTypeCode == dto.PushTypeCode)) //推送分类
                .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
                .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
                                                                                                //.WhereIF(dto.Statuses.Any(), d => dto.Statuses.Contains(d.Status))  //工单状态
                .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status) //工单状态
                                                                           //.WhereIF(dto.Statuses.Any(d => d == EOrderStatus.SpecialToUnAccept), d => d.Status <= EOrderStatus.SpecialToUnAccept)
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName), d => d.ActualHandlerName == dto.ActualHandlerName) //接办人
                .WhereIF(dto.IsScreen == true, d => d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //有甄别
                .WhereIF(dto.IsScreen == false, d => !d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //无甄别
                .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepName), d => d.CurrentStepName == dto.CurrentStepName) //当前办理节点
                .WhereIF(dto.ActualHandleTimeStart.HasValue, d => d.FiledTime >= dto.ActualHandleTimeStart) //办结时间开始
                .WhereIF(dto.ActualHandleTimeEnd.HasValue, d => d.FiledTime <= dto.ActualHandleTimeEnd) //办结时间结束
                .WhereIF(dto.IsOverTime == true,
                    d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime < d.FiledTime && d.Status >= EOrderStatus.Filed)) //是 超期
                .WhereIF(dto.IsOverTime == false,
                    d => (d.ExpiredTime > DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime > d.FiledTime && d.Status >= EOrderStatus.Filed)) //否 超期
                .WhereIF(dto.IdentityType != null, d => d.IdentityType == dto.IdentityType) //来电主体
                .WhereIF(!string.IsNullOrEmpty(dto.FromName), d => d.FromName == dto.FromName) //来电人姓名
                                                                                               //.WhereIF(dto.AreaCodes.Any(), d => dto.AreaCodes.Contains(d.AreaCode)) //区域
                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.AreaCode), d => d.AreaCode == dto.AreaCode)//区域
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") > 0,
                    d => d.AreaCode.StartsWith(SqlFunc.Substring(dto.AreaCode, 0, 4)))
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") <= 0, d => d.AreaCode.StartsWith(dto.AreaCode))
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch != true, d => d.IsProvince == true)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false && dto.ProvinceSearch != true, d => d.IsProvince == false)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch == true, d => d.Source == ESource.ProvinceStraight)
                .WhereIF(!string.IsNullOrEmpty(dto.SensitiveWord), d => SqlFunc.JsonArrayAny(d.Sensitive, dto.SensitiveWord))
                .WhereIF(dto.IsSensitiveWord.HasValue && dto.IsSensitiveWord == true,
                    d => d.Sensitive != null && SqlFunc.JsonArrayLength(d.Sensitive) > 0)
                .WhereIF(dto.IsUrgent.HasValue, d => d.IsUrgent == dto.IsUrgent.Value)
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == false) //政民互动直派
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == true) //政民互动
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "S12345" && d.IsProvince == true) //省12345
                                                                             //.WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval),d => d.Title.Contains(dto.ContentRetrieval) || d.Content.Contains(dto.ContentRetrieval) || d.FileOpinion.Contains(dto.ContentRetrieval) || d.ActualOpinion.Contains(dto.ContentRetrieval))
                .WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval), d => d.Content.Contains(dto.ContentRetrieval!))
                .WhereIF(!string.IsNullOrEmpty(dto.FileOption), d => d.FileOpinion.Contains(dto.FileOption!))
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == true, d => d.CurrentStepAcceptTime != null)
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == false, d => d.CurrentStepAcceptTime == null)
                .WhereIF(dto.FiledType is FiledType.CenterFiled, d => d.FileOrgIsCenter == true) //d => d.ProcessType == EProcessType.Zhiban
                .WhereIF(dto.FiledType is FiledType.OrgFiled, d => d.FileOrgIsCenter == false) //d => d.ProcessType == EProcessType.Jiaoban
                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTagCode == dto.OrderTagCode)// 工单标签
                .WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTagCode)) //工单标签
                .WhereIF(!string.IsNullOrEmpty(dto.FocusOnEvents),
                    d => d.FocusOnEvents.Contains(dto.FocusOnEvents) && !d.FocusOnEvents.Contains("99")) //!string.IsNullOrEmpty(d.FocusOnEvents) && SqlFunc.SplitIn(d.FocusOnEvents, dto.FocusOnEvents))
                 .WhereIF(dto.SeatEvaluate.Any(), d => dto.SeatEvaluate.Contains(d.SeatEvaluate.Value)) //话务员评价（话务评价）
                .WhereIF(dto.OrgProcessingResults.Any(), d => dto.OrgProcessingResults.Contains(SqlFunc.JsonField(d.OrgProcessingResults, "Key")))//部门办件结果
                .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc) //默认排序时间为创建时间
                .OrderByIF(dto is { SortField: "no", SortRule: 0 }, d => d.No, OrderByType.Asc) //工单编号升序
                .OrderByIF(dto is { SortField: "no", SortRule: 1 }, d => d.No, OrderByType.Desc) //工单编号降序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 0 }, d => d.IsProvince, OrderByType.Asc) //是否省工单升序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 1 }, d => d.IsProvince, OrderByType.Desc) //是否省工单降序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 0 }, d => d.ReTransactNum, OrderByType.Asc) //重办次数升序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 1 }, d => d.ReTransactNum, OrderByType.Desc) //重办次数降序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 0 }, d => d.IsUrgent, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 1 }, d => d.IsUrgent, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 0 }, d => d.IsSecret, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 1 }, d => d.IsSecret, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 0 }, d => d.CurrentStepName, OrderByType.Asc) //当前节点升序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 1 }, d => d.CurrentStepName, OrderByType.Desc) //当前节点降序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 0 }, d => d.ActualHandleStepAcceptTime.HasValue,
                    OrderByType.Asc) //受理情况升序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 1 }, d => d.ActualHandleStepAcceptTime.HasValue,
                    OrderByType.Desc) //受理情况降序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 0 }, d => d.Status, OrderByType.Asc) //工单状态升序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 1 }, d => d.Status, OrderByType.Desc) //工单状态降序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, d => d.StartTime, OrderByType.Asc) //受理时间升序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, d => d.StartTime, OrderByType.Desc) //受理时间降序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, d => d.ExpiredTime, OrderByType.Asc) //超期时间升序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, d => d.ExpiredTime, OrderByType.Desc) //超期时间降序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, d => d.FiledTime, OrderByType.Asc) //办结时间升序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, d => d.FiledTime, OrderByType.Desc) //办结时间降序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 0 }, d => d.OrgLevelOneName, OrderByType.Asc) //一级部门升序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 1 }, d => d.OrgLevelOneName, OrderByType.Desc) //一级部门降序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 0 }, d => d.OrgLevelTwoName, OrderByType.Asc) //二级部门升序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 1 }, d => d.OrgLevelTwoName, OrderByType.Desc) //二级部门降序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 0 }, d => d.ActualHandleOrgName, OrderByType.Asc) //接办部门升序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 1 }, d => d.ActualHandleOrgName, OrderByType.Desc) //接办部门降序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 0 }, d => d.AcceptTypeCode, OrderByType.Asc) //受理类型升序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 1 }, d => d.AcceptTypeCode, OrderByType.Desc) //受理类型降序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 0 }, d => d.CounterSignType, OrderByType.Asc) //是否会签升序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 1 }, d => d.CounterSignType, OrderByType.Desc) //是否会签降序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 0 }, d => d.HotspotSpliceName, OrderByType.Asc) //热点分类全称升序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 1 }, d => d.HotspotSpliceName, OrderByType.Desc) //热点分类全称降序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 0 }, d => d.HotspotName, OrderByType.Asc) //热点分类升序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 1 }, d => d.HotspotName, OrderByType.Desc) //热点分类降序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 0 }, d => d.AcceptorName, OrderByType.Asc) //受理人升序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 1 }, d => d.AcceptorName, OrderByType.Desc) //受理人降序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 0 }, d => d.CurrentStepAcceptTime, OrderByType.Asc) //接办时间升序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 1 }, d => d.CurrentStepAcceptTime, OrderByType.Desc) //接办时间降序
            ;

        return query;
    }

    public ISugarQueryable<Order> QueryTravel(QueryOrderDto dto)
    {
        var query = _orderRepository.Queryable(canView: false);
        query = query.Includes(d => d.OrderScreens).Includes(d => d.OrderTags);

        query = query
                .Where(d => d.FocusOnEvents.Contains("7"))
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.Contains(dto.Keyword!)) //标题
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceNo), d => d.ProvinceNo.Contains(dto.ProvinceNo)) //省本地编号
                .WhereIF(!string.IsNullOrEmpty(dto.ReceiveProvinceNo), d => d.ReceiveProvinceNo.Contains(dto.ReceiveProvinceNo)) //省编号
                .WhereIF(dto.IsSecret.HasValue, d => d.IsSecret == dto.IsSecret.Value)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value, d => d.ReTransactNum > 0)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value == false, d => d.ReTransactNum == null || d.ReTransactNum == 0)
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No)) //工单编码
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
                                                                                                         //.WhereIF(dto.AcceptTypes.Any(), d => dto.AcceptTypes.Contains(d.AcceptTypeCode)) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.SourceChannelCode == dto.Channel)
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.Hotspot))
                .WhereIF(!string.IsNullOrEmpty(dto.TransferPhone), d => d.TransferPhone == dto.TransferPhone!) //转接号码
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => d.Workflow.Assigns.Any(s => dto.OrgCodes.Contains(s.OrgCode)))
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => dto.OrgCodes.Contains(d.ActualHandleOrgCode)) //接办部门
                                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrgId), d => d.CurrentHandleOrgId == dto.OrgId)//接办部门
                .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
                .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo), d => d.AcceptorName == dto.NameOrNo! || d.AcceptorStaffNo == dto.NameOrNo!) //受理人/坐席
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(dto.StartTimeStart.HasValue, d => d.StartTime >= dto.StartTimeStart) //流程开启时间开始
                .WhereIF(dto.StartTimeEnd.HasValue, d => d.StartTime <= dto.StartTimeEnd) //流程开启时间结束
                                                                                          //.WhereIF(dto.EmergencyLevels.Any(), d => dto.EmergencyLevels.Contains(d.EmergencyLevel))  //紧急程度
                .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
                .WhereIF(!string.IsNullOrEmpty(dto.PhoneNo), d => d.Contact.Contains(dto.PhoneNo)) //联系电话
                                                                                                   //.WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), d => d.PushTypeCode == dto.PushTypeCode) //推送分类
                .WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), x => x.OrderPushTypes.Any(opt => opt.PushTypeCode == dto.PushTypeCode)) //推送分类
                .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
                .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
                                                                                                //.WhereIF(dto.Statuses.Any(), d => dto.Statuses.Contains(d.Status))  //工单状态
                .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status) //工单状态
                                                                           //.WhereIF(dto.Statuses.Any(d => d == EOrderStatus.SpecialToUnAccept), d => d.Status <= EOrderStatus.SpecialToUnAccept)
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName), d => d.ActualHandlerName == dto.ActualHandlerName) //接办人
                .WhereIF(dto.IsScreen == true, d => d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //有甄别
                .WhereIF(dto.IsScreen == false, d => !d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //无甄别
                .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepCode), d => d.CurrentStepCode == dto.CurrentStepCode) //当前办理节点
                .WhereIF(dto.ActualHandleTimeStart.HasValue, d => d.FiledTime >= dto.ActualHandleTimeStart) //办结时间开始
                .WhereIF(dto.ActualHandleTimeEnd.HasValue, d => d.FiledTime <= dto.ActualHandleTimeEnd) //办结时间结束
                .WhereIF(dto.IsOverTime == true,
                    d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime < d.FiledTime && d.Status >= EOrderStatus.Filed)) //是 超期
                .WhereIF(dto.IsOverTime == false,
                    d => (d.ExpiredTime > DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime > d.FiledTime && d.Status >= EOrderStatus.Filed)) //否 超期
                .WhereIF(dto.IdentityType != null, d => d.IdentityType == dto.IdentityType) //来电主体
                .WhereIF(!string.IsNullOrEmpty(dto.FromName), d => d.FromName == dto.FromName) //来电人姓名
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") > 0,
                    d => d.AreaCode.StartsWith(SqlFunc.Substring(dto.AreaCode, 0, 4)))
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") <= 0, d => d.AreaCode.StartsWith(dto.AreaCode))
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch != true, d => d.IsProvince == true)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false && dto.ProvinceSearch != true, d => d.IsProvince == false)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch == true, d => d.Source == ESource.ProvinceStraight)
                .WhereIF(!string.IsNullOrEmpty(dto.SensitiveWord), d => SqlFunc.JsonArrayAny(d.Sensitive, dto.SensitiveWord))
                .WhereIF(dto.IsSensitiveWord.HasValue && dto.IsSensitiveWord == true,
                    d => d.Sensitive != null && SqlFunc.JsonArrayLength(d.Sensitive) > 0)
                .WhereIF(dto.IsUrgent.HasValue, d => d.IsUrgent == dto.IsUrgent.Value)
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == false) //政民互动直派
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == true) //政民互动
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "S12345" && d.IsProvince == true) //省12345
                                                                             //.WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval),d => d.Title.Contains(dto.ContentRetrieval) || d.Content.Contains(dto.ContentRetrieval) || d.FileOpinion.Contains(dto.ContentRetrieval) || d.ActualOpinion.Contains(dto.ContentRetrieval))
                .WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval), d => d.Content.Contains(dto.ContentRetrieval!))
                .WhereIF(!string.IsNullOrEmpty(dto.FileOption), d => d.FileOpinion.Contains(dto.FileOption!))
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == true, d => d.CurrentStepAcceptTime != null)
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == false, d => d.CurrentStepAcceptTime == null)
                .WhereIF(dto.FiledType is FiledType.CenterFiled, d => d.FileOrgIsCenter == true) //d => d.ProcessType == EProcessType.Zhiban
                .WhereIF(dto.FiledType is FiledType.OrgFiled, d => d.FileOrgIsCenter == false) //d => d.ProcessType == EProcessType.Jiaoban
                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTagCode == dto.OrderTagCode)// 工单标签
                .WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTagCode)) //工单标签
                .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc) //默认排序时间为创建时间
                .OrderByIF(dto is { SortField: "no", SortRule: 0 }, d => d.No, OrderByType.Asc) //工单编号升序
                .OrderByIF(dto is { SortField: "no", SortRule: 1 }, d => d.No, OrderByType.Desc) //工单编号降序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 0 }, d => d.IsProvince, OrderByType.Asc) //是否省工单升序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 1 }, d => d.IsProvince, OrderByType.Desc) //是否省工单降序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 0 }, d => d.ReTransactNum, OrderByType.Asc) //重办次数升序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 1 }, d => d.ReTransactNum, OrderByType.Desc) //重办次数降序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 0 }, d => d.IsUrgent, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 1 }, d => d.IsUrgent, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 0 }, d => d.IsSecret, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 1 }, d => d.IsSecret, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 0 }, d => d.CurrentStepName, OrderByType.Asc) //当前节点升序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 1 }, d => d.CurrentStepName, OrderByType.Desc) //当前节点降序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 0 }, d => d.ActualHandleStepAcceptTime.HasValue,
                    OrderByType.Asc) //受理情况升序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 1 }, d => d.ActualHandleStepAcceptTime.HasValue,
                    OrderByType.Desc) //受理情况降序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 0 }, d => d.Status, OrderByType.Asc) //工单状态升序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 1 }, d => d.Status, OrderByType.Desc) //工单状态降序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, d => d.StartTime, OrderByType.Asc) //受理时间升序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, d => d.StartTime, OrderByType.Desc) //受理时间降序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, d => d.ExpiredTime, OrderByType.Asc) //超期时间升序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, d => d.ExpiredTime, OrderByType.Desc) //超期时间降序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, d => d.FiledTime, OrderByType.Asc) //办结时间升序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, d => d.FiledTime, OrderByType.Desc) //办结时间降序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 0 }, d => d.OrgLevelOneName, OrderByType.Asc) //一级部门升序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 1 }, d => d.OrgLevelOneName, OrderByType.Desc) //一级部门降序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 0 }, d => d.OrgLevelTwoName, OrderByType.Asc) //二级部门升序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 1 }, d => d.OrgLevelTwoName, OrderByType.Desc) //二级部门降序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 0 }, d => d.ActualHandleOrgName, OrderByType.Asc) //接办部门升序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 1 }, d => d.ActualHandleOrgName, OrderByType.Desc) //接办部门降序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 0 }, d => d.AcceptTypeCode, OrderByType.Asc) //受理类型升序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 1 }, d => d.AcceptTypeCode, OrderByType.Desc) //受理类型降序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 0 }, d => d.CounterSignType, OrderByType.Asc) //是否会签升序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 1 }, d => d.CounterSignType, OrderByType.Desc) //是否会签降序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 0 }, d => d.HotspotSpliceName, OrderByType.Asc) //热点分类全称升序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 1 }, d => d.HotspotSpliceName, OrderByType.Desc) //热点分类全称降序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 0 }, d => d.HotspotName, OrderByType.Asc) //热点分类升序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 1 }, d => d.HotspotName, OrderByType.Desc) //热点分类降序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 0 }, d => d.AcceptorName, OrderByType.Asc) //受理人升序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 1 }, d => d.AcceptorName, OrderByType.Desc) //受理人降序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 0 }, d => d.CurrentStepAcceptTime, OrderByType.Asc) //接办时间升序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 1 }, d => d.CurrentStepAcceptTime, OrderByType.Desc) //接办时间降序
            ;

        query = query
            .Includes(x => x.OrderSupervises.OrderByDescending(d => d.CreationTime).Take(2).ToList())
            .Includes(x => x.OrderVisits.Where(q=>q.VisitState == EVisitState.Visited).Take(1).ToList(), d => d.OrderVisitDetails.Where(c => c.VisitTarget == EVisitTarget.Org).Take(1).ToList());

        return query;
    }

    public ISugarQueryable<Order> QueryEnterprise(QueryOrderDto dto)
    {
        var query = _orderRepository.Queryable(canView: false);
        query = query.Includes(d => d.OrderScreens).Includes(d => d.OrderTags);

        query = query
                .Where(d => d.IdentityType == EIdentityType.Enterprise) //来电主体
                .WhereIF(!string.IsNullOrEmpty(dto.PoliticalIdentityValue), d => d.PoliticalIdentityValue == dto.PoliticalIdentityValue)//政治身份查询
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.Contains(dto.Keyword!)) //标题
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceNo), d => d.ProvinceNo.Contains(dto.ProvinceNo)) //省本地编号
                .WhereIF(!string.IsNullOrEmpty(dto.ReceiveProvinceNo), d => d.ReceiveProvinceNo.Contains(dto.ReceiveProvinceNo)) //省编号
                .WhereIF(dto.IsSecret.HasValue, d => d.IsSecret == dto.IsSecret.Value)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value, d => d.ReTransactNum > 0)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value == false, d => d.ReTransactNum == null || d.ReTransactNum == 0)
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No)) //工单编码
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
                                                                                                         //.WhereIF(dto.AcceptTypes.Any(), d => dto.AcceptTypes.Contains(d.AcceptTypeCode)) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.SourceChannelCode == dto.Channel)
                //.WhereIF(dto.Channels.Any(), d => dto.Channels.Contains(d.SourceChannelCode)) //来源渠道
                //.WhereIF(dto.HotspotIds.Any(), d => dto.HotspotIds.Contains(d.HotspotId)) //热点类型
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.Hotspot))
                .WhereIF(!string.IsNullOrEmpty(dto.TransferPhone), d => d.TransferPhone == dto.TransferPhone!) //转接号码
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => d.Workflow.Assigns.Any(s => dto.OrgCodes.Contains(s.OrgCode)))
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => dto.OrgCodes.Contains(d.ActualHandleOrgCode)) //接办部门
                                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrgId), d => d.CurrentHandleOrgId == dto.OrgId)//接办部门
                .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
                .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo), d => d.AcceptorName == dto.NameOrNo! || d.AcceptorStaffNo == dto.NameOrNo!) //受理人/坐席
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(dto.StartTimeStart.HasValue, d => d.StartTime >= dto.StartTimeStart) //流程开启时间开始
                .WhereIF(dto.StartTimeEnd.HasValue, d => d.StartTime <= dto.StartTimeEnd) //流程开启时间结束
                                                                                          //.WhereIF(dto.EmergencyLevels.Any(), d => dto.EmergencyLevels.Contains(d.EmergencyLevel))  //紧急程度
                .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
                .WhereIF(!string.IsNullOrEmpty(dto.PhoneNo), d => d.Contact.Contains(dto.PhoneNo)) //联系电话
                                                                                                   //.WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), d => d.PushTypeCode == dto.PushTypeCode) //推送分类
                .WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), x => x.OrderPushTypes.Any(opt => opt.PushTypeCode == dto.PushTypeCode)) //推送分类
                .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
                .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
                                                                                                //.WhereIF(dto.Statuses.Any(), d => dto.Statuses.Contains(d.Status))  //工单状态
                .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status) //工单状态
                                                                           //.WhereIF(dto.Statuses.Any(d => d == EOrderStatus.SpecialToUnAccept), d => d.Status <= EOrderStatus.SpecialToUnAccept)
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName), d => d.ActualHandlerName == dto.ActualHandlerName) //接办人
                .WhereIF(dto.IsScreen == true, d => d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //有甄别
                .WhereIF(dto.IsScreen == false, d => !d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //无甄别
                .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepCode), d => d.CurrentStepCode == dto.CurrentStepCode) //当前办理节点
                .WhereIF(dto.ActualHandleTimeStart.HasValue, d => d.FiledTime >= dto.ActualHandleTimeStart) //办结时间开始
                .WhereIF(dto.ActualHandleTimeEnd.HasValue, d => d.FiledTime <= dto.ActualHandleTimeEnd) //办结时间结束
                .WhereIF(dto.IsOverTime == true,
                    d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime < d.FiledTime && d.Status >= EOrderStatus.Filed)) //是 超期
                .WhereIF(dto.IsOverTime == false,
                    d => (d.ExpiredTime > DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime > d.FiledTime && d.Status >= EOrderStatus.Filed)) //否 超期
                                                                                          //.WhereIF(dto.IdentityType != null, d => d.IdentityType == dto.IdentityType) //来电主体
                .WhereIF(!string.IsNullOrEmpty(dto.FromName), d => d.FromName == dto.FromName) //来电人姓名
                                                                                               //.WhereIF(dto.AreaCodes.Any(), d => dto.AreaCodes.Contains(d.AreaCode)) //区域
                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.AreaCode), d => d.AreaCode == dto.AreaCode)//区域
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") > 0,
                    d => d.AreaCode.StartsWith(SqlFunc.Substring(dto.AreaCode, 0, 4)))
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") <= 0, d => d.AreaCode.StartsWith(dto.AreaCode))
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch != true, d => d.IsProvince == true)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false && dto.ProvinceSearch != true, d => d.IsProvince == false)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch == true, d => d.Source == ESource.ProvinceStraight)
                .WhereIF(!string.IsNullOrEmpty(dto.SensitiveWord), d => SqlFunc.JsonArrayAny(d.Sensitive, dto.SensitiveWord))
                .WhereIF(dto.IsSensitiveWord.HasValue && dto.IsSensitiveWord == true,
                    d => d.Sensitive != null && SqlFunc.JsonArrayLength(d.Sensitive) > 0)
                .WhereIF(dto.IsUrgent.HasValue, d => d.IsUrgent == dto.IsUrgent.Value)
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == false) //政民互动直派
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == true) //政民互动
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "S12345" && d.IsProvince == true) //省12345
                                                                             //.WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval),d => d.Title.Contains(dto.ContentRetrieval) || d.Content.Contains(dto.ContentRetrieval) || d.FileOpinion.Contains(dto.ContentRetrieval) || d.ActualOpinion.Contains(dto.ContentRetrieval))
                .WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval), d => d.Content.Contains(dto.ContentRetrieval!))
                .WhereIF(!string.IsNullOrEmpty(dto.FileOption), d => d.FileOpinion.Contains(dto.FileOption!))
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == true, d => d.CurrentStepAcceptTime != null)
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == false, d => d.CurrentStepAcceptTime == null)
                .WhereIF(dto.FiledType is FiledType.CenterFiled, d => d.FileOrgIsCenter == true) //d => d.ProcessType == EProcessType.Zhiban
                .WhereIF(dto.FiledType is FiledType.OrgFiled, d => d.FileOrgIsCenter == false) //d => d.ProcessType == EProcessType.Jiaoban
                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTagCode == dto.OrderTagCode)// 工单标签
                .WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTagCode)) //工单标签
                .WhereIF(!string.IsNullOrEmpty(dto.FocusOnEvents),
                    d => d.FocusOnEvents.Contains(dto.FocusOnEvents)) //!string.IsNullOrEmpty(d.FocusOnEvents) && SqlFunc.SplitIn(d.FocusOnEvents, dto.FocusOnEvents))
                .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc) //默认排序时间为创建时间
                .OrderByIF(dto is { SortField: "no", SortRule: 0 }, d => d.No, OrderByType.Asc) //工单编号升序
                .OrderByIF(dto is { SortField: "no", SortRule: 1 }, d => d.No, OrderByType.Desc) //工单编号降序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 0 }, d => d.IsProvince, OrderByType.Asc) //是否省工单升序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 1 }, d => d.IsProvince, OrderByType.Desc) //是否省工单降序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 0 }, d => d.ReTransactNum, OrderByType.Asc) //重办次数升序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 1 }, d => d.ReTransactNum, OrderByType.Desc) //重办次数降序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 0 }, d => d.IsUrgent, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 1 }, d => d.IsUrgent, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 0 }, d => d.IsSecret, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 1 }, d => d.IsSecret, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 0 }, d => d.CurrentStepName, OrderByType.Asc) //当前节点升序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 1 }, d => d.CurrentStepName, OrderByType.Desc) //当前节点降序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 0 }, d => d.ActualHandleStepAcceptTime.HasValue,
                    OrderByType.Asc) //受理情况升序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 1 }, d => d.ActualHandleStepAcceptTime.HasValue,
                    OrderByType.Desc) //受理情况降序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 0 }, d => d.Status, OrderByType.Asc) //工单状态升序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 1 }, d => d.Status, OrderByType.Desc) //工单状态降序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, d => d.StartTime, OrderByType.Asc) //受理时间升序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, d => d.StartTime, OrderByType.Desc) //受理时间降序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, d => d.ExpiredTime, OrderByType.Asc) //超期时间升序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, d => d.ExpiredTime, OrderByType.Desc) //超期时间降序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, d => d.FiledTime, OrderByType.Asc) //办结时间升序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, d => d.FiledTime, OrderByType.Desc) //办结时间降序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 0 }, d => d.OrgLevelOneName, OrderByType.Asc) //一级部门升序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 1 }, d => d.OrgLevelOneName, OrderByType.Desc) //一级部门降序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 0 }, d => d.OrgLevelTwoName, OrderByType.Asc) //二级部门升序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 1 }, d => d.OrgLevelTwoName, OrderByType.Desc) //二级部门降序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 0 }, d => d.ActualHandleOrgName, OrderByType.Asc) //接办部门升序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 1 }, d => d.ActualHandleOrgName, OrderByType.Desc) //接办部门降序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 0 }, d => d.AcceptTypeCode, OrderByType.Asc) //受理类型升序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 1 }, d => d.AcceptTypeCode, OrderByType.Desc) //受理类型降序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 0 }, d => d.CounterSignType, OrderByType.Asc) //是否会签升序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 1 }, d => d.CounterSignType, OrderByType.Desc) //是否会签降序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 0 }, d => d.HotspotSpliceName, OrderByType.Asc) //热点分类全称升序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 1 }, d => d.HotspotSpliceName, OrderByType.Desc) //热点分类全称降序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 0 }, d => d.HotspotName, OrderByType.Asc) //热点分类升序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 1 }, d => d.HotspotName, OrderByType.Desc) //热点分类降序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 0 }, d => d.AcceptorName, OrderByType.Asc) //受理人升序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 1 }, d => d.AcceptorName, OrderByType.Desc) //受理人降序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 0 }, d => d.CurrentStepAcceptTime, OrderByType.Asc) //接办时间升序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 1 }, d => d.CurrentStepAcceptTime, OrderByType.Desc) //接办时间降序
            ;

        return query;
    }

    /// <summary>
    /// 未签收统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order, WorkflowStep> QueryUnsignedOrders(QueryUnsignedOrdersRequest dto)
    {
        var IsCenter = _sessionContext.OrgIsCenter;
        return _orderRepository.Queryable()
            .LeftJoin<WorkflowStep>((x, ws) => x.Id == ws.ExternalId)
            .WhereIF(dto.StartTime.HasValue, (x, ws) => ws.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, (x, ws) => ws.CreationTime <= dto.EndTime)
            .WhereIF(dto.Level == 0 && IsCenter == false, (x, ws) => ws.AcceptorOrgId.StartsWith(_sessionContext.OrgId))
            .WhereIF(dto.Level == 1, (x, ws) => ws.AcceptorOrgId == _sessionContext.OrgId)
            .WhereIF(dto.Level == 2, (x, ws) => ws.AcceptorOrgId.StartsWith(_sessionContext.OrgId))
            .WhereIF(dto.Signed == 0, (x, ws) => ws.Status == Share.Enums.FlowEngine.EWorkflowStepStatus.WaitForAccept)
            .WhereIF(dto.Signed == 1, (x, ws) => ws.Status == Share.Enums.FlowEngine.EWorkflowStepStatus.WaitForHandle)
            .Where((x, ws) => ws.CountersignPosition == Share.Enums.FlowEngine.ECountersignPosition.None && x.Status > EOrderStatus.WaitForAccept)
            .OrderByDescending((x, ws) => ws.CreationTime);
    }

    /// <summary>
    /// 信件来源统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> QueryOrderSource(QueryOrderSourceRequest dto)
    {
        return _orderRepository.Queryable()
            .WhereIF(dto.StartTime.HasValue, d => d.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, d => d.CreationTime <= dto.EndTime)
            .WhereIF(dto.TypeId != null && dto.TypeId == 1, x => x.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeId != null && dto.TypeId == 2, x => x.IdentityType == EIdentityType.Enterprise)
            .Where(d => d.SourceChannel != null && d.SourceChannel != "");
    }

    /// <summary>
    /// 信件来源统计明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> QueryOrderSourceDetail(QueryOrderSourceDetailRequest dto)
    {
        return _orderRepository.Queryable()
            .WhereIF(!string.IsNullOrEmpty(dto.SourceChannel), d => d.SourceChannel == dto.SourceChannel)
            .WhereIF(dto.Time.HasValue, d => d.CreationTime.ToString("yyyy-MM-dd") == dto.Time.Value.ToString("yyyy-MM-dd"))
            .WhereIF(dto.TypeId != null && dto.TypeId == 1, x => x.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeId != null && dto.TypeId == 2, x => x.IdentityType == EIdentityType.Enterprise)
            .Where(d => d.SourceChannel != null && d.SourceChannel != "");
    }

    /// <summary>
    /// 部门超期统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderBiOrgDataListVo> QueryOrgDataList(ReportPagedRequest dto)
    {
        if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

        //dto.EndTime = dto.EndTime.Value.AddDays(1).AddSeconds(-1);

        var IsCenter = _sessionContext.OrgIsCenter;


        var queryOrder = _systemOrganizeRepository.Queryable()
            .LeftJoin<Order>((x, o) => x.Id == o.ActualHandleOrgCode)
            .WhereIF(dto.StartTime.HasValue, (x, o) => o.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, (x, o) => o.CreationTime <= dto.EndTime)
            .WhereIF(dto.TypeId != null && dto.TypeId == 1, (x, o) => o.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeId != null && dto.TypeId == 2, (x, o) => o.IdentityType == EIdentityType.Enterprise)
            .WhereIF(IsCenter == false, (x, o) => o.ActualHandleOrgCode == _sessionContext.RequiredOrgId)
            .GroupBy((x, o) => new { x.Id, x.Name })
            .Select((x, o) => new OrderBiOrgDataListVo
            {
                OrgName = x.Name,
                OrgId = x.Id,
                HandlerExtendedNum = SqlFunc.AggregateSum(SqlFunc.IIF(o.Status >= EOrderStatus.Filed && o.ExpiredTime < o.FiledTime, 1, 0)),
                NoHandlerExtendedNum = SqlFunc.AggregateSum(SqlFunc.IIF(o.Status < EOrderStatus.Filed && o.ExpiredTime < SqlFunc.GetDate(), 1, 0)),
            }).MergeTable();

        var queryCountersign = _workflowStepRepository.Queryable()
            .Where(x => x.CountersignPosition != ECountersignPosition.None)
            .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
            .GroupBy(x => x.HandlerOrgId)
            .Select(x => new OrderBiOrgDataListVo
            {
                OrgId = x.HandlerOrgId,
                CounterHandlerExtendedNum =
                    SqlFunc.AggregateSum(
                        SqlFunc.IIF(x.Status == Share.Enums.FlowEngine.EWorkflowStepStatus.Handled && x.StepExpiredTime < x.HandleTime, 1, 0)),
                CounterNoHandlerExtendedNum =
                    SqlFunc.AggregateSum(SqlFunc.IIF(
                        x.Status != Share.Enums.FlowEngine.EWorkflowStepStatus.Handled && x.StepExpiredTime < SqlFunc.GetDate(), 1, 0)),
            }).MergeTable();

        var query =
            _systemOrganizeRepository.Queryable()
                .LeftJoin(queryOrder, (x, or) => x.Id == or.OrgId)
                .LeftJoin(queryCountersign, (x, or, co) => x.Id == co.OrgId)
                //.LeftJoin<SystemOrganize>((or, co, so) => or.OrgId.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")) == so.Id)
                .LeftJoin<SystemOrganize>((x, or, co, so) => or.OrgId == so.Id && so.Level == 1)
                .GroupBy((x, or, co, so) => new { so.Id, so.Name })
                .Select((x, or, co, so) => new OrderBiOrgDataListVo
                {
                    OrgName = so.Name,
                    OrgId = so.Id,
                    HandlerExtendedNum = SqlFunc.AggregateSum(or.HandlerExtendedNum),
                    NoHandlerExtendedNum = SqlFunc.AggregateSum(or.NoHandlerExtendedNum),
                    CounterHandlerExtendedNum = SqlFunc.AggregateSum(co.CounterHandlerExtendedNum),
                    CounterNoHandlerExtendedNum = SqlFunc.AggregateSum(co.CounterNoHandlerExtendedNum)
                }).MergeTable();

        query = query.WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.OrgName.Contains(dto.Keyword!))
            .Where(x => x.OrgName != null).Where(x =>
                x.HandlerExtendedNum > 0 || x.NoHandlerExtendedNum > 0 || x.CounterHandlerExtendedNum > 0 || x.CounterNoHandlerExtendedNum > 0);
        switch (dto.SortField)
        {
            case "handlerExtendedNum":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.HandlerExtendedNum) : query.OrderByDescending(x => x.HandlerExtendedNum);
                break;
            case "counterHandlerExtendedNum":
                query = dto.SortRule is 0
                    ? query.OrderBy(x => x.CounterHandlerExtendedNum)
                    : query.OrderByDescending(x => x.CounterHandlerExtendedNum);
                break;
            case "noHandlerExtendedNum":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.NoHandlerExtendedNum) : query.OrderByDescending(x => x.NoHandlerExtendedNum);
                break;
            case "counterNoHandlerExtendedNum":
                query = dto.SortRule is 0
                    ? query.OrderBy(x => x.CounterNoHandlerExtendedNum)
                    : query.OrderByDescending(x => x.CounterNoHandlerExtendedNum);
                break;
        }

        return query;
    }

    /// <summary>
    /// 部门超期统计明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> QueryOrgDataListDetail(OrgDataListDetailRequest dto)
    {
        var quer = _orderRepository.Queryable()
            .InnerJoin<SystemOrganize>((x, so) => x.ActualHandleOrgCode == so.Id && so.Level == 1)
            .Where((x, so) => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
            //.WhereIF(dto.Statuses.Any(), x => dto.Statuses.Contains(x.Status))  //工单状态
            .WhereIF(dto.QueryType == 1, (x, so) => x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.FiledTime) //业务已办超期
            .WhereIF(dto.QueryType == 3, (x, so) => x.Status < EOrderStatus.Filed && x.ExpiredTime < SqlFunc.GetDate()) //业务待办超期
            .WhereIF(dto.TypeId != null && dto.TypeId == 1, (x, so) => x.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeId != null && dto.TypeId == 2, (x, so) => x.IdentityType == EIdentityType.Enterprise)
            .WhereIF(dto.QueryType == 5, (x, so) =>
                (x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.FiledTime) ||
                (x.Status < EOrderStatus.Filed && x.ExpiredTime < SqlFunc.GetDate()))
            .WhereIF(!string.IsNullOrEmpty(dto.OrgCode), (x, so) => x.ActualHandleOrgCode == dto.OrgCode)
            .Select(x => new Order { DaysOverdueOrgName = x.ActualHandleOrgName, Id = x.Id.SelectAll() });
        if (dto.QueryType is 2 or 4)
        {
            var queryCountersign = _workflowStepRepository.Queryable()
                .Includes(x => x.Workflow)
                .InnerJoin<SystemOrganize>((x, so) => x.HandlerOrgId == so.Id && so.Level == 1)
                .Where((x, so) => x.CountersignPosition != ECountersignPosition.None && x.Workflow.ModuleCode == "OrderHandle")
                .Where((x, so) => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .WhereIF(dto.QueryType == 2,
                    (x, so) => x.Status == Share.Enums.FlowEngine.EWorkflowStepStatus.Handled && x.StepExpiredTime < x.HandleTime) //会签已办超期
                .WhereIF(dto.QueryType == 4,
                    (x, so) => x.Status != Share.Enums.FlowEngine.EWorkflowStepStatus.Handled && x.StepExpiredTime < SqlFunc.GetDate()) //会签待办超期
                .WhereIF(!string.IsNullOrEmpty(dto.OrgCode), (x, so) => x.HandlerOrgId == dto.OrgCode)
                .GroupBy(x => new { x.ExternalId, x.HandlerOrgName })
                .Select(x => new { Id = x.ExternalId, WorkflowId = x.ExternalId, HandlerOrgName = x.HandlerOrgName });

            quer = _orderRepository.Queryable().InnerJoin(queryCountersign, (o, w) => o.Id == w.Id)
                .Select((o, w) => new Order { DaysOverdueOrgName = w.HandlerOrgName, Id = o.Id.SelectAll() })
                .WhereIF(!string.IsNullOrEmpty(dto.No), o => o.No == dto.No);
            //quer = _orderRepository.UnionAll(quer, queryCountersignOrder);
        }

        return quer;
    }

    /// <summary>
    /// 部门超期统计明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> QueryOrgDataListDetail(OrgDataListAllDetailRequest dto)
    {
        bool IsCenter = _sessionContext.OrgIsCenter;

        var quer = _orderRepository.Queryable()
            .InnerJoin<SystemOrganize>((x, so) => x.ActualHandleOrgCode == so.Id && so.Level == 1)
            .Where((x, so) => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
            .WhereIF(dto.Statuses.Any(), (x, so) => dto.Statuses.Contains(x.Status)) //工单状态
            .WhereIF(dto.ExpiredType is 2, (x, so) => x.OrderDelays.Any(x => x.DelayState == EDelayState.Pass))
            .Where((x, so) =>
                (x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.FiledTime) ||
                (x.Status < EOrderStatus.Filed && x.ExpiredTime < SqlFunc.GetDate()))
            .WhereIF(IsCenter == false, (x, so) => x.ActualHandleOrgCode == _sessionContext.RequiredOrgId)
            .WhereIF(!string.IsNullOrEmpty(dto.OrgName), (x, so) => x.AcceptorOrgName == dto.OrgName)
            .Select(x => new Order { DaysOverdueOrgName = x.ActualHandleOrgName, Id = x.Id.SelectAll() });

        var queryCountersign = _workflowStepRepository.Queryable()
            .Includes(x => x.Workflow)
            .InnerJoin<SystemOrganize>((x, so) => x.HandlerOrgId == so.Id && so.Level == 1)
            .LeftJoin<Order>((x, so, o) => x.ExternalId == o.Id)
            .Where((x, so) => x.CountersignPosition != ECountersignPosition.None && x.Workflow.ModuleCode == "OrderHandle")
            .Where((x, so) => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
            .Where((x, so) => (x.Status == Share.Enums.FlowEngine.EWorkflowStepStatus.Handled && x.StepExpiredTime < x.HandleTime) ||
                              (x.Status != Share.Enums.FlowEngine.EWorkflowStepStatus.Handled && x.StepExpiredTime < SqlFunc.GetDate()))
            .WhereIF(IsCenter == false, (x, so) => x.HandlerOrgId == _sessionContext.RequiredOrgId)
            .WhereIF(dto.ExpiredType is 2, (x, so, o) => o.OrderDelays.Any(x => x.DelayState == EDelayState.Pass))
            .GroupBy(x => new { x.ExternalId, x.HandlerOrgName })
            .Select(x => new { Id = x.ExternalId, WorkflowId = x.ExternalId, HandlerOrgName = x.HandlerOrgName });

        var queryCountersignOrder = _orderRepository.Queryable().InnerJoin(queryCountersign, (o, w) => o.Id == w.Id)
            .Select((o, w) => new Order { DaysOverdueOrgName = w.HandlerOrgName, Id = o.Id.SelectAll() });
        quer = _orderRepository.UnionAll(quer, queryCountersignOrder).MergeTable()
            .InnerJoin<SystemOrganize>((x, so) => x.ActualHandleOrgCode == so.Id)
            .WhereIF(!string.IsNullOrEmpty(dto.No), (x, so) => x.No == dto.No)
            .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
            .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
            .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
            .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, x => x.ExpiredTime, OrderByType.Asc)
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, x => x.ExpiredTime, OrderByType.Desc);
        return quer;
    }

    /// <summary>
    /// 回退错件统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderReTransactVo> OrderReTransact(QueryOrderReTransactRequest dto)
    {
        return _orderSpecialDetailRepository.Queryable()
            .Includes(x => x.OrderSpecial)
            .WhereIF(!string.IsNullOrEmpty(dto.OrgName), x => x.OrgName.Contains(dto.OrgName!))
            .Where(x => x.OrderSpecial.SpecialType == ESpecialType.ReTransact || x.OrderSpecial.SpecialType == ESpecialType.SendBack)
            .Where(x => x.OrderSpecial.CreationTime >= dto.StartTime)
            .Where(x => x.OrderSpecial.CreationTime <= dto.EndTime)
            .WhereIF(!_sessionContext.OrgIsCenter, x => x.OrgId.StartsWith(_sessionContext.RequiredOrgId))
            .MergeTable()
            .GroupBy(x => new { Time = x.OrderSpecial.CreationTime.ToString("yyyy-MM-dd"), x.OrgId, x.OrgName })
            .Select(x => new OrderReTransactVo
            {
                Time = x.OrderSpecial.CreationTime.ToString("yyyy-MM-dd"),
                OrgId = x.OrgId,
                OrgName = x.OrgName,
                Num = SqlFunc.AggregateCount(1)
            }).MergeTable()
            .OrderByIF(dto.SortRule is 0, x => x.Num, OrderByType.Asc)
            .OrderByIF(dto.SortRule is 1, x => x.Num, OrderByType.Desc);
        ;
    }

    /// <summary>
    /// 回退错件明细统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderSpecialDetail> QueryOrderSourceDetail(QueryOrderReTransactDetailRequest dto)
    {
        if (!dto.StartTime.HasValue || !dto.EndTime.HasValue)
            throw UserFriendlyException.SameMessage("请选择时间!");
        return _orderSpecialDetailRepository.Queryable()
            .Includes(x => x.OrderSpecial, s => s.Order)
            .WhereIF(!string.IsNullOrEmpty(dto.OrgName), x => x.OrgName.Contains(dto.OrgName!))
            .WhereIF(!string.IsNullOrEmpty(dto.ErrorName), x => x.ErrorName.Contains(dto.ErrorName!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.OrderSpecial!.Order!.No!.Contains(dto.No!))
            .WhereIF(!_sessionContext.OrgIsCenter, x => x.OrgId.StartsWith(_sessionContext.RequiredOrgId))
            .Where(x => x.OrderSpecial.SpecialType == ESpecialType.ReTransact || x.OrderSpecial.SpecialType == ESpecialType.SendBack)
            .Where(x => x.OrderSpecial.CreationTime >= dto.StartTime)
            .Where(x => x.OrderSpecial.CreationTime <= dto.EndTime);
    }

    ///// <summary>
    ///// 
    ///// </summary>
    ///// <param name="dto"></param>
    ///// <returns></returns>
    //public async Task<List<VisitAndOrgSatisfactionStatisticsDto>> SeatSatisfactionStatistics(PagedKeywordSonRequest dto)
    //{
    //    _orderVisitRepository.Queryable()
    //        .Includes(d => d.Order)
    //        .Where(x => x.VisitTime >= dto.StartTime.Value && x.VisitTime <= dto.EndTime.Value && x.VisitState == EVisitState.Visited)
    //        .GroupBy(x=>new {
    //            AcceptorId = x.Order.AcceptorId,
    //            AcceptorName=  x.Order.AcceptorName
    //        }).Select(x => new VisitAndOrgSatisfactionStatisticsDto()
    //        {
    //            OrgCode = x.Order.AcceptorId,
    //            TotalSumCount =
    //                    SqlFunc.AggregateCount(x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))),
    //            VerySatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "5", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "5", 1, 0))), //非常满意数
    //            SatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "4", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "4", 1, 0))), //满意数
    //            RegardedAsSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "-1", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "-1", 1, 0))), //视为满意
    //            DefaultSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "0", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "0", 1, 0))), //默认满意
    //            NoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2", 1, 0))), //不满意
    //            NoEvaluateCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "7", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "7", 1, 0))), //未做评价
    //            NoPutThroughCount = SqlFunc.IIF(dto.TypeId == 1,
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "6", 1, 0)),
    //                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "6", 1, 0))), //未接通
    //        })
    //    return null;
    //}

    /// <summary>
    /// 部门满意度统计
    /// </summary>
    /// <returns></returns>
    public async Task<List<VisitAndOrgSatisfactionStatisticsDto>> VisitAndOrgSatisfactionStatistics(PagedKeywordSonRequest dto)
    {
        bool IsCenter = _sessionContext.OrgIsCenter;
        var orgLevel = _sessionContext.OrgLevel;
        string orgLevelStr = (_sessionContext.RequiredOrgId.Length + 3).ToString();

        var list = _orderVisitDetailRepository.Queryable()
            .Where(x => x.OrderVisit.VisitTime >= dto.StartTime.Value && x.OrderVisit.VisitTime <= dto.EndTime.Value &&
                        x.VisitTarget == EVisitTarget.Org && x.OrderVisit.VisitState == EVisitState.Visited && !string.IsNullOrEmpty(x.VisitOrgCode))
            .WhereIF(string.IsNullOrEmpty(dto.OrgName) == false, x => x.VisitOrgName.Contains(dto.OrgName))
            .WhereIF(string.IsNullOrEmpty(dto.LineNum) == false && _appOptions.Value.IsYiBin == true, x => x.OrderVisit.Order.CallRecord.Gateway.Contains(dto.LineNum))
            .WhereIF(string.IsNullOrEmpty(dto.LineNum) == false && _appOptions.Value.IsYiBin == false, x => x.OrderVisit.Order.FwCallRecord.ToNo.Contains(dto.LineNum))
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 1, x => x.OrderVisit.Order.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 2, x => x.OrderVisit.Order.IdentityType == EIdentityType.Enterprise)
            .WhereIF(IsCenter == false, x => x.VisitOrgCode.StartsWith(_sessionContext.OrgId))
            .WhereIF(dto.VisitType != null, x => x.OrderVisit.VisitType == dto.VisitType)
            .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.OrderVisit.Order.Title.Contains(dto.Title)) // 工单标题
            .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.OrderVisit.Order.No == dto.No) // 工单编号
            .WhereIF(dto.CreationTimeStart.HasValue, x => x.OrderVisit.Order.CreationTime >= dto.CreationTimeStart) // 受理时间开始
            .WhereIF(dto.CreationTimeEnd.HasValue, x => x.OrderVisit.Order.CreationTime <= dto.CreationTimeEnd) // 受理时间结束
            .WhereIF(dto.OrgVisitStatisticsType.HasValue && dto.OrgVisitStatisticsType == EOrgVisitStatisticsType.CallCenter, // 部门分类 中心归档
                x => x.OrderVisit.Order.ActualHandleOrgCode == OrgSeedData.CenterId)
            .WhereIF(dto.OrgVisitStatisticsType.HasValue && dto.OrgVisitStatisticsType == EOrgVisitStatisticsType.Org, // 部门分类 部门归档
                x => x.OrderVisit.Order.ActualHandleOrgCode != OrgSeedData.CenterId)
            .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.OrderVisit.Order.SourceChannelCode == dto.Channel) // 来源渠道	
            .WhereIF(!string.IsNullOrEmpty(dto.VisitUser), x => x.OrderVisit.Employee.Name.Contains(dto.VisitUser)) // 回访人
            .WhereIF(dto.OrgProcessingResults != null, // 办件结果
                dto.AttitudeType == EAttitudeType.ProcessingResult
                    ? x => dto.OrgProcessingResults.Contains(SqlFunc.JsonField(x.OrgProcessingResults, "Key"))
                    : x => dto.OrgProcessingResults.Contains(SqlFunc.JsonField(x.OrgHandledAttitude, "Key")))
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), x => x.OrderVisit.Order.HotspotSpliceName != null &&
                                                              x.OrderVisit.Order.HotspotSpliceName.Contains(dto.Hotspot)) // 热点分类
            .WhereIF(!string.IsNullOrEmpty(dto.OrgId), x => x.VisitOrgCode == dto.OrgId) // 回访部门
            .WhereIF(dto.ActualHandleTimeStart.HasValue, x => x.OrderVisit.Order.ActualHandleTime >= dto.ActualHandleTimeStart) // 办结时间开始
            .WhereIF(dto.ActualHandleTimeEnd.HasValue, x => x.OrderVisit.Order.ActualHandleTime <= dto.ActualHandleTimeEnd) // 办结时间结束
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true, x => x.OrderVisit.Order.Source == ESource.ProvinceStraight) //省/市工单
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false, x => x.OrderVisit.Order.Source != ESource.ProvinceStraight) //省/市工单
            .WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval), x => x.VisitContent.Contains(dto.ContentRetrieval!)); // 回访内容检索

        var data = new List<VisitAndOrgSatisfactionStatisticsDto>();
        var oldData = new List<VisitAndOrgSatisfactionStatisticsDto>();

        if (IsCenter && list != null)
        {
            data = await list.GroupBy(x => new
            {
                VisitOrgCode = x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))
            })
                .Select(x => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgCode = x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                    TotalSumCount =
                        SqlFunc.AggregateCount(x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))),
                    VerySatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "5", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "5", 1, 0))), //非常满意数
                    SatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "4", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "4", 1, 0))), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "-1", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "-1", 1, 0))), //视为满意
                    DefaultSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "0", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "0", 1, 0))), //默认满意
                    NoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2", 1, 0))), //不满意
                    NoEvaluateCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "7", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "6", 1, 0))), //未做评价
                    NoPutThroughCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "6", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "8", 1, 0))), //未接通
                    NormalCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "3", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "3", 1, 0))), //一般
                    VeryNoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "1", 1, 0))), //非常不满意
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((it, o) => it.OrgCode == o.Id)
                .Select((it, o) => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgName = o.Name,
                    OrgCode = it.OrgCode,
                    OrgType = o.OrgType,
                    TotalSumCount = it.TotalSumCount,
                    VerySatisfiedCount = it.VerySatisfiedCount, //非常满意数
                    SatisfiedCount = it.SatisfiedCount, //满意数
                    RegardedAsSatisfiedCount = it.RegardedAsSatisfiedCount, //视为满意
                    DefaultSatisfiedCount = it.DefaultSatisfiedCount, //默认满意
                    NoSatisfiedCount = it.NoSatisfiedCount, //不满意
                    NoEvaluateCount = it.NoEvaluateCount, //未做评价
                    NoPutThroughCount = it.NoPutThroughCount, //未接通
                    NormalCount = it.NormalCount,
                    VeryNoSatisfiedCount = it.VeryNoSatisfiedCount
                })
                .ToListAsync();
        }
        else
        {
            data = await list.GroupBy(x => new
            {
                VisitOrgCode = x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr))
            })
                .Select(x => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgCode = x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr)),
                    TotalSumCount =
                        SqlFunc.AggregateCount(x.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr))),
                    VerySatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "5", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "5", 1, 0))), //非常满意数
                    SatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "4", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "4", 1, 0))), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "-1", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "-1", 1, 0))), //视为满意
                    DefaultSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "0", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "0", 1, 0))), //默认满意
                    NoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2", 1, 0))), //不满意
                    NoEvaluateCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "7", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "6", 1, 0))), //未做评价
                    NoPutThroughCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "6", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "8", 1, 0))), //未接通
                    NormalCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "3", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "3", 1, 0))), //一般
                    VeryNoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "1", 1, 0))), //非常不满意
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((it, o) => it.OrgCode == o.Id && (o.Level == orgLevel || o.Level == (orgLevel + 1)))
                .Select((it, o) => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgName = o.Name,
                    OrgCode = it.OrgCode,
                    OrgType = o.OrgType,
                    TotalSumCount = it.TotalSumCount,
                    VerySatisfiedCount = it.VerySatisfiedCount, //非常满意数
                    SatisfiedCount = it.SatisfiedCount, //满意数
                    RegardedAsSatisfiedCount = it.RegardedAsSatisfiedCount, //视为满意
                    DefaultSatisfiedCount = it.DefaultSatisfiedCount, //默认满意
                    NoSatisfiedCount = it.NoSatisfiedCount, //不满意
                    NoEvaluateCount = it.NoEvaluateCount, //未做评价
                    NoPutThroughCount = it.NoPutThroughCount, //未接通
                    NormalCount = it.NormalCount, //一般
                    VeryNoSatisfiedCount = it.VeryNoSatisfiedCount //非常不满意
                })
                .ToListAsync();
        }

        #region 老系统数据

        if (await _statisticsDepartSatisfiedRepository.Queryable().Where(x => x.Time >= dto.StartTime.Value && x.Time <= dto.EndTime.Value)
                .AnyAsync())
        {
            var query = _statisticsDepartSatisfiedRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.DepartmentId == so.oldBmid)
                .WhereIF(IsCenter == false, (x, so) => so.Id.StartsWith(_sessionContext.OrgId))
                .Where((x, so) => x.Time >= dto.StartTime.Value && x.Time <= dto.EndTime.Value);
            if (IsCenter)
            {
                oldData = await query.GroupBy((x, so) => new
                {
                    VisitOrgCode = so.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))
                }).Select((x, so) => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgCode = so.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                    TotalSumCount = SqlFunc.AggregateSum(x.Total),
                    VerySatisfiedCount = SqlFunc.AggregateSum(x.VerySatisfaction), //非常满意数
                    SatisfiedCount = SqlFunc.AggregateSum(x.Satisfaction), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.AggregateSum(x.TreatSatisfaction), //视为满意
                    DefaultSatisfiedCount = SqlFunc.AggregateSum(x.DefaultSatisfaction), //默认满意
                    NoSatisfiedCount = SqlFunc.AggregateSum(x.Dissatisfaction), //不满意
                    NoEvaluateCount = SqlFunc.AggregateSum(x.NotEvaluated), //未做评价
                    NoPutThroughCount = SqlFunc.AggregateSum(x.BlockCall), //未接通
                })
                    .MergeTable()
                    .LeftJoin<SystemOrganize>((it, o) => it.OrgCode == o.Id)
                    .Select((it, o) => new VisitAndOrgSatisfactionStatisticsDto()
                    {
                        OrgName = o.Name,
                        OrgCode = it.OrgCode,
                        OrgType = o.OrgType,
                        TotalSumCount = it.TotalSumCount,
                        VerySatisfiedCount = it.VerySatisfiedCount, //非常满意数
                        SatisfiedCount = it.SatisfiedCount, //满意数
                        RegardedAsSatisfiedCount = it.RegardedAsSatisfiedCount, //视为满意
                        DefaultSatisfiedCount = it.DefaultSatisfiedCount, //默认满意
                        NoSatisfiedCount = it.NoSatisfiedCount, //不满意
                        NoEvaluateCount = it.NoEvaluateCount, //未做评价
                        NoPutThroughCount = it.NoPutThroughCount, //未接通
                    })
                    .ToListAsync();
                ;
            }
            else
            {
                oldData = await query.GroupBy((x, so) => new
                {
                    VisitOrgCode = so.Id
                }).Select((x, so) => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgCode = so.Id, //.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr)),
                    TotalSumCount = SqlFunc.AggregateSum(x.Total),
                    VerySatisfiedCount = SqlFunc.AggregateSum(x.VerySatisfaction), //非常满意数
                    SatisfiedCount = SqlFunc.AggregateSum(x.Satisfaction), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.AggregateSum(x.TreatSatisfaction), //视为满意
                    DefaultSatisfiedCount = SqlFunc.AggregateSum(x.DefaultSatisfaction), //默认满意
                    NoSatisfiedCount = SqlFunc.AggregateSum(x.Dissatisfaction), //不满意
                    NoEvaluateCount = SqlFunc.AggregateSum(x.NotEvaluated), //未做评价
                    NoPutThroughCount = SqlFunc.AggregateSum(x.BlockCall), //未接通
                })
                    .MergeTable().LeftJoin<SystemOrganize>((it, o) => it.OrgCode == o.Id && (o.Level == orgLevel || o.Level == (orgLevel + 1)))
                    .Select((it, o) => new VisitAndOrgSatisfactionStatisticsDto()
                    {
                        OrgName = o.Name,
                        OrgCode = it.OrgCode,
                        OrgType = o.OrgType,
                        TotalSumCount = it.TotalSumCount,
                        VerySatisfiedCount = it.VerySatisfiedCount, //非常满意数
                        SatisfiedCount = it.SatisfiedCount, //满意数
                        RegardedAsSatisfiedCount = it.RegardedAsSatisfiedCount, //视为满意
                        DefaultSatisfiedCount = it.DefaultSatisfiedCount, //默认满意
                        NoSatisfiedCount = it.NoSatisfiedCount, //不满意
                        NoEvaluateCount = it.NoEvaluateCount, //未做评价
                        NoPutThroughCount = it.NoPutThroughCount, //未接通
                    })
                    .ToListAsync();
            }

            data = (from t1 in data
                    join t2 in oldData on t1.OrgCode equals t2.OrgCode into t1_t2
                    from item in t1_t2.DefaultIfEmpty()
                    select new VisitAndOrgSatisfactionStatisticsDto()
                    {
                        OrgName = t1.OrgName,
                        OrgCode = t1.OrgCode,
                        OrgType = t1.OrgType,
                        TotalSumCount = t1.TotalSumCount + t1_t2.Select(x => x.TotalSumCount).FirstOrDefault(),
                        VerySatisfiedCount = t1.VerySatisfiedCount + t1_t2.Select(x => x.VerySatisfiedCount).FirstOrDefault(), //非常满意数
                        SatisfiedCount = t1.SatisfiedCount + t1_t2.Select(x => x.SatisfiedCount).FirstOrDefault(), //满意数
                        RegardedAsSatisfiedCount = t1.RegardedAsSatisfiedCount + t1_t2.Select(x => x.RegardedAsSatisfiedCount).FirstOrDefault(), //视为满意
                        DefaultSatisfiedCount = t1.DefaultSatisfiedCount + t1_t2.Select(x => x.DefaultSatisfiedCount).FirstOrDefault(), //默认满意
                        NoSatisfiedCount = t1.NoSatisfiedCount + t1_t2.Select(x => x.NoSatisfiedCount).FirstOrDefault(), //不满意
                        NoEvaluateCount = t1.NoEvaluateCount + t1_t2.Select(x => x.NoEvaluateCount).FirstOrDefault(), //未做评价
                        NoPutThroughCount = t1.NoPutThroughCount + t1_t2.Select(x => x.NoPutThroughCount).FirstOrDefault(), //未接通
                    }).ToList();
        }

        #endregion

        return data;
    }

    /// <summary>
    /// 子部门满意度
    /// </summary>
    /// <returns></returns>
    public async Task<List<VisitAndOrgSatisfactionStatisticsDto>> VisitAndOrgStatisfactionOrgDetail(PagedKeywordSonRequest dto)
    {
        bool IsCenter = _sessionContext.OrgIsCenter;
        var org = await _systemOrganizeRepository.Queryable().FirstAsync(x => x.Id == dto.OrgCode);

        string orgLevelStr = (dto.OrgCode.Length + 3).ToString();
        var oldData = new List<VisitAndOrgSatisfactionStatisticsDto>();

        var mainList = await _systemOrganizeRepository.Queryable().Where(x => x.Id.StartsWith(dto.OrgCode))
            .LeftJoin<OrderVisitDetail>((x, it) => x.Id == it.VisitOrgCode)
            .Where((x, it) => it.OrderVisit.VisitTime >= dto.StartTime.Value &&
                              it.OrderVisit.VisitTime <= dto.EndTime.Value &&
                              it.VisitTarget == EVisitTarget.Org && it.OrderVisit.VisitState == EVisitState.Visited)
            .Where((x, it) => it.VisitOrgCode.StartsWith(dto.OrgCode))
            //&& it.VisitOrgCode != dto.OrgCode
            .WhereIF(!string.IsNullOrEmpty(dto.LineNum),
                (x, it) => it.OrderVisit.Order.CallRecord.Gateway.Contains(dto.LineNum))
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 1,
                (x, it) => it.OrderVisit.Order.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 2,
                (x, it) => it.OrderVisit.Order.IdentityType == EIdentityType.Enterprise)
            .WhereIF(IsCenter == false,
                (x, it) => it.VisitOrgCode.StartsWith(_sessionContext.OrgId))
            .WhereIF(dto.VisitType != null, (x, it) => it.OrderVisit.VisitType == dto.VisitType)
            .GroupBy((x, it) => new
            {
                VisitOrgCode = it.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr))
            })
            .Select((x, it) => new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgCode = it.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr)),
                TotalSumCount =
                    SqlFunc.AggregateCount(it.VisitOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr))),
                VerySatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "5", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "5", 1,
                        0))), //非常满意数
                SatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "4", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "4", 1,
                        0))), //满意数
                RegardedAsSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "-1", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "-1", 1,
                        0))), //视为满意
                DefaultSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "0", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "0", 1,
                        0))), //默认满意
                NoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "2", 1,
                        0))), //不满意
                NoEvaluateCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "7", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "6", 1,
                        0))), //未做评价
                NoPutThroughCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "6", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "8", 1,
                        0))), //未接通
                NormalCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "3", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "3", 1, 0))), //一般
                VeryNoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1", 1, 0)),
                    SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgHandledAttitude, "Key") == "1", 1, 0))), //非常不满意
            })
            .MergeTable()
            .LeftJoin<SystemOrganize>((x, it) =>
                x.OrgCode == it.Id && (it.Level == org.Level || it.Level == (org.Level + 1)))
            .Select((x, it) => new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = it.Name,
                OrgCode = x.OrgCode,
                OrgType = it.OrgType,
                TotalSumCount = x.TotalSumCount,
                VerySatisfiedCount = x.VerySatisfiedCount, //非常满意数
                SatisfiedCount = x.SatisfiedCount, //满意数
                RegardedAsSatisfiedCount = x.RegardedAsSatisfiedCount, //视为满意
                DefaultSatisfiedCount = x.DefaultSatisfiedCount, //默认满意
                NoSatisfiedCount = x.NoSatisfiedCount, //不满意
                NoEvaluateCount = x.NoEvaluateCount, //未做评价
                NoPutThroughCount = x.NoPutThroughCount, //未接通
                NormalCount = x.NormalCount, //一般
                VeryNoSatisfiedCount = x.VeryNoSatisfiedCount //非常不满意
            }).ToListAsync();


        #region 老系统数据

        if (await _statisticsDepartSatisfiedRepository.Queryable().Where(x => x.Time >= dto.StartTime.Value && x.Time <= dto.EndTime.Value)
                .AnyAsync())
        {
            var query = _statisticsDepartSatisfiedRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.DepartmentId == so.oldBmid)
                .WhereIF(dto.OrgCode == "001", (x, so) => so.Id == dto.OrgCode)
                .WhereIF(dto.OrgCode != "001", (x, so) => so.Id.StartsWith(dto.OrgCode))
                .Where((x, so) => x.Time >= dto.StartTime.Value && x.Time <= dto.EndTime.Value);

            oldData = await query.GroupBy((x, so) => new
            {
                VisitOrgCode = so.Id
            }).Select((x, so) => new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgCode = so.Id, //.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(orgLevelStr)),
                TotalSumCount = SqlFunc.AggregateSum(x.Total),
                VerySatisfiedCount = SqlFunc.AggregateSum(x.VerySatisfaction), //非常满意数
                SatisfiedCount = SqlFunc.AggregateSum(x.Satisfaction), //满意数
                RegardedAsSatisfiedCount = SqlFunc.AggregateSum(x.TreatSatisfaction), //视为满意
                DefaultSatisfiedCount = SqlFunc.AggregateSum(x.DefaultSatisfaction), //默认满意
                NoSatisfiedCount = SqlFunc.AggregateSum(x.Dissatisfaction), //不满意
                NoEvaluateCount = SqlFunc.AggregateSum(x.NotEvaluated), //未做评价
                NoPutThroughCount = SqlFunc.AggregateSum(x.BlockCall), //未接通
            })
                .MergeTable().LeftJoin<SystemOrganize>((it, o) => it.OrgCode == o.Id && (o.Level == org.Level || o.Level == (org.Level + 1)))
                .Select((it, o) => new VisitAndOrgSatisfactionStatisticsDto()
                {
                    OrgName = o.Name,
                    OrgCode = it.OrgCode,
                    OrgType = o.OrgType,
                    TotalSumCount = it.TotalSumCount,
                    VerySatisfiedCount = it.VerySatisfiedCount, //非常满意数
                    SatisfiedCount = it.SatisfiedCount, //满意数
                    RegardedAsSatisfiedCount = it.RegardedAsSatisfiedCount, //视为满意
                    DefaultSatisfiedCount = it.DefaultSatisfiedCount, //默认满意
                    NoSatisfiedCount = it.NoSatisfiedCount, //不满意
                    NoEvaluateCount = it.NoEvaluateCount, //未做评价
                    NoPutThroughCount = it.NoPutThroughCount, //未接通
                })
                .ToListAsync();
            mainList = (from t1 in mainList
                        join t2 in oldData on t1.OrgCode equals t2.OrgCode into t1_t2
                        from item in t1_t2.DefaultIfEmpty()
                        select new VisitAndOrgSatisfactionStatisticsDto()
                        {
                            OrgName = t1.OrgName,
                            OrgCode = t1.OrgCode,
                            OrgType = t1.OrgType,
                            TotalSumCount = t1.TotalSumCount + t1_t2.Select(x => x.TotalSumCount).FirstOrDefault(),
                            VerySatisfiedCount = t1.VerySatisfiedCount + t1_t2.Select(x => x.VerySatisfiedCount).FirstOrDefault(), //非常满意数
                            SatisfiedCount = t1.SatisfiedCount + t1_t2.Select(x => x.SatisfiedCount).FirstOrDefault(), //满意数
                            RegardedAsSatisfiedCount = t1.RegardedAsSatisfiedCount + t1_t2.Select(x => x.RegardedAsSatisfiedCount).FirstOrDefault(), //视为满意
                            DefaultSatisfiedCount = t1.DefaultSatisfiedCount + t1_t2.Select(x => x.DefaultSatisfiedCount).FirstOrDefault(), //默认满意
                            NoSatisfiedCount = t1.NoSatisfiedCount + t1_t2.Select(x => x.NoSatisfiedCount).FirstOrDefault(), //不满意
                            NoEvaluateCount = t1.NoEvaluateCount + t1_t2.Select(x => x.NoEvaluateCount).FirstOrDefault(), //未做评价
                            NoPutThroughCount = t1.NoPutThroughCount + t1_t2.Select(x => x.NoPutThroughCount).FirstOrDefault(), //未接通
                        }).ToList();
        }

        #endregion

        return mainList;
    }


    /// <summary>
    /// 热点区域统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<(List<SystemArea> area, object items)> HotspotAndAreaStatistics(HotspotAndAreaStatisticsReq dto)
    {
        var areaList = _systemAreaRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == 6 && x.Id != "510000").OrderBy(x => x.Id).MergeTable();

        var endIndex = (2 * dto.HotspotLevel).ToString();
        var hotspotList = _hotspotRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == int.Parse(endIndex))
            .Select(x => new
            {
                HotspotId = x.Id,
                HotspotName = x.HotSpotFullName,
            }).MergeTable();


        var orderList = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime < dto.EndTime)
            .Select(x => new
            {
                HotspotId = x.HotspotId.Substring(0, int.Parse(endIndex)),
                AreaCode = x.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
            }).MergeTable();


        var hotListAndOrder = hotspotList.LeftJoin(orderList, (it, o) => it.HotspotId == o.HotspotId)
            .GroupBy((it, o) => new
            {
                it.HotspotId,
                it.HotspotName,
                AreaCode = o.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
            })
            .OrderBy((it, o) => it.HotspotId)
            .Select((it, o) => new
            {
                HotspotId = it.HotspotId,
                HotspotName = it.HotspotName,
                AreaCode = o.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                Count = SqlFunc.AggregateCount(it.HotspotId)
            }).MergeTable();


        var returnList = await areaList.LeftJoin(hotListAndOrder, (pp, dd) => pp.Id == dd.AreaCode)
            .GroupBy((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AreaCode = pp.Id,
                AreaName = pp.AreaName,
            })
            .OrderBy((pp, dd) => dd.HotspotId)
            .Select((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AreaCode = pp.Id,
                AreaName = pp.AreaName,
                Count = SqlFunc.AggregateSum(dd.Count)
            }).ToPivotListAsync(q => q.AreaCode, q => new { q.HotspotName, q.HotspotId }, q => q.Sum(x => x.Count));

        var areaTitleList = await _systemAreaRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == 6 && x.Id != "510000").OrderBy(x => x.Id)
            .ToListAsync();
        return (areaTitleList, returnList);
    }


    /// <summary>
    /// 热点区域统计--导出
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<DataTable> HotspotAndAreaStatisticsExport(HotspotAndAreaStatisticsReq dto)
    {
        var areaList = _systemAreaRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == 6 && x.Id != "510000").OrderBy(x => x.Id).MergeTable();

        var endIndex = (2 * dto.HotspotLevel).ToString();
        var hotspotList = _hotspotRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == int.Parse(endIndex))
            .Select(x => new
            {
                HotspotId = x.Id,
                HotspotName = x.HotSpotFullName,
            }).MergeTable();


        var orderList = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime < dto.EndTime)
            .Select(x => new
            {
                HotspotId = x.HotspotId.Substring(0, int.Parse(endIndex)),
                AreaCode = x.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
            }).MergeTable();


        var hotListAndOrder = hotspotList.LeftJoin(orderList, (it, o) => it.HotspotId == o.HotspotId)
            .GroupBy((it, o) => new
            {
                it.HotspotId,
                it.HotspotName,
                AreaCode = o.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
            })
            .OrderBy((it, o) => it.HotspotId)
            .Select((it, o) => new
            {
                HotspotId = it.HotspotId,
                HotspotName = it.HotspotName,
                AreaCode = o.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                Count = SqlFunc.AggregateCount(it.HotspotId)
            }).MergeTable();


        var returnList = await areaList.LeftJoin(hotListAndOrder, (pp, dd) => pp.Id == dd.AreaCode)
            .GroupBy((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AreaCode = pp.Id,
                AreaName = pp.AreaName,
            })
            .OrderBy((pp, dd) => dd.HotspotId)
            .Select((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AreaCode = pp.Id,
                AreaName = pp.AreaName,
                Count = SqlFunc.AggregateSum(dd.Count)
            }).ToPivotTableAsync(q => q.AreaName, q => new { q.HotspotName }, q => q.Sum(x => x.Count));
        //returnList.Rows.RemoveAt(returnList.Rows.Count-1);
        return returnList;
    }


    public DataTable InitHotspotTable(DataTable dt, List<string> AddColumnName, int HotspotLevel)
    {
        //修改列名
        if (dt.Columns.Contains("HotspotName"))
            dt.Columns["HotspotName"].ColumnName = "一级热点";

        //增加小计
        DataColumn totalColumn = new DataColumn("小计", typeof(decimal));
        dt.Columns.Add(totalColumn);
        if (dt.Columns.Contains("Column1"))
            dt.Columns.Remove("Column1");

        //计算小计
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            int sumcount = 0;
            for (int j = 1; j < dt.Columns.Count - 1; j++)
            {
                sumcount += Convert.ToInt32(dt.Rows[i][j].ToString());
            }

            dt.Rows[i][dt.Columns.Count - 1] = sumcount;
        }

        //增加合计
        DataRow totalRow = dt.NewRow();
        if (dt.Columns[0].ColumnName == "HotspotName") totalRow["HotspotName"] = "合计";
        else totalRow["一级热点"] = "合计";
        for (int i = 1; i < dt.Columns.Count; i++)
        {
            int sumcount = 0;
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                sumcount += Convert.ToInt32(dt.Rows[j][i].ToString());
            }

            totalRow[i] = sumcount;
        }

        dt.Rows.Add(totalRow);

        //创建新表
        DataTable dt2 = new DataTable();

        //添加表头
        foreach (var item in AddColumnName)
        {
            if (item.Equals("HotspotName") || item.Equals("热点分类"))
            {
                dt2.Columns.Add("一级热点");
                if (HotspotLevel == 2)
                {
                    dt2.Columns.Add("二级热点");
                }
                else if (HotspotLevel == 3)
                {
                    dt2.Columns.Add("二级热点");
                    dt2.Columns.Add("三级热点");
                }
                else if (HotspotLevel == 4)
                {
                    dt2.Columns.Add("二级热点");
                    dt2.Columns.Add("三级热点");
                    dt2.Columns.Add("四级热点");
                }
            }
            else
            {
                //if (dt.Columns.Contains(item))
                dt2.Columns.Add(item);
            }
        }

        //处理数据
        foreach (DataRow sourceRow in dt.Rows)
        {
            if (sourceRow["一级热点"].ToString() == "")
            {
                continue;
            }

            DataRow targetRow = dt2.NewRow();
            foreach (var item in AddColumnName)
            {
                if (item.Equals("HotspotName") || item.Equals("热点分类"))
                {
                    targetRow["一级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[0];
                    if (HotspotLevel == 2)
                    {
                        targetRow["二级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[1];
                    }
                    else if (HotspotLevel == 3)
                    {
                        try
                        {
                            targetRow["二级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[1];
                        }
                        catch
                        {
                            targetRow["二级热点"] = "";
                        }

                        try
                        {
                            targetRow["三级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[2];
                        }
                        catch
                        {
                            targetRow["三级热点"] = "";
                        }
                    }
                    else if (HotspotLevel == 4)
                    {
                        try
                        {
                            targetRow["二级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[1];
                        }
                        catch
                        {
                            targetRow["二级热点"] = "";
                        }

                        try
                        {
                            targetRow["三级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[2];
                        }
                        catch
                        {
                            targetRow["三级热点"] = "";
                        }

                        try
                        {
                            targetRow["四级热点"] = sourceRow["一级热点"].ToString()?.Split('-')[3];
                        }
                        catch
                        {
                            targetRow["四级热点"] = "";
                        }
                    }
                }
                else
                {
                    try
                    {
                        targetRow[item] = sourceRow[item];
                    }
                    catch
                    {
                        targetRow[item] = 0;
                    }
                }
            }

            dt2.Rows.Add(targetRow);
        }

        return dt2;
    }

    /// <summary>
    /// 热点类型满意度统计
    /// </summary>
    /// <returns></returns>
    public async Task<List<VisitAndHotspotSatisfactionStatisticsDto>> VisitAndHotspotSatisfactionStatistics(VisitAndHotspotPagedKeywordRequest dto)
    {
        bool IsCenter = _sessionContext.OrgIsCenter;

        var list = _orderVisitDetailRepository.Queryable()
            .Includes(x => x.OrderVisit, v => v.Order)
            .InnerJoin<Hotspot>((x, h) =>
                h.Id == x.OrderVisit.Order.HotspotId.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("2")) &&
                h.ParentId == null)
            .Where(x => x.OrderVisit.VisitTime >= dto.StartTime.Value && x.OrderVisit.VisitTime <= dto.EndTime.Value &&
                        x.VisitTarget == EVisitTarget.Org && x.OrderVisit.VisitState == EVisitState.Visited && !string.IsNullOrEmpty(x.VisitOrgCode))
            .WhereIF(string.IsNullOrEmpty(dto.HotspotName) == false, (x, h) => h.HotSpotName == dto.HotspotName)
            .WhereIF(IsCenter == false, x => x.VisitOrgCode.StartsWith(_sessionContext.OrgId))
            .WhereIF(dto.TypeId == 1, x => x.OrgProcessingResults != null)
            .WhereIF(dto.TypeId == 2, x => x.OrgHandledAttitude != null);

        var data = new List<VisitAndHotspotSatisfactionStatisticsDto>();

        if (IsCenter && list != null)
        {
            data = await list.GroupBy((x, h) => new
            {
                HotspotName = h.HotSpotName,
                HotspotId = h.Id
            })
                .Select((x, h) => new VisitAndHotspotSatisfactionStatisticsDto()
                {
                    HotspotName = h.HotSpotName,
                    HotspotId = h.Id,
                    TotalSumCount =
                        SqlFunc.AggregateCount(x.OrderVisit.Order.HotspotId.Substring(SqlFunc.MappingColumn<int>("0"),
                            SqlFunc.MappingColumn<int>("2"))),
                    VerySatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "5", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "5", 1, 0))), //非常满意数
                    SatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "4", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "4", 1, 0))), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "-1", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "-1", 1, 0))), //视为满意
                    DefaultSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "0", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "0", 1, 0))), //默认满意
                    NoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2", 1, 0))), //不满意
                    NoEvaluateCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "7", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "7", 1, 0))), //未做评价
                    NoPutThroughCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "6", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "6", 1, 0))), //未接通
                })
                .ToListAsync();
        }
        else
        {
            data = await list.GroupBy((x, h) => new
            {
                HotspotName = h.HotSpotName,
                HotspotId = h.Id
            })
                .Select((x, h) => new VisitAndHotspotSatisfactionStatisticsDto()
                {
                    HotspotName = h.HotSpotName,
                    HotspotId = h.Id,
                    TotalSumCount =
                        SqlFunc.AggregateCount(x.OrderVisit.Order.HotspotId.Substring(SqlFunc.MappingColumn<int>("0"),
                            SqlFunc.MappingColumn<int>("2"))),
                    VerySatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "5", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "5", 1, 0))), //非常满意数
                    SatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "4", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "4", 1, 0))), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "-1", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "-1", 1, 0))), //视为满意
                    DefaultSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "0", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "0", 1, 0))), //默认满意
                    NoSatisfiedCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2", 1, 0))), //不满意
                    NoEvaluateCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "7", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "7", 1, 0))), //未做评价
                    NoPutThroughCount = SqlFunc.IIF(dto.TypeId == 1,
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "6", 1, 0)),
                        SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "6", 1, 0))), //未接通
                })
                .ToListAsync();
        }

        //老系统数据
        if (await _statisticsHotspotSatisfiedRepository.Queryable().Where(x => x.Time >= dto.StartTime.Value && x.Time <= dto.EndTime.Value)
                .AnyAsync())
        {
            var oldList = await _statisticsHotspotSatisfiedRepository.Queryable()
                .InnerJoin<Hotspot>((x, h) =>
                    h.Id == x.HotspotId.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("2")) &&
                    h.ParentId == null)
                .GroupBy((x, h) => new
                {
                    HotspotName = h.HotSpotName,
                    HotspotId = h.Id
                })
                .Select((x, h) => new VisitAndHotspotSatisfactionStatisticsDto()
                {
                    HotspotName = h.HotSpotName,
                    HotspotId = h.Id,
                    TotalSumCount = SqlFunc.AggregateSum(x.Total),
                    VerySatisfiedCount = SqlFunc.AggregateSum(x.VerySatisfaction), //非常满意数
                    SatisfiedCount = SqlFunc.AggregateSum(x.Satisfaction), //满意数
                    RegardedAsSatisfiedCount = SqlFunc.AggregateSum(x.TreatSatisfaction), //视为满意
                    DefaultSatisfiedCount = SqlFunc.AggregateSum(x.DefaultSatisfaction), //默认满意
                    NoSatisfiedCount = SqlFunc.AggregateSum(x.Dissatisfaction), //不满意
                    NoEvaluateCount = SqlFunc.AggregateSum(x.NotEvaluated), //未做评价
                    NoPutThroughCount = SqlFunc.AggregateSum(x.BlockCall), //未接通
                })
                .ToListAsync();

            data = (from t1 in data
                    join t2 in oldList on t1.HotspotId equals t2.HotspotId into t1_t2
                    from item in t1_t2.DefaultIfEmpty()
                    select new VisitAndHotspotSatisfactionStatisticsDto()
                    {
                        HotspotName = t1.HotspotName,
                        HotspotId = t1.HotspotId,
                        TotalSumCount = t1.TotalSumCount + t1_t2.Select(x => x.TotalSumCount).FirstOrDefault(),
                        VerySatisfiedCount = t1.VerySatisfiedCount + t1_t2.Select(x => x.VerySatisfiedCount).FirstOrDefault(), //非常满意数
                        SatisfiedCount = t1.SatisfiedCount + t1_t2.Select(x => x.SatisfiedCount).FirstOrDefault(), //满意数
                        RegardedAsSatisfiedCount = t1.RegardedAsSatisfiedCount + t1_t2.Select(x => x.RegardedAsSatisfiedCount).FirstOrDefault(), //视为满意
                        DefaultSatisfiedCount = t1.DefaultSatisfiedCount + t1_t2.Select(x => x.DefaultSatisfiedCount).FirstOrDefault(), //默认满意
                        NoSatisfiedCount = t1.NoSatisfiedCount + t1_t2.Select(x => x.NoSatisfiedCount).FirstOrDefault(), //不满意
                        NoEvaluateCount = t1.NoEvaluateCount + t1_t2.Select(x => x.NoEvaluateCount).FirstOrDefault(), //未做评价
                        NoPutThroughCount = t1.NoPutThroughCount + t1_t2.Select(x => x.NoPutThroughCount).FirstOrDefault(), //未接通
                    }).ToList();
        }

        return data;
    }

    /// <summary>
    /// 热点满意度明细统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVisitDetail> VisitAndHotspotSatisfactionDetail(VisitAndHotspotPagedKeywordRequest dto)
    {
        bool IsCenter = _sessionContext.OrgIsCenter;
        var key = string.Empty;
        if (!string.IsNullOrEmpty(dto.TitleCode))
        {
            switch (dto.TitleCode)
            {
                case "verySatisfiedCount":
                    key = "5";
                    break;
                case "satisfiedCount":
                    key = "4";
                    break;
                case "regardedAsSatisfiedCount":
                    key = "-1";
                    break;
                case "defaultSatisfiedCount":
                    key = "0";
                    break;
                case "noSatisfiedCount":
                    key = "2";
                    break;
                case "noEvaluateCount":
                    key = "7";
                    break;
                case "noPutThroughCount":
                    key = "6";
                    break;
            }
        }

        return _orderVisitDetailRepository.Queryable()
            .Includes(x => x.OrderVisit, o => o.Order)
            .Where(x => x.OrderVisit.VisitTime >= dto.StartTime && x.OrderVisit.VisitTime <= dto.EndTime && x.VisitTarget == EVisitTarget.Org &&
                        x.OrderVisit.VisitState == EVisitState.Visited)
            .WhereIF(!string.IsNullOrEmpty(dto.HotspotName), x => x.OrderVisit.Order.Hotspot.HotSpotFullName.StartsWith(dto.HotspotName))
            .WhereIF(IsCenter == false, x => x.VisitOrgCode.StartsWith(_sessionContext.OrgId))
            .WhereIF(dto.TypeId is 1, x => SqlFunc.JsonField(x.OrgProcessingResults, "Key") == key)
            .WhereIF(dto.TypeId is 2, x => SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == key);
    }

    /// <summary>
    /// 话务员办件统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderBiCentreDataListVo> CentreDataList(ReportPagedRequest dto)
    {
        if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

        var query = _orderRepository.Queryable(false, false, false)
            .WhereIF(dto.StartTime.HasValue, it => it.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, it => it.CreationTime <= dto.EndTime)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), it => it.SignerName.Contains(dto.Keyword!))
            .GroupBy(it => new { it.SignerId, it.SignerName })
            .Select(it => new OrderBiCentreDataListVo
            {
                UserName = it.SignerName,
                UserId = it.SignerId,
                //Subtotal = SqlFunc.AggregateCount(x.AcceptorId),
                CentreArchive =
                    SqlFunc.AggregateSum(
                        SqlFunc.IIF(it.Status >= EOrderStatus.Filed && it.FileOrgIsCenter == true && it.AcceptType != "无效", 1, 0)), //中心归档件
                //CentreCareOf = SqlFunc.AggregateSum(SqlFunc.IIF(it.Status >= EOrderStatus.Filed && (it.FileUserRole == EFileUserType.Org || it.FileUserRole == EFileUserType.Dispatch), 1, 0)), //转办信件
                CentreCareOf = SqlFunc.AggregateSum(SqlFunc.IIF(
                    it.AcceptType != "无效" && (it.ProcessType == EProcessType.Jiaoban ||
                                              (it.ActualHandleStepName == "派单组" && it.Status < EOrderStatus.Filed) ||
                                              (it.ActualHandleStepName == "班长审批" && it.Status < EOrderStatus.Filed)), 1, 0)),
                NoCentreCareOf =
                    SqlFunc.AggregateSum(SqlFunc.IIF(it.AcceptType != "无效" && (it.Status <= EOrderStatus.HandOverToUnAccept), 1,
                        0)), //坐席待办 //中心领导?市领导? 是否在统计条件中
                //CentreCareOf = SqlFunc.AggregateSum(SqlFunc.IIF(it.Status >= EOrderStatus.Filed && it.ProcessType == EProcessType.Jiaoban, 1, 0)),
                //NoCentreCareOf = SqlFunc.AggregateSum(SqlFunc.IIF((int)x.Status < 300 && x.ExpiredTime > x.FiledTime, 1, 0)),
                Invalid = SqlFunc.AggregateSum(SqlFunc.IIF(it.AcceptType == "无效", 1, 0)),
                Repeat = SqlFunc.AggregateSum(SqlFunc.IIF(it.DuplicateIds != null && SqlFunc.JsonArrayLength(it.DuplicateIds) > 0, 1, 0)),
                Subtotal = SqlFunc.AggregateSum(SqlFunc.IIF(
                    (it.Status >= EOrderStatus.Filed && it.FileOrgIsCenter == true && it.AcceptType != "无效") ||
                    (it.AcceptType != "无效" && (it.ProcessType == EProcessType.Jiaoban ||
                                               (it.ActualHandleStepName == "派单组" && it.Status < EOrderStatus.Filed) ||
                                               (it.ActualHandleStepName == "班长审批" && it.Status < EOrderStatus.Filed))) ||
                    (it.Status <= EOrderStatus.HandOverToUnAccept) || it.AcceptType == "无效" ||
                    (it.DuplicateIds != null && SqlFunc.JsonArrayLength(it.DuplicateIds) > 0), 1, 0))
            }).MergeTable();
        switch (dto.SortField)
        {
            case "centreArchive":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.CentreArchive) : query.OrderByDescending(x => x.CentreArchive);
                break;
            case "centreCareOf":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.CentreCareOf) : query.OrderByDescending(x => x.CentreCareOf);
                break;
            case "noCentreCareOf":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.NoCentreCareOf) : query.OrderByDescending(x => x.NoCentreCareOf);
                break;
            case "invalid":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.Invalid) : query.OrderByDescending(x => x.Invalid);
                break;
            case "repeat":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.Repeat) : query.OrderByDescending(x => x.Repeat);
                break;
            case "subtotal":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.Subtotal) : query.OrderByDescending(x => x.Subtotal);
                break;
        }

        if (string.IsNullOrEmpty(dto.SortField))
        {
            query = query.OrderByDescending(x => x.Subtotal);
        }

        return query;
    }

    /// <summary>
    /// 话务员办件统计--自贡专用
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderBiCentreDataListVo> CentreDataListZG(ReportPagedRequest dto)
    {
        if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

        var query = _orderRepository.Queryable(false, false, false)
            .WhereIF(dto.StartTime.HasValue, it => it.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, it => it.CreationTime <= dto.EndTime)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), it => it.SignerName.Contains(dto.Keyword!))
            .GroupBy(it => new { it.AcceptorId })
            .Select(it => new OrderBiCentreDataListVo
            {
                UserId = it.AcceptorId,
                CentreArchive = SqlFunc.AggregateSum(SqlFunc.IIF(it.Status >= EOrderStatus.Filed && it.FileOrgIsCenter == true, 1, 0)), //中心归档件

                CentreCareOf = SqlFunc.AggregateSum(SqlFunc.IIF((it.Status >= EOrderStatus.Filed && it.FileOrgIsCenter == false) ||
               (it.ActualHandleStepName != "话务部" && it.Status < EOrderStatus.Filed && it.Status > EOrderStatus.WaitForAccept)
               , 1, 0)),//转办件(部门归档件+已开启流程且当前节点在非话务部的办理中的工单)

                NoCentreCareOf = SqlFunc.AggregateSum(SqlFunc.IIF(it.ActualHandleStepName == "话务部" &&
                it.Status < EOrderStatus.Filed && it.Status > EOrderStatus.WaitForAccept, 1, 0)),//待转办信件(当前节点为话务部，已受理未归档的工单)
                Invalid = 0,
                Repeat = 0,
                Subtotal = SqlFunc.AggregateSum(SqlFunc.IIF(it.Status > EOrderStatus.WaitForAccept, 1, 0))//排除待受理工单
            })
            .LeftJoin<User>((it, u) => it.UserId == u.Id)
            .Select((it, u) => new OrderBiCentreDataListVo
            {
                UserId = it.UserId,
                UserName = u.Name,
                CentreArchive = it.CentreArchive,
                CentreCareOf = it.CentreCareOf,
                NoCentreCareOf = it.NoCentreCareOf,
                Invalid = it.Invalid,
                Repeat = it.Repeat,
                Subtotal = it.Subtotal
            }).MergeTable()
            ;
        switch (dto.SortField)
        {
            case "centreArchive":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.CentreArchive) : query.OrderByDescending(x => x.CentreArchive);
                break;
            case "centreCareOf":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.CentreCareOf) : query.OrderByDescending(x => x.CentreCareOf);
                break;
            case "noCentreCareOf":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.NoCentreCareOf) : query.OrderByDescending(x => x.NoCentreCareOf);
                break;
            case "subtotal":
                query = dto.SortRule is 0 ? query.OrderBy(x => x.Subtotal) : query.OrderByDescending(x => x.Subtotal);
                break;
        }

        if (string.IsNullOrEmpty(dto.SortField))
        {
            query = query.OrderByDescending(x => x.Subtotal);
        }

        return query;
    }

    /// <summary>
    /// 话务员办件统计明细--自贡专用
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> CentreDataListDetailZG(CentreDataListDetailRequest dto)
    {
        var query = _orderRepository.Queryable(false, false, false)
       .WhereIF(dto.StartTime.HasValue, p => p.CreationTime >= dto.StartTime)
       .WhereIF(dto.EndTime.HasValue, p => p.CreationTime <= dto.EndTime)
       .WhereIF(!string.IsNullOrEmpty(dto.UserId), p => p.AcceptorId == dto.UserId)
       .WhereIF(!string.IsNullOrEmpty(dto.No), p => p.No == dto.No)
       .WhereIF(!string.IsNullOrEmpty(dto.Title), p => p.Title.Contains(dto.Title))
       ;
        if (dto.FieldName == "subtotal")//所有信件
            query = query.Where(p => p.Status > EOrderStatus.WaitForAccept);

        if (dto.FieldName == "centreArchive")//中心归档件
            query = query.Where(p => p.Status >= EOrderStatus.Filed && p.FileOrgIsCenter == true);

        if (dto.FieldName == "centreCareOf")//转办信件
            query = query.Where(p => (p.Status >= EOrderStatus.Filed && p.FileOrgIsCenter == false) ||
               (p.ActualHandleStepName != "话务部" && p.Status < EOrderStatus.Filed && p.Status > EOrderStatus.WaitForAccept));

        if (dto.FieldName == "noCentreCareOf")//待转办信件
            query = query.Where(p => p.ActualHandleStepName == "话务部" && p.Status < EOrderStatus.Filed && p.Status > EOrderStatus.WaitForAccept);

        query = query.OrderByDescending(p => p.CreationTime);

        return query;
    }

    /// <summary>
    /// 工单业务量统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVolumeDataListVo> OrderVolumeStatistics(ReportPagedRequest dto)
    {
        if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

        var query1 = _orderRepository.Queryable(false, false, false)
            .RightJoin<OrderVisit>((o, v) => o.No == v.No)
            .Where((o, v) => v.VisitState == EVisitState.Visited)
            .WhereIF(dto.StartTime.HasValue, (o, v) => v.VisitTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, (o, v) => v.VisitTime <= dto.EndTime)
            .GroupBy((o, v) => new { v.EmployeeId })
            .Select((o, v) => new OrderVolumeDataListVo
            {
                UserId = v.EmployeeId,
                UserName = "",
                VisitCenter = SqlFunc.AggregateSum(
                        SqlFunc.IIF(v.Order.ActualHandleOrgCode == OrgSeedData.CenterId, 1, 0)), //中心归档件
                VisitOrg = SqlFunc.AggregateSum(
                        SqlFunc.IIF(v.Order.ActualHandleOrgCode != OrgSeedData.CenterId, 1, 0)), //部门归档件
                PublishCenter = 0,
                PublishOrg = 0,
                PublishOpen = 0,
                DispatchCenter = 0,
                DispatchOrg = 0,
                ReTransact = 0,
                Subtotal = 0
            }).MergeTable();

        var query2 = _orderRepository.Queryable(false, false, false)
            .RightJoin<OrderPublish>((o, p) => o.No == p.No)
            .WhereIF(dto.StartTime.HasValue, (o, p) => p.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, (o, p) => p.CreationTime <= dto.EndTime)
            .GroupBy((o, p) => new { p.CreatorId })
            .Select((o, p) => new OrderVolumeDataListVo
            {
                UserId = p.CreatorId,
                UserName = "",
                VisitCenter = 0,
                VisitOrg = 0,
                PublishCenter = SqlFunc.AggregateSum(
                        SqlFunc.IIF(p.Order.ActualHandleOrgCode == OrgSeedData.CenterId, 1, 0)), //中心归档发布量
                PublishOrg = SqlFunc.AggregateSum(
                        SqlFunc.IIF(p.Order.ActualHandleOrgCode != OrgSeedData.CenterId, 1, 0)), //部门归档发布量
                PublishOpen = SqlFunc.AggregateSum(
                        SqlFunc.IIF(p.PublishState == true, 1, 0)),                              //公开发布量
                DispatchCenter = 0,
                DispatchOrg = 0,
                ReTransact = 0,
                Subtotal = 0
            }).MergeTable();

        var query3 = _workflowTraceRepository.Queryable()
            .Where(o => o.PrevStepName == "派单组" && o.ModuleCode == "OrderHandle")
            .WhereIF(dto.StartTime.HasValue, o => o.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, o => o.CreationTime <= dto.EndTime)
            .GroupBy(o => new { o.CreatorId })
            .Select(o => new OrderVolumeDataListVo
            {
                UserId = o.CreatorId,
                UserName = "",
                VisitCenter = 0,
                VisitOrg = 0,
                PublishCenter = 0,
                PublishOrg = 0,
                PublishOpen = 0,
                DispatchCenter = SqlFunc.AggregateSum(
                        SqlFunc.IIF(o.HandlerOrgId == OrgSeedData.CenterId, 1, 0)), //中心派单量
                DispatchOrg = SqlFunc.AggregateSum(
                        SqlFunc.IIF(o.HandlerOrgId != OrgSeedData.CenterId, 1, 0)), //部门派单量
                ReTransact = 0,
                Subtotal = 0
            }).MergeTable();

        var query4 = _orderSpecialRepository.Queryable()
            .WhereIF(dto.StartTime.HasValue, o => o.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, o => o.CreationTime <= dto.EndTime)
            .GroupBy(o => new { o.CreatorId })
            .Select(o => new OrderVolumeDataListVo
            {
                UserId = o.CreatorId,
                UserName = "",
                VisitCenter = 0,
                VisitOrg = 0,
                PublishCenter = 0,
                PublishOrg = 0,
                PublishOpen = 0,
                DispatchCenter = 0,
                DispatchOrg = 0,
                ReTransact = SqlFunc.AggregateSum(SqlFunc.IIF(o.SpecialType == ESpecialType.ReTransact, 1, 0)), //重办信件量
                Subtotal = 0
            }).MergeTable();

        var query = _orderRepository.UnionAll(query1, query2, query3, query4)
                                    .LeftJoin<User>((x, y) => x.UserId == y.Id)
                                    .GroupBy((x, y) => new { x.UserId, y.Name })
                                    .Where((x, y) => y.OrgId == OrgSeedData.CenterId)
                                    .Select((x, y) => new OrderVolumeDataListVo
                                    {
                                        UserId = x.UserId,
                                        UserName = y.Name,
                                        VisitCenter = SqlFunc.AggregateSum(x.VisitCenter),       //中心归档件
                                        VisitOrg = SqlFunc.AggregateSum(x.VisitOrg),             //部门归档件
                                        PublishCenter = SqlFunc.AggregateSum(x.PublishCenter),   //中心归档发布量
                                        PublishOrg = SqlFunc.AggregateSum(x.PublishOrg),         //部门归档发布量
                                        PublishOpen = SqlFunc.AggregateSum(x.PublishOpen),       //公开发布量
                                        DispatchCenter = SqlFunc.AggregateSum(x.DispatchCenter), //中心派单量
                                        DispatchOrg = SqlFunc.AggregateSum(x.DispatchOrg),       //部门派单量
                                        ReTransact = SqlFunc.AggregateSum(x.ReTransact),         //重办信件量
                                        Subtotal = SqlFunc.AggregateSum(x.VisitCenter) + SqlFunc.AggregateSum(x.VisitOrg) +
                                                   SqlFunc.AggregateSum(x.PublishCenter) + SqlFunc.AggregateSum(x.PublishOrg) +
                                                   SqlFunc.AggregateSum(x.PublishOpen) + SqlFunc.AggregateSum(x.DispatchCenter) +
                                                   SqlFunc.AggregateSum(x.DispatchOrg) + SqlFunc.AggregateSum(x.ReTransact)
                                    });
        return query;
    }

    /// <summary>
    /// 工单业务量明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> OrderVolumeList(QueryOrderVolumeDto dto)
    {
        if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");
        if (string.IsNullOrEmpty(dto.UserID)) throw UserFriendlyException.SameMessage("请传入UserID!");
        if (string.IsNullOrEmpty(dto.FieldType)) throw UserFriendlyException.SameMessage("请传入FieldType!");
        if (dto.FieldType != "visitCenter" &&
            dto.FieldType != "visitOrg" &&
            dto.FieldType != "publishCenter" &&
            dto.FieldType != "publishOrg" &&
            dto.FieldType != "publishOpen" &&
            dto.FieldType != "dispatchCenter" &&
            dto.FieldType != "dispatchOrg" &&
            dto.FieldType != "reTransact")
            throw UserFriendlyException.SameMessage("请传入正确FieldType!");

        var query = _orderRepository.Queryable(canView: false);
        query = query.Includes(d => d.OrderScreens).Includes(d => d.OrderTags);

        if (dto.FieldType == "visitCenter" || dto.FieldType == "visitOrg")
        {
            #region 回访
            if (dto.FieldType == "visitCenter")
            {
                //中心归档件
                query = query.RightJoin<OrderVisit>((d, v) => d.No == v.No)
                             .Where((d, v) => v.VisitState == EVisitState.Visited)
                             .Where((d, v) => v.Order.ActualHandleOrgCode == OrgSeedData.CenterId)
                             .Where((d, v) => v.EmployeeId == dto.UserID)
                             .WhereIF(dto.StartTime.HasValue, (d, v) => v.VisitTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, v) => v.VisitTime <= dto.EndTime);
            }
            else if (dto.FieldType == "visitOrg")
            {
                //部门归档件
                query = query.RightJoin<OrderVisit>((d, v) => d.No == v.No)
                             .Where((d, v) => v.VisitState == EVisitState.Visited)
                             .Where((d, v) => v.Order.ActualHandleOrgCode != OrgSeedData.CenterId)
                             .Where((d, v) => v.EmployeeId == dto.UserID)
                             .WhereIF(dto.StartTime.HasValue, (d, v) => v.VisitTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, v) => v.VisitTime <= dto.EndTime);
            }
            #endregion
        }
        else if (dto.FieldType == "publishCenter" || dto.FieldType == "publishOrg" || dto.FieldType == "publishOpen")
        {
            #region 发布
            if (dto.FieldType == "publishCenter")
            {
                //中心归档发布量
                query = query.RightJoin<OrderPublish>((d, p) => d.No == p.No)
                             .Where((d, p) => p.CreatorId == dto.UserID)
                             .Where((d, p) => p.Order.ActualHandleOrgCode == OrgSeedData.CenterId)
                             .WhereIF(dto.StartTime.HasValue, (d, p) => p.CreationTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, p) => p.CreationTime <= dto.EndTime);
            }
            else if (dto.FieldType == "publishOrg")
            {
                //部门归档发布量
                query = query.RightJoin<OrderPublish>((d, p) => d.No == p.No)
                             .Where((d, p) => p.CreatorId == dto.UserID)
                             .Where((d, p) => p.Order.ActualHandleOrgCode != OrgSeedData.CenterId)
                             .WhereIF(dto.StartTime.HasValue, (d, p) => p.CreationTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, p) => p.CreationTime <= dto.EndTime);
            }
            else if (dto.FieldType == "publishOpen")
            {
                //公开发布量
                query = query.RightJoin<OrderPublish>((d, p) => d.No == p.No)
                             .Where((d, p) => p.CreatorId == dto.UserID)
                             .Where((d, p) => p.PublishState == true)
                             .WhereIF(dto.StartTime.HasValue, (d, p) => p.CreationTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, p) => p.CreationTime <= dto.EndTime);
            }
            #endregion
        }
        else if (dto.FieldType == "dispatchCenter" || dto.FieldType == "dispatchOrg")
        {
            #region 派单
            if (dto.FieldType == "dispatchCenter")
            {
                //中心派单量
                query = query.InnerJoin(_workflowTraceRepository.Queryable(), (d, w) => d.Id == w.ExternalId)
                             .WhereIF(dto.StartTime.HasValue, (d, w) => w.CreationTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, w) => w.CreationTime <= dto.EndTime)
                             .Where((d, w) => w.CreatorId == dto.UserID)
                             .Where((d, w) => w.PrevStepName == "派单组" && w.ModuleCode == "OrderHandle")
                             .Where((d, w) => w.HandlerOrgId == OrgSeedData.CenterId);
            }
            else if (dto.FieldType == "dispatchOrg")
            {
                //部门派单量
                query = query.InnerJoin(_workflowTraceRepository.Queryable(), (d, w) => d.Id == w.ExternalId)
                             .WhereIF(dto.StartTime.HasValue, (d, w) => w.CreationTime >= dto.StartTime)
                             .WhereIF(dto.EndTime.HasValue, (d, w) => w.CreationTime <= dto.EndTime)
                             .Where((d, w) => w.CreatorId == dto.UserID)
                             .Where((d, w) => w.PrevStepName == "派单组" && w.ModuleCode == "OrderHandle")
                             .Where((d, w) => w.HandlerOrgId != OrgSeedData.CenterId);
            }
            #endregion
        }
        else if (dto.FieldType == "reTransact")
        {
            // 重办
            query = query.InnerJoin(_orderSpecialRepository.Queryable(), (d, r) => d.Id == r.OrderId)
                         .WhereIF(dto.StartTime.HasValue, (d, r) => r.CreationTime >= dto.StartTime)
                         .WhereIF(dto.EndTime.HasValue, (d, r) => r.CreationTime <= dto.EndTime)
                         .Where((d, r) => r.CreatorId == dto.UserID)
                         .Where((d, r) => r.SpecialType == ESpecialType.ReTransact);
        }

        query = query
                .WhereIF(!string.IsNullOrEmpty(dto.PoliticalIdentityValue), d => d.PoliticalIdentityValue == dto.PoliticalIdentityValue)//政治身份查询
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.Contains(dto.Keyword!)) //标题
                .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Title.Contains(dto.Title!)) //标题
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceNo), d => d.ProvinceNo.Contains(dto.ProvinceNo)) //省本地编号
                .WhereIF(!string.IsNullOrEmpty(dto.ReceiveProvinceNo), d => d.ReceiveProvinceNo.Contains(dto.ReceiveProvinceNo)) //省编号
                .WhereIF(dto.IsSecret.HasValue, d => d.IsSecret == dto.IsSecret.Value)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value, d => d.ReTransactNum > 0)
                .WhereIF(dto.IsReTransact.HasValue && dto.IsReTransact.Value == false, d => d.ReTransactNum == null || d.ReTransactNum == 0)
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No)) //工单编码
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.AcceptTypeCode == dto.AcceptType) //受理类型
                                                                                                         //.WhereIF(dto.AcceptTypes.Any(), d => dto.AcceptTypes.Contains(d.AcceptTypeCode)) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.SourceChannelCode == dto.Channel)
                //.WhereIF(dto.Channels.Any(), d => dto.Channels.Contains(d.SourceChannelCode)) //来源渠道
                //.WhereIF(dto.HotspotIds.Any(), d => dto.HotspotIds.Contains(d.HotspotId)) //热点类型
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.HotspotSpliceName != null && d.HotspotSpliceName.Contains(dto.Hotspot))
                .WhereIF(!string.IsNullOrEmpty(dto.TransferPhone), d => d.TransferPhone == dto.TransferPhone!) //转接号码
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => d.Workflow.Assigns.Any(s => dto.OrgCodes.Contains(s.OrgCode)))
                                                                                                               //.WhereIF(dto.OrgCodes.Any(), d => dto.OrgCodes.Contains(d.ActualHandleOrgCode)) //接办部门
                                                                                                               //.WhereIF(!string.IsNullOrEmpty(dto.OrgId), d => d.CurrentHandleOrgId == dto.OrgId)//接办部门
                .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
                .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo), d => d.AcceptorName == dto.NameOrNo! || d.AcceptorStaffNo == dto.NameOrNo!) //受理人/坐席
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(dto.StartTimeStart.HasValue, d => d.StartTime >= dto.StartTimeStart) //流程开启时间开始
                .WhereIF(dto.StartTimeEnd.HasValue, d => d.StartTime <= dto.StartTimeEnd) //流程开启时间结束
                                                                                          //.WhereIF(dto.EmergencyLevels.Any(), d => dto.EmergencyLevels.Contains(d.EmergencyLevel))  //紧急程度
                .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone.Contains(dto.FromPhone)) //来电号码
                .WhereIF(!string.IsNullOrEmpty(dto.PhoneNo), d => d.Contact.Contains(dto.PhoneNo)) //联系电话
                                                                                                   //.WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), d => d.PushTypeCode == dto.PushTypeCode) //推送分类
                .WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), x => x.OrderPushTypes.Any(opt => opt.PushTypeCode == dto.PushTypeCode)) //推送分类
                .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
                .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
                                                                                                //.WhereIF(dto.Statuses.Any(), d => dto.Statuses.Contains(d.Status))  //工单状态
                .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status) //工单状态
                                                                           //.WhereIF(dto.Statuses.Any(d => d == EOrderStatus.SpecialToUnAccept), d => d.Status <= EOrderStatus.SpecialToUnAccept)
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName), d => d.ActualHandlerName == dto.ActualHandlerName) //接办人
                .WhereIF(dto.IsScreen == true, d => d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //有甄别
                .WhereIF(dto.IsScreen == false, d => !d.OrderScreens.Any(x => x.Status != EScreenStatus.Refuse)) //无甄别
                .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepCode), d => d.CurrentStepCode == dto.CurrentStepCode) //当前办理节点
                .WhereIF(dto.ActualHandleTimeStart.HasValue, d => d.FiledTime >= dto.ActualHandleTimeStart) //办结时间开始
                .WhereIF(dto.ActualHandleTimeEnd.HasValue, d => d.FiledTime <= dto.ActualHandleTimeEnd) //办结时间结束
                .WhereIF(dto.IsOverTime == true,
                    d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime < d.FiledTime && d.Status >= EOrderStatus.Filed)) //是 超期
                .WhereIF(dto.IsOverTime == false,
                    d => (d.ExpiredTime > DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime > d.FiledTime && d.Status >= EOrderStatus.Filed)) //否 超期
                .WhereIF(dto.IdentityType != null, d => d.IdentityType == dto.IdentityType) //来电主体
                .WhereIF(!string.IsNullOrEmpty(dto.FromName), d => d.FromName == dto.FromName) //来电人姓名                  
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") > 0,
                    d => d.AreaCode.StartsWith(SqlFunc.Substring(dto.AreaCode, 0, 4)))           //区域
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode) && dto.AreaCode.LastIndexOf("00") <= 0, d => d.AreaCode.StartsWith(dto.AreaCode))
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch != true, d => d.IsProvince == true)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false && dto.ProvinceSearch != true, d => d.IsProvince == false)
                .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true && dto.ProvinceSearch == true, d => d.Source == ESource.ProvinceStraight)
                .WhereIF(!string.IsNullOrEmpty(dto.SensitiveWord), d => SqlFunc.JsonArrayAny(d.Sensitive, dto.SensitiveWord))
                .WhereIF(dto.IsSensitiveWord.HasValue && dto.IsSensitiveWord == true,
                    d => d.Sensitive != null && SqlFunc.JsonArrayLength(d.Sensitive) > 0)
                .WhereIF(dto.IsUrgent.HasValue, d => d.IsUrgent == dto.IsUrgent.Value)
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "1", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == false) //政民互动直派
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "2", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "SZMHD" && d.IsProvince == true) //政民互动
                .WhereIF(!string.IsNullOrEmpty(dto.ProvinceChannel) && dto.ProvinceChannel == "3", d => d.Source == ESource.ProvinceStraight &&
                    d.SourceChannelCode == "S12345" && d.IsProvince == true) //省12345
                                                                             //.WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval),d => d.Title.Contains(dto.ContentRetrieval) || d.Content.Contains(dto.ContentRetrieval) || d.FileOpinion.Contains(dto.ContentRetrieval) || d.ActualOpinion.Contains(dto.ContentRetrieval))
                .WhereIF(!string.IsNullOrEmpty(dto.ContentRetrieval), d => d.Content.Contains(dto.ContentRetrieval!))
                .WhereIF(!string.IsNullOrEmpty(dto.FileOption), d => d.FileOpinion.Contains(dto.FileOption!))
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == true, d => d.CurrentStepAcceptTime != null)
                .WhereIF(dto.IsSgin.HasValue && dto.IsSgin == false, d => d.CurrentStepAcceptTime == null)
                .WhereIF(dto.FiledType is FiledType.CenterFiled, d => d.FileOrgIsCenter == true) //d => d.ProcessType == EProcessType.Zhiban
                .WhereIF(dto.FiledType is FiledType.OrgFiled, d => d.FileOrgIsCenter == false) //d => d.ProcessType == EProcessType.Jiaoban
                .WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTagCode)) //工单标签
                .WhereIF(!string.IsNullOrEmpty(dto.FocusOnEvents),
                    d => d.FocusOnEvents.Contains(dto.FocusOnEvents)) //!string.IsNullOrEmpty(d.FocusOnEvents) && SqlFunc.SplitIn(d.FocusOnEvents, dto.FocusOnEvents))
                .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc) //默认排序时间为创建时间
                .OrderByIF(dto is { SortField: "no", SortRule: 0 }, d => d.No, OrderByType.Asc) //工单编号升序
                .OrderByIF(dto is { SortField: "no", SortRule: 1 }, d => d.No, OrderByType.Desc) //工单编号降序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 0 }, d => d.IsProvince, OrderByType.Asc) //是否省工单升序
                .OrderByIF(dto is { SortField: "isProvinceText", SortRule: 1 }, d => d.IsProvince, OrderByType.Desc) //是否省工单降序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 0 }, d => d.ReTransactNum, OrderByType.Asc) //重办次数升序
                .OrderByIF(dto is { SortField: "reTransactNum", SortRule: 1 }, d => d.ReTransactNum, OrderByType.Desc) //重办次数降序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 0 }, d => d.IsUrgent, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isUrgentText", SortRule: 1 }, d => d.IsUrgent, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 0 }, d => d.IsSecret, OrderByType.Asc) //是否紧急升序
                .OrderByIF(dto is { SortField: "isSecret", SortRule: 1 }, d => d.IsSecret, OrderByType.Desc) //是否紧急降序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 0 }, d => d.CurrentStepName, OrderByType.Asc) //当前节点升序
                .OrderByIF(dto is { SortField: "currentStepName", SortRule: 1 }, d => d.CurrentStepName, OrderByType.Desc) //当前节点降序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 0 }, d => d.ActualHandleStepAcceptTime.HasValue, OrderByType.Asc) //受理情况升序
                .OrderByIF(dto is { SortField: "actualStepAcceptText", SortRule: 1 }, d => d.ActualHandleStepAcceptTime.HasValue, OrderByType.Desc) //受理情况降序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 0 }, d => d.Status, OrderByType.Asc) //工单状态升序
                .OrderByIF(dto is { SortField: "statusText", SortRule: 1 }, d => d.Status, OrderByType.Desc) //工单状态降序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, d => d.StartTime, OrderByType.Asc) //受理时间升序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, d => d.StartTime, OrderByType.Desc) //受理时间降序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, d => d.ExpiredTime, OrderByType.Asc) //超期时间升序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, d => d.ExpiredTime, OrderByType.Desc) //超期时间降序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, d => d.FiledTime, OrderByType.Asc) //办结时间升序
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, d => d.FiledTime, OrderByType.Desc) //办结时间降序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 0 }, d => d.OrgLevelOneName, OrderByType.Asc) //一级部门升序
                .OrderByIF(dto is { SortField: "orgLevelOneName", SortRule: 1 }, d => d.OrgLevelOneName, OrderByType.Desc) //一级部门降序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 0 }, d => d.OrgLevelTwoName, OrderByType.Asc) //二级部门升序
                .OrderByIF(dto is { SortField: "orgLevelTwoName", SortRule: 1 }, d => d.OrgLevelTwoName, OrderByType.Desc) //二级部门降序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 0 }, d => d.ActualHandleOrgName, OrderByType.Asc) //接办部门升序
                .OrderByIF(dto is { SortField: "actualHandleOrgName", SortRule: 1 }, d => d.ActualHandleOrgName, OrderByType.Desc) //接办部门降序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 0 }, d => d.AcceptTypeCode, OrderByType.Asc) //受理类型升序
                .OrderByIF(dto is { SortField: "acceptType", SortRule: 1 }, d => d.AcceptTypeCode, OrderByType.Desc) //受理类型降序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 0 }, d => d.CounterSignType, OrderByType.Asc) //是否会签升序
                .OrderByIF(dto is { SortField: "counterSignTypeText", SortRule: 1 }, d => d.CounterSignType, OrderByType.Desc) //是否会签降序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 0 }, d => d.HotspotSpliceName, OrderByType.Asc) //热点分类全称升序
                .OrderByIF(dto is { SortField: "hotspotSpliceName", SortRule: 1 }, d => d.HotspotSpliceName, OrderByType.Desc) //热点分类全称降序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 0 }, d => d.HotspotName, OrderByType.Asc) //热点分类升序
                .OrderByIF(dto is { SortField: "hotspotName", SortRule: 1 }, d => d.HotspotName, OrderByType.Desc) //热点分类降序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 0 }, d => d.AcceptorName, OrderByType.Asc) //受理人升序
                .OrderByIF(dto is { SortField: "acceptorName", SortRule: 1 }, d => d.AcceptorName, OrderByType.Desc) //受理人降序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 0 }, d => d.CurrentStepAcceptTime, OrderByType.Asc) //接办时间升序
                .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 1 }, d => d.CurrentStepAcceptTime, OrderByType.Desc) //接办时间降序
            ;
        return query;
    }

    /// <summary>
    /// 热点受理类型统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<(List<SystemDicData> acceptTypes, object items)> HotspotAndAcceptTypeStatistics(HotspotAndAcceptTypeStatisticsReq dto)
    {
        var dicList = _systemDicDataRepository.Queryable().Where(x => x.DicTypeCode == "AcceptType").OrderBy(x => x.Sort).MergeTable();
        var endIndex = (2 * dto.HotspotLevel).ToString();
        var hotspotList = _hotspotRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == int.Parse(endIndex))
            .Select(x => new
            {
                HotspotId = x.Id,
                HotspotName = x.HotSpotFullName,
            }).MergeTable();

        var orderList = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime < dto.EndTime)
            .Select(x => new
            {
                HotspotId = x.HotspotId.Substring(0, int.Parse(endIndex)),
                AcceptTypeCode = x.AcceptTypeCode,
            }).MergeTable();

        var hotListAndOrder = hotspotList.LeftJoin(orderList, (it, o) => it.HotspotId == o.HotspotId)
            .GroupBy((it, o) => new
            {
                it.HotspotId,
                it.HotspotName,
                AcceptTypeCode = o.AcceptTypeCode,
            })
            .OrderBy((it, o) => it.HotspotId)
            .Select((it, o) => new
            {
                HotspotId = it.HotspotId,
                HotspotName = it.HotspotName,
                AcceptTypeCode = o.AcceptTypeCode,
                Count = SqlFunc.AggregateCount(it.HotspotId)
            }).MergeTable();

        var returnList = await dicList.LeftJoin(hotListAndOrder, (pp, dd) => pp.DicDataValue == dd.AcceptTypeCode)
            .GroupBy((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AcceptTypeCode = pp.DicDataValue,
                AcceptType = pp.DicDataName,
            })
            .OrderBy((pp, dd) => dd.HotspotId)
            .Select((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AcceptTypeCode = pp.DicDataValue,
                AcceptType = pp.DicDataName,
                Count = SqlFunc.AggregateSum(dd.Count)
            }).ToPivotListAsync(q => q.AcceptTypeCode, q => new { q.HotspotName, q.HotspotId }, q => q.Sum(x => x.Count));

        var titleList = await _systemDicDataRepository.Queryable().Where(x => x.DicTypeCode == "AcceptType").OrderBy(x => x.Sort).ToListAsync();
        return (titleList, returnList);
    }

    /// <summary>
    /// 热点受理类型统计--导出
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<DataTable> HotspotAndAcceptTypeStatisticsExport(HotspotAndAcceptTypeStatisticsReq dto)
    {
        var dicList = _systemDicDataRepository.Queryable().Where(x => x.DicTypeCode == "AcceptType").OrderBy(x => x.Sort).MergeTable();
        var endIndex = (2 * dto.HotspotLevel).ToString();
        var hotspotList = _hotspotRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == int.Parse(endIndex))
            .Select(x => new
            {
                HotspotId = x.Id,
                HotspotName = x.HotSpotFullName,
            }).MergeTable();

        var orderList = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime < dto.EndTime)
            .Select(x => new
            {
                HotspotId = x.HotspotId.Substring(0, int.Parse(endIndex)),
                AcceptTypeCode = x.AcceptTypeCode,
            }).MergeTable();

        var hotListAndOrder = hotspotList.LeftJoin(orderList, (it, o) => it.HotspotId == o.HotspotId)
            .GroupBy((it, o) => new
            {
                it.HotspotId,
                it.HotspotName,
                AcceptTypeCode = o.AcceptTypeCode,
            })
            .OrderBy((it, o) => it.HotspotId)
            .Select((it, o) => new
            {
                HotspotId = it.HotspotId,
                HotspotName = it.HotspotName,
                AcceptTypeCode = o.AcceptTypeCode,
                Count = SqlFunc.AggregateCount(it.HotspotId)
            }).MergeTable();


        var returnList = await dicList.LeftJoin(hotListAndOrder, (pp, dd) => pp.DicDataValue == dd.AcceptTypeCode)
            .GroupBy((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AcceptTypeCode = pp.DicDataValue,
                AcceptType = pp.DicDataName,
            })
            .OrderBy((pp, dd) => dd.HotspotId)
            .Select((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AcceptTypeCode = pp.DicDataValue,
                AcceptType = pp.DicDataName,
                Count = SqlFunc.AggregateSum(dd.Count)
            }).ToPivotTableAsync(q => q.AcceptTypeCode, q => new { q.HotspotName }, q => q.Sum(x => x.Count));
        //returnList.Rows.RemoveAt(returnList.Rows.Count-1);
        return returnList;
    }

    /// <summary>
    /// 热点受理类型统计明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> HotspotAndAcceptTypeStatisticsDetail(HotspotAndAcceptTypeStatisticsDetailReq dto)
    {
        var query = _orderRepository.Queryable()
            .Where(x => x.HotspotId.StartsWith(dto.HotspotId) && x.CreationTime >= dto.StartTime && x.CreationTime < dto.EndTime)
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptTypeCode), x => x.AcceptTypeCode.StartsWith(dto.AcceptTypeCode))
            .OrderByDescending(x => x.CreationTime);
        return query;
    }

    /// <summary>
    /// 甄别申请统计
    /// </summary>
    /// <returns></returns>
    public ISugarQueryable<OrderScreenApplyVo> OrderScreenApply(OrderScreenApplyPagedRequest dto)
    {
        var query = _orderScreenRepository.Queryable()
            .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
            .WhereIF(!string.IsNullOrEmpty(dto.ApplyUserName), x => x.CreatorName == dto.ApplyUserName)
            .WhereIF(!string.IsNullOrEmpty(dto.ApplyOrgName), x => x.CreatorOrgName == dto.ApplyOrgName)
            .GroupBy(x => new { ApplyTime = x.CreationTime.ToString("yyyy-MM-dd"), x.CreatorName, x.CreatorOrgName })
            .Select(x => new OrderScreenApplyVo
            {
                ApplyTime = x.CreationTime.ToString("yyyy-MM-dd"),
                ApplyUserName = x.CreatorName,
                ApplyOrgName = x.CreatorOrgName,
                ApplyNum = SqlFunc.AggregateCount(1)
            });
        return query;
    }

    /// <summary>
    /// 甄别审批统计
    /// </summary>
    /// <returns></returns>
    public ISugarQueryable<OrderScreenAuditVo> OrderScreenAudit(OrderScreenAuditPagedRequest dto)
    {
        if (_appOptions.Value.IsZiGong)
        {
            return _workflowTraceRepository.Queryable()
                .Where(x => x.ModuleCode == "OrderScreen")
                .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.HandleTime >= dto.StartTime && x.HandleTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.AuditUserName), x => x.HandlerName == dto.AuditUserName)
                .Where(x => x.HandlerName != null && x.HandlerName != "")
                .WhereIF(!string.IsNullOrEmpty(dto.StepName), x => x.Name == dto.StepName)
                //.WhereIF(dto.AuditType is 1, x => x.Name == "班长审批")
                //.WhereIF(dto.AuditType is 2, x => x.Name == "中心领导")
                // .WhereIF(_appOptions.Value.IsZiGong && dto.AuditType is 3, x => x.Name == "中心初审")
                .GroupBy(x => new { x.HandlerName, x.Name })
                .Select(x => new OrderScreenAuditVo
                {
                    AuditName = x.HandlerName,
                    StepName = x.Name,
                    //AuditNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.TraceType == EWorkflowTraceType.Normal && x.TraceState == EWorkflowTraceState.Normal, 1, 0)),
                    AuditNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.TraceType == EWorkflowTraceType.Normal && x.TraceState == EWorkflowTraceState.Normal && x.ReviewResult == EReviewResult.Approval, 1, 0)),
                    AuditNoNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.TraceType == EWorkflowTraceType.Normal && x.TraceState == EWorkflowTraceState.Normal && x.ReviewResult == EReviewResult.Failed, 1, 0)),
                    AuditBackNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.TraceState == EWorkflowTraceState.StepRemoveByPrevious || x.TraceState == EWorkflowTraceState.StepRemoveByRecall, 1, 0)),
                });
        }
        else
        {
            return _workflowTraceRepository.Queryable()
               .Where(x => x.ModuleCode == "OrderScreen")
               .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.HandleTime >= dto.StartTime && x.HandleTime <= dto.EndTime)
               .WhereIF(!string.IsNullOrEmpty(dto.AuditUserName), x => x.HandlerName == dto.AuditUserName)
               .Where(x => x.HandlerName != null && x.HandlerName != "")
               .WhereIF(dto.AuditType is 1, x => x.Name == "班长审批")
               .WhereIF(dto.AuditType is 2, x => x.Name == "中心领导")
               .WhereIF(_appOptions.Value.IsZiGong && dto.AuditType is 3, x => x.Name == "中心初审")
               .GroupBy(x => new { x.HandlerName })
               .Select(x => new OrderScreenAuditVo
               {
                   AuditName = x.HandlerName,
                   AuditNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.TraceType == EWorkflowTraceType.Normal && x.TraceState == EWorkflowTraceState.Normal, 1, 0)),
                   AuditBackNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.TraceState == EWorkflowTraceState.StepRemoveByPrevious, 1, 0)),
               });
        }
    }

    /// <summary>
    /// 中心受理统计（日期）
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderCenterAcceptVo> OrderCenterAccept(OrderCenterAcceptPagedRequest dto)
    {
        var sendBack = _orderSendBackAuditRepository.Queryable()
            .Where(x => x.State == ESendBackAuditState.End)
            .GroupBy(x => x.OrderId).Select(x => new { OrderId = x.OrderId });

        var query = _orderRepository.Queryable()
            .LeftJoin(sendBack, (d, s) => d.Id == s.OrderId)
            .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, d => d.CreationTime >= dto.StartTime && d.CreationTime <= dto.EndTime)
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 1, d => d.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 2, d => d.IdentityType == EIdentityType.Enterprise)
            .GroupBy(d => d.CreationTime.ToString("yyyy-MM-dd"))
            .Select((d, s) => new OrderCenterAcceptVo
            {
                Time = d.CreationTime.ToString("yyyy-MM-dd"),
                AcceptNum = SqlFunc.AggregateCount(1),
                ValidNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.AcceptType != "无效", 1, 0)),
                RepetitionNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.DuplicateIds == null || SqlFunc.JsonArrayLength(d.DuplicateIds) > 0, 1, 0)),
                InvalidNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.AcceptType == "无效", 1, 0)),
                HandleNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.Status >= EOrderStatus.Filed, 1, 0)),
                NoHandleNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.Status < EOrderStatus.Filed, 1, 0)),
                BackNum = SqlFunc.AggregateSum(SqlFunc.IIF(s.OrderId != null && s.OrderId != "", 1, 0)),
                DutyDeskNum = SqlFunc.AggregateDistinctCount(d.AcceptorId)
            });
        return query;
    }

    /// <summary>
    /// 中心受理统计（值班坐席）
    /// </summary>
    /// <returns></returns>
    public ISugarQueryable<OrderCenterAcceptUserVo> OrderCenterAcceptUser(OrderCenterAcceptPagedRequest dto)
    {
        var sendBack = _orderSendBackAuditRepository.Queryable()
            .Where(x => x.State == ESendBackAuditState.End)
            .GroupBy(x => x.OrderId).Select(x => new { OrderId = x.OrderId });

        var query = _orderRepository.Queryable()
            .LeftJoin(sendBack, (d, s) => d.Id == s.OrderId)
            .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, d => d.CreationTime >= dto.StartTime && d.CreationTime <= dto.EndTime)
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 1, d => d.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeCode != null && dto.TypeCode == 2, d => d.IdentityType == EIdentityType.Enterprise)
            .GroupBy(d => d.AcceptorName)
            .Select((d, s) => new OrderCenterAcceptUserVo
            {
                AcceptUserName = d.AcceptorName,
                AcceptNum = SqlFunc.AggregateCount(1),
                ValidNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.AcceptType != "无效", 1, 0)),
                RepetitionNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.DuplicateIds == null || SqlFunc.JsonArrayLength(d.DuplicateIds) > 0, 1, 0)),
                InvalidNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.AcceptType == "无效", 1, 0)),
                HandleNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.Status >= EOrderStatus.Filed, 1, 0)),
                NoHandleNum = SqlFunc.AggregateSum(SqlFunc.IIF(d.Status < EOrderStatus.Filed, 1, 0)),
                BackNum = SqlFunc.AggregateSum(SqlFunc.IIF(s.OrderId != null && s.OrderId != "", 1, 0))
            });
        return query;
    }

    #region 甄别

    public ISugarQueryable<OrderScreen> OrderScreenList(ScreenListDto dto)
    {
        var handler = dto.TabStatus is EScreenStatus.Apply;
        var isAdmin = _orderDomainService.IsCheckAdmin();
        ISugarQueryable<OrderScreen> query;

        if (dto.source == 1)
        {
            query = _orderScreenRepository.Queryable(hasHandled: !handler, isAdmin: isAdmin);
        }
        else
        {
            query = _orderScreenRepository.Queryable(isAdmin: isAdmin)
                .WhereIF(!isAdmin, d => d.CreatorOrgId.StartsWith(_sessionContext.RequiredOrgId));
        }

        return query
            .Includes(d => d.Order)
            .Includes(d => d.VisitDetail)
            .Includes(d => d.Visit, v => v.Order)
            .Includes(d => d.Workflow)
            .Includes(d => d.ScreenDetails.Where(sd => sd.AuditUserId == _sessionContext.UserId).OrderByDescending(sd => sd.AuditTime).Take(1)
                .ToList())
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Visit.Order.Title.Contains(dto.Title!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Visit.Order.No.Contains(dto.No!))
            .WhereIF(dto.TabStatus is EScreenStatus.Apply,
                d => (d.Status == EScreenStatus.Apply || d.Status == EScreenStatus.Approval ||
                      (d.Status == EScreenStatus.SendBack && d.SendBackApply == false)))
            .WhereIF(dto.TabStatus.HasValue && dto.Status == EScreenStatus.MyHandle, d => (d.Status != EScreenStatus.Apply))
            .WhereIF(dto.DataScope is 1, d => d.CreatorId == _sessionContext.RequiredUserId)
            .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status)
            .WhereIF(_appOptions.Value.IsZiGong && dto.QueryScreenType is EQueryOrderScreenType.Org, d => d.ScreenType == EOrderScreenType.Org)
            .WhereIF(_appOptions.Value.IsZiGong && dto.QueryScreenType is EQueryOrderScreenType.Seat, d => d.ScreenType == EOrderScreenType.Seat)
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order!.AcceptTypeCode! == dto.AcceptType!)
            .WhereIF(!string.IsNullOrEmpty(dto.HotspotSpliceName), d => d.Order!.Hotspot.HotSpotFullName!.StartsWith(dto.HotspotSpliceName!))
            .WhereIF(!string.IsNullOrEmpty(dto.SourceChannel), d => d.Order!.SourceChannelCode! == dto.SourceChannel!)
            .WhereIF(!string.IsNullOrEmpty(dto.VisitOrgName), d => d.VisitDetail.VisitOrgName!.Contains(dto.VisitOrgName!))
            .WhereIF(!string.IsNullOrEmpty(dto.CreatorOrgName), d => d.CreatorOrgName!.Contains(dto.CreatorOrgName!))
            .WhereIF(!string.IsNullOrEmpty(dto.CreatorName), d => d.CreatorName!.Contains(dto.CreatorName!))
            .WhereIF(dto.IsProvince.HasValue, d => d.Order!.IsProvince == dto.IsProvince)
            .WhereIF(dto.IsSendBackApplyNum is true, d => d.SendBackApplyNum > 0)
            .WhereIF(dto.IsSendBackApplyNum is false, d => d.SendBackApplyNum == 0)
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart)
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd)
            .WhereIF(dto.NewestAuditTimeStart.HasValue, d => d.NewestAuditTime >= dto.NewestAuditTimeStart)
            .WhereIF(dto.NewestAuditTimeEnd.HasValue, d => d.NewestAuditTime <= dto.NewestAuditTimeEnd)
            .WhereIF(!string.IsNullOrEmpty(dto.OrderId), d => d.OrderId == dto.OrderId)
            //甄别列表
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.Order!.OrgLevelOneName!.Contains(dto.OrgLevelOneName!))
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentHandleOrgName), d => d.Order!.CurrentHandleOrgName!.Contains(dto.CurrentHandleOrgName!))
            .WhereIF(dto.CreationTime.HasValue && dto.EndCreationTime.HasValue,
                d => d.Order!.CreationTime >= dto.CreationTime && d.Order!.CreationTime <= dto.EndCreationTime)
            .WhereIF(dto.CurrentHandleTime.HasValue && dto.EndCurrentHandleTime.HasValue,
                d => d.Order!.CurrentHandleTime >= dto.CurrentHandleTime && d.Order!.ActualHandleTime <= dto.EndCurrentHandleTime)
            .WhereIF(dto.FiledTime.HasValue && dto.EndFiledTime.HasValue,
                d => d.Order!.FiledTime >= dto.FiledTime && d.Order!.FiledTime <= dto.EndFiledTime)
            .WhereIF(dto.VisitTime.HasValue && dto.EndVisitTime.HasValue,
                d => d.Visit.VisitTime >= dto.VisitTime && d.Visit.VisitTime <= dto.EndVisitTime)
            .WhereIF(!string.IsNullOrEmpty(dto.Contact), d => d.Order!.Contact! == dto.Contact!)
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.Order!.FromPhone! == dto.FromPhone!)
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepName),
                d => !SqlFunc.IsNullOrEmpty(d.WorkflowId) && d.Workflow.ActualHandleStepName == dto.CurrentStepName) //当前节点
            .OrderByIF(dto is { SortRule: 0, SortField: "creationTime" }, d => d.CreationTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "creationTime" } || dto.SortRule is null, d => d.CreationTime, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.Order.IsUrgent, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.Order.StartTime, OrderByType.Desc);
    }

    public ISugarQueryable<OrderVisitDetail> MayScreenList(MayScreenListDto dto)
    {
        dto.ScreenType = dto.ScreenType is null ? 0 : dto.ScreenType;
        var query = _orderVisitedDetailRepository.Queryable(false, true)
            .Includes(x => x.OrderVisit)
            .Includes(x => x.OrderVisit, y => y.Order)
            .Includes(x => x.OrderVisit, y => y.Employee)
            //.LeftJoin<OrderScreen>((x, s) => x.Id == s.VisitDetailId && s.IsDeleted == false)
            .Includes(x => x.OrderScreens)
            .Where(x => x.OrderScreens.Any(s => s.Status == EScreenStatus.SendBack && s.ScreenType == dto.ScreenType && s.SendBackApply == true) ||
                        x.OrderScreens.Any() == false
            //|| x.OrderScreens.Any(s => (s.Status != EScreenStatus.SendBack && s.SendBackApply != true)) == false
            )
            .Where(x => x.OrderVisit.Order.ReceiveProvinceNo.StartsWith("ZGZFW") == false ||
                        string.IsNullOrEmpty(x.OrderVisit.Order.ReceiveProvinceNo))
            .WhereIF(dto.ScreenType == EOrderScreenType.Seat, x => x.OrderVisit.Order.IsProvince == false)
            .WhereIF(dto.ScreenSendBack is 1,
                x => x.OrderScreens.Any(s => s.Status == EScreenStatus.SendBack && s.ScreenType == dto.ScreenType && s.SendBackApply == true))
            .WhereIF(dto.ScreenSendBack is 2,
                x => x.OrderScreens.Any(s => (s.Status != EScreenStatus.SendBack && s.ScreenType == dto.ScreenType && s.SendBackApply != true)) ==
                     false)
            .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.OrderVisit.Order!.No!.Contains(dto.No!))
            .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo),
                x => x.OrderVisit.Order!.AcceptorName == dto.NameOrNo! || x.OrderVisit.Order!.AcceptorStaffNo == dto.NameOrNo!) //受理人/坐席
            .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.OrderVisit.Order!.Title!.Contains(dto.Title!))
            .WhereIF(dto.IsProvince.HasValue, x => x.OrderVisit.Order!.IsProvince == dto.IsProvince)
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.OrderVisit.Order!.AcceptTypeCode! == dto.AcceptType!)
            .WhereIF(!string.IsNullOrEmpty(dto.HotspotSpliceName),
                x => x.OrderVisit.Order!.Hotspot.HotSpotFullName!.StartsWith(dto.HotspotSpliceName!))
            .WhereIF(!string.IsNullOrEmpty(dto.SourceChannel), x => x.OrderVisit.Order!.SourceChannelCode! == dto.SourceChannel!)
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), x => x.OrderVisit.Order!.OrgLevelOneName!.Contains(dto.OrgLevelOneName!))
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentHandleOrgName),
                x => x.OrderVisit.Order!.CurrentHandleOrgName!.Contains(dto.CurrentHandleOrgName!))
            .WhereIF(!string.IsNullOrEmpty(dto.VisitOrgName), x => x.VisitOrgName!.Contains(dto.VisitOrgName!))
            .WhereIF(dto.CreationTime.HasValue && dto.EndCreationTime.HasValue,
                x => x.OrderVisit.Order!.CreationTime >= dto.CreationTime && x.OrderVisit.Order!.CreationTime <= dto.EndCreationTime)
            .WhereIF(dto.CurrentHandleTime.HasValue && dto.EndCurrentHandleTime.HasValue,
                x => x.OrderVisit.Order!.CurrentHandleTime >= dto.CurrentHandleTime &&
                     x.OrderVisit.Order!.ActualHandleTime <= dto.EndCurrentHandleTime)
            .WhereIF(dto.FiledTime.HasValue && dto.EndFiledTime.HasValue,
                x => x.OrderVisit.Order!.FiledTime >= dto.FiledTime && x.OrderVisit.Order!.FiledTime <= dto.EndFiledTime)
            .WhereIF(dto.VisitTime.HasValue && dto.EndVisitTime.HasValue,
                x => x.OrderVisit.VisitTime >= dto.VisitTime && x.OrderVisit.VisitTime <= dto.EndVisitTime)
            .WhereIF(dto.IsHomePage.HasValue && dto.IsHomePage == true,
                x => x.OrderVisit.VisitTime < dto.CreationTimeEnd && x.OrderVisit.VisitTime > dto.CreationTimeStart)
            //.WhereIF(dto.CounterSignType.HasValue, x => x.OrderVisit.Order!.CounterSignType == dto.CounterSignType)
            //.WhereIF(!string.IsNullOrEmpty(dto.OrgProcessingResults),
            //    x => SqlFunc.JsonField(x.OrgProcessingResults, "Key") == dto.OrgProcessingResults)
            //.WhereIF(!string.IsNullOrEmpty(dto.OrgHandledAttitude),
            //    x => SqlFunc.JsonListObjectAny(x.OrgHandledAttitude, "Key", dto.OrgHandledAttitude))
            //.WhereIF(!string.IsNullOrEmpty(dto.OrgNoSatisfiedReason),
            //    x => SqlFunc.JsonField(x.OrgNoSatisfiedReason, "Key") == dto.OrgNoSatisfiedReason)
            .Where(x => x.OrderVisit.VisitState == EVisitState.Visited && x.OrderVisit.IsCanHandle)
           ;
        if (_sessionContext.OrgId != null && !_sessionContext.OrgIsCenter)
        {
            query.WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.OrderVisit.Order.Title.Contains(dto.Keyword!) || x.OrderVisit.Order.No.Contains(dto.Keyword!))
                .Where(x => x.VisitTarget == EVisitTarget.Org && (
                    SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1" ||
                    SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2" ||
                    SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "1" ||
                    SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2"
                ))
                .WhereIF(dto.DataScope is 0, x => x.VisitOrgCode.StartsWith(_sessionContext.OrgId))
                .WhereIF(dto.DataScope is 1, x => x.VisitOrgCode == _sessionContext.OrgId)
                ;
        }
        else
        {
            query.WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.OrderVisit.Order.Title.Contains(dto.Keyword!) || x.OrderVisit.Order.No.Contains(dto.Keyword!))
                .WhereIF(dto.ScreenType == EOrderScreenType.Org, x => x.VisitTarget == EVisitTarget.Org && (
                    SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1" ||
                    SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2" ||
                    SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "1" ||
                    SqlFunc.JsonField(x.OrgHandledAttitude, "Key") == "2"
                ))
                .WhereIF(dto.ScreenType == EOrderScreenType.Seat, x => x.VisitTarget == EVisitTarget.Seat &&
                (x.SeatEvaluate == ESeatEvaluate.VeryNoSatisfied || x.SeatEvaluate == ESeatEvaluate.NoSatisfied
                || x.VoiceEvaluate == EVoiceEvaluate.NoSatisfied || x.VoiceEvaluate == EVoiceEvaluate.VeryNoSatisfied))
                ;
        }

        return query.OrderByIF(dto is { SortRule: 0, SortField: "order.startTime" }, x => x.OrderVisit.Order.StartTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "order.startTime" }, x => x.OrderVisit.Order.StartTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "order.actualHandleTime" }, x => x.OrderVisit.Order.ActualHandleTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "order.actualHandleTime" }, x => x.OrderVisit.Order.ActualHandleTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "order.filedTime" }, x => x.OrderVisit.Order.FiledTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "order.filedTime" }, x => x.OrderVisit.Order.FiledTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "orderVisit.visitTime" }, x => x.OrderVisit.VisitTime, OrderByType.Asc)
            .OrderByIF(dto is { SortRule: 1, SortField: "orderVisit.visitTime" }, x => x.OrderVisit.VisitTime, OrderByType.Desc)
            .OrderByIF(dto is { SortRule: 0, SortField: "screenByEndTime" }, x => x.ScreenByEndTime, OrderByType.Asc)//截止申请日期排序
            .OrderByIF(dto is { SortRule: 1, SortField: "screenByEndTime" }, x => x.ScreenByEndTime, OrderByType.Desc)
            //.OrderByIF(dto.SortRule is null, x => x.CreationTime, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), x => x.OrderVisit.Order.IsUrgent, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), x => x.OrderVisit.Order.CreationTime, OrderByType.Desc);
    }

    #endregion

    #region 特提

    /// <summary>
    /// 特提验证
    /// </summary>
    /// <param name="dto"></param>
    public async Task SpecialVerify(OrderSpecialAddDto dto, Order order, CancellationToken cancellationToken)
    {
        var screen = await _orderScreenRepository.Queryable().Where(x => x.OrderId == dto.OrderId && (int)x.Status < 2)
            .ToListAsync(cancellationToken);
        //var order = await _orderRepository.Queryable().Includes(d => d.Workflow).FirstAsync(d => d.Id == dto.OrderId);
        var sendBackAudit = await _orderSendBackAuditRepository.Queryable()
            .Where(x => x.OrderId == dto.OrderId && x.State == ESendBackAuditState.Apply).ToListAsync(cancellationToken);
        var orderDelay = await _orderDelayRepository.Queryable().Where(x => x.OrderId == dto.OrderId && x.DelayState == EDelayState.Examining)
            .ToListAsync(cancellationToken);
        var orderSecondaries = await _orderSecondaryHandlingRepository.Queryable()
            .Where(x => x.OrderId == dto.OrderId && x.State == ESecondaryHandlingState.Apply).ToListAsync(cancellationToken);

        if (_appOptions.Value.IsYiBin || _appOptions.Value.IsZiGong)
        {
            if (screen.Any())
            {
                await _orderScreenRepository.RemoveRangeAsync(screen, false, cancellationToken);
            }

            if (sendBackAudit.Any())
            {
                await _orderSendBackAuditRepository.RemoveRangeAsync(sendBackAudit, false, cancellationToken);
            }

            if (orderDelay.Any())
            {
                await _orderDelayRepository.RemoveRangeAsync(orderDelay, false, cancellationToken);
            }

            if (orderSecondaries.Any())
            {
                await _orderSecondaryHandlingRepository.RemoveRangeAsync(orderSecondaries, false, cancellationToken);
            }

            if (order.Workflow.IsInCountersign)
            {
                var workflowStep = await _workflowStepRepository.Queryable().Where(x => x.Id == order.Workflow.TopCountersignStepId)
                    .FirstAsync(cancellationToken);

                if (workflowStep != null)
                {
                    var dtoEnd = new EndCountersignDto() { CountersignId = workflowStep.StartCountersignId };
                    await EndCountersignAsync(dtoEnd, cancellationToken);
                }
            }
        }
        else
        {
            if (screen.Any()) throw UserFriendlyException.SameMessage("工单存在甄别中的信息！");

            if (sendBackAudit.Any())
                throw UserFriendlyException.SameMessage("该工单存在正在审核中的退回，不能办理");

            if (order.Workflow.IsInCountersign) throw UserFriendlyException.SameMessage("工单会签中，无法进行特提！");
        }
    }

    /// <summary>
    /// 省要求重办、省要求撤单 删除甄别等数据
    /// </summary>
    /// <param name="order"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task SpecialNewVerify(Order order, CancellationToken cancellationToken)
    {
        var screen = await _orderScreenRepository.Queryable().Where(x => x.OrderId == order.Id && (int)x.Status < 2)
        .ToListAsync(cancellationToken);
        var sendBackAudit = await _orderSendBackAuditRepository.Queryable()
            .Where(x => x.OrderId == order.Id && x.State == ESendBackAuditState.Apply).ToListAsync(cancellationToken);
        var orderDelay = await _orderDelayRepository.Queryable().Where(x => x.OrderId == order.Id && x.DelayState == EDelayState.Examining)
            .ToListAsync(cancellationToken);
        var orderSecondaries = await _orderSecondaryHandlingRepository.Queryable()
            .Where(x => x.OrderId == order.Id && x.State == ESecondaryHandlingState.Apply).ToListAsync(cancellationToken);

        if (screen != null && screen.Any())
        {
            await _orderScreenRepository.RemoveRangeAsync(screen, false, cancellationToken);
        }

        if (sendBackAudit != null && sendBackAudit.Any())
        {
            await _orderSendBackAuditRepository.RemoveRangeAsync(sendBackAudit, false, cancellationToken);
        }

        if (orderDelay != null && orderDelay.Any())
        {
            await _orderDelayRepository.RemoveRangeAsync(orderDelay, false, cancellationToken);
        }

        if (orderSecondaries != null && orderSecondaries.Any())
        {
            await _orderSecondaryHandlingRepository.RemoveRangeAsync(orderSecondaries, false, cancellationToken);
        }

        if (order.Workflow != null && order.Workflow.IsInCountersign)
        {
            var workflowStep = await _workflowStepRepository.Queryable().Where(x => x.Id == order.Workflow.TopCountersignStepId)
                .FirstAsync(cancellationToken);
            if (workflowStep != null)
            {
                var dtoEnd = new EndCountersignDto() { CountersignId = workflowStep.StartCountersignId };
                await EndCountersignAsync(dtoEnd, cancellationToken);
            }
        }
    }

    public async Task EndCountersignAsync(EndCountersignDto dto, CancellationToken cancellationToken)
    {
        var countersign = await _workflowCountersignRepository.GetAsync(dto.CountersignId, cancellationToken);
        if (countersign is null)
            throw new UserFriendlyException("无效会签编号");

        var order = await _orderRepository.GetAsync(d => d.WorkflowId == countersign.WorkflowId, cancellationToken);
        if (order is null)
            throw new UserFriendlyException($"工单未开启流程, workflowId: {countersign.WorkflowId}");

        var workflow = await _workflowDomainService.TerminalCountersignAsync(countersign, order.ExpiredTime.Value, cancellationToken);

        order.UpdateHandlingStatus(workflow.IsInCountersign);
        _mapper.Map(workflow, order);
        await _orderRepository.UpdateAsync(order, cancellationToken);
    }

    #endregion

    /// <summary>
    /// 回访列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVisit> QueryOrderVisitList(QueryOrderVisitDto dto)
    {
        var query = _orderVisitRepository.Queryable()
            .Includes(d => d.Order, d => d.OrderTags)
            .Includes(d => d.Employee)
            .Includes(d => d.OrderVisitDetails);

        if (_appOptions.Value.IsZiGong || _appOptions.Value.IsLuZhou)
        {
            //任务217  待回访工单显示优化（自贡+泸州通用）回访状态选择“待回访”，在该状态下不查“设为未接通”工单
            query = query.WhereIF(dto.VisitStateQuery == EVisitStateQuery.NoVisit,
                d => (d.VisitState == EVisitState.WaitForVisit || d.VisitState == EVisitState.NoSatisfiedWaitForVisit) &&
                     (d.IsPutThrough == true || d.IsPutThrough == null));
        }
        else
            query = query.WhereIF(dto.VisitStateQuery == EVisitStateQuery.NoVisit,
                d => d.VisitState == EVisitState.WaitForVisit || d.VisitState == EVisitState.NoSatisfiedWaitForVisit);

        query = query.WhereIF(dto.VisitStateQuery == EVisitStateQuery.Visited, d => d.VisitState == EVisitState.Visited)
            .WhereIF(dto.VisitStateQuery == EVisitStateQuery.SMSUnsatisfied, d => d.VisitState == EVisitState.SMSUnsatisfied)
            .WhereIF(dto.VisitStateQuery == EVisitStateQuery.SMSVisiting, d => d.VisitState == EVisitState.SMSVisiting)
            .WhereIF(dto.VisitStateQuery == EVisitStateQuery.AiVisitWaitForVisit, d => d.VisitState == EVisitState.AiVisitWaitForVisit)
            .WhereIF(dto.VisitStateQuery == EVisitStateQuery.NoPutThrough,
                d => d.IsPutThrough == false && d.VisitState != EVisitState.Visited && d.VisitState != EVisitState.None)
            .WhereIF(_appOptions.Value.IsZiGong && dto.VisitStateQuery == EVisitStateQuery.NoPutThrough,
                d => d.VisitState != EVisitState.SMSVisiting)//自贡未接通的短信回访了不在未接通中查询
            .WhereIF(dto.VisitStateQuery == EVisitStateQuery.ChipVoiceVisiting, d => d.VisitState == EVisitState.AiVisiting) //任务 162：回访状态快捷查询条件
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Order.Title.Contains(dto.Keyword!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No == dto.No)
            .WhereIF(dto.VisitType != null, d => d.VisitType == dto.VisitType)
            //.WhereIF(dto.FiledType != null && dto.FiledType == FiledType.CenterFiled, d => d.Order.ProcessType == EProcessType.Zhiban)
            //.WhereIF(dto.FiledType != null && dto.FiledType == FiledType.OrgFiled, d => d.Order.ProcessType == EProcessType.Jiaoban)
            .WhereIF(dto.FiledType != null && dto.FiledType == FiledType.CenterFiled, d => d.Order.FileOrgIsCenter == true)
            .WhereIF(dto.FiledType != null && dto.FiledType == FiledType.OrgFiled, d => d.Order.FileOrgIsCenter == false)
            .WhereIF(dto.IsCountersign != null && dto.IsCountersign == true, d => d.Order.CounterSignType != null)
            .WhereIF(dto.IsCountersign != null && dto.IsCountersign == false, d => d.Order.CounterSignType == null)
            .WhereIF(dto.QuerySelf.HasValue && dto.QuerySelf.Value, d => d.EmployeeId == _sessionContext.RequiredUserId)
            .WhereIF(!string.IsNullOrEmpty(dto.EmployeeName), d => !string.IsNullOrEmpty(d.EmployeeId) && d.Employee.Name.Contains(dto.EmployeeName))
            .WhereIF(dto.IsProvince != null && dto.IsProvince == true, d => d.Order.IsProvince == true)
            .WhereIF(dto.IsProvince != null && dto.IsProvince == false, d => d.Order.IsProvince == false)
            .WhereIF(dto.IsEffectiveAiVisit != null, d => d.IsEffectiveAiVisit == dto.IsEffectiveAiVisit)
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.Order.FromPhone.Contains(dto.FromPhone!))
            .WhereIF(!string.IsNullOrEmpty(dto.Contact), d => d.Order.Contact == dto.Contact)
            .WhereIF(dto.VoiceEvaluate.Any(), d => d.OrderVisitDetails.Any(m => dto.VoiceEvaluate.Contains(m.VoiceEvaluate.Value)))
            .WhereIF(dto.SeatEvaluate.Any(), d => d.OrderVisitDetails.Any(m => dto.SeatEvaluate.Contains(m.SeatEvaluate.Value)))
            .WhereIF(dto.OrgProcessingResults.Any(),
                d => d.OrderVisitDetails.Any(m => dto.OrgProcessingResults.Contains(SqlFunc.JsonField(m.OrgProcessingResults, "Key"))))
            .WhereIF(dto.OrgHandledAttitude.Any(),
                d => d.OrderVisitDetails.Any(q => dto.OrgHandledAttitude.Contains(SqlFunc.JsonField(q.OrgHandledAttitude, "Key"))))
            .WhereIF(dto.IsOverTime == true,
                d => (d.Order.ExpiredTime < DateTime.Now && d.Order.Status < EOrderStatus.Filed) ||
                     (d.Order.ExpiredTime < d.Order.ActualHandleTime && d.Order.Status >= EOrderStatus.Filed)) //是 超期
            .WhereIF(dto.IsOverTime == false,
                d => (d.Order.ExpiredTime > DateTime.Now && d.Order.Status < EOrderStatus.Filed) ||
                     (d.Order.ExpiredTime > d.Order.ActualHandleTime && d.Order.Status >= EOrderStatus.Filed)) //否 超期
            .WhereIF(dto.StartTime.HasValue, d => d.VisitTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, d => d.VisitTime <= dto.EndTime)
            .WhereIF(dto.StartPublishTime.HasValue && dto.EndPublishTime.HasValue,
                d => d.PublishTime >= dto.StartPublishTime && d.PublishTime <= dto.EndPublishTime) // 发布时间
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.Order.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门
            .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.Order.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
            .WhereIF(dto.IdentityType != null, d => d.Order.IdentityType == dto.IdentityType) //来电主体
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart)
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd)
            .WhereIF(dto.AiVisitResult.HasValue && dto.AiVisitResult == EAiVisitResult.OrgProcessingResultsNoSatisfied,
                d => d.VisitState == EVisitState.WaitForVisit && d.VisitType == EVisitType.ChipVoiceVisit &&
                     d.OrderVisitDetails.Any(m => SqlFunc.JsonField(m.OrgProcessingResults, "Key") == "2"))
            //.WhereIF(dto.IsAiVisit.HasValue && dto.IsAiVisit == false, x => x.AiVisitCount > 0)   //是否建立智能回访任务 取反（建立过）
            .WhereIF(dto.IsAiVisit.HasValue && dto.IsAiVisit == true, d => d.AiVisitCount <= 0) //（未建立过）
            .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.Order.SourceChannelCode == dto.Channel)
            .WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode),
                d => SqlFunc.Subqueryable<OrderRelationTag>().InnerJoin<SystemDicData>((s, p) => s.TagId == p.Id)
                    .Where((s, p) => p.DicDataValue == dto.OrderTagCode && d.OrderId == s.OrderId).Any()) //工单标签
            .WhereIF(dto.IsUpdate.HasValue && dto.IsUpdate == true, d => d.IsUpdate == true)
            .WhereIF(dto.IsUpdate.HasValue && dto.IsUpdate == false, d => d.IsUpdate == false || d.IsUpdate == null)
            .WhereIF(dto.IsEmployeeNameNull.HasValue && dto.IsEmployeeNameNull == true, d => d.EmployeeId != null && d.EmployeeId != "")
            .WhereIF(dto.IsEmployeeNameNull.HasValue && dto.IsEmployeeNameNull == false, d => d.EmployeeId == null || d.EmployeeId == "")

            .OrderByIF(_appOptions.Value.IsYiBin && dto.VisitStateQuery != EVisitStateQuery.Visited, d => d.Order.IsUrgent, OrderByType.Desc)
            .OrderByIF(_appOptions.Value.IsZiGong == false, d => d.PublishTime, OrderByType.Desc)
            .OrderByIF(dto is { SortField: "publishTime", SortRule: 0 }, d => d.PublishTime, OrderByType.Asc) // 发布时间升序 
            .OrderByIF(dto is { SortField: "publishTime", SortRule: 1 }, d => d.PublishTime, OrderByType.Desc)// 发布时间升序
            .OrderByIF(dto is { SortField: "order.creationTime", SortRule: 0 }, d => d.Order.CreationTime, OrderByType.Asc) // 受理时间升序
            .OrderByIF(dto is { SortField: "order.creationTime", SortRule: 1 }, d => d.Order.CreationTime, OrderByType.Desc) // 受理时间升序
            .OrderByIF(dto is { SortField: "order.filedTime", SortRule: 0 }, d => d.Order.FiledTime, OrderByType.Asc) // 办结时间升序
            .OrderByIF(dto is { SortField: "order.filedTime", SortRule: 1 }, d => d.Order.FiledTime, OrderByType.Desc) // 办结时间升序
            .OrderByIF(dto is { SortField: "visitTime", SortRule: 0 }, d => d.VisitTime, OrderByType.Asc) // 回访时间升序
            .OrderByIF(dto is { SortField: "visitTime", SortRule: 1 }, d => d.VisitTime, OrderByType.Desc) // 回访时间升序
            .OrderByIF(_appOptions.Value.IsZiGong && string.IsNullOrEmpty(dto.SortField), d => d.PublishTime, OrderByType.Desc)
            ;
        return query;
    }

    /// <summary>
    /// 回访量明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVisit> QueryOrderVisitQuantityListAsync(QueryOrderVisitListDto dto)
    {
        var query = _orderVisitRepository.Queryable()
             .Includes(d => d.Order, d => d.OrderTags)
             .Includes(d => d.Employee)
             .Includes(d => d.OrderVisitDetails)
             .Includes(d => d.Order, d => d.OrderVisits.Where(x => Convert.ToInt32(x.VisitState) == 30).ToList())
             .Where(d => d.VisitTime >= dto.StartTime && d.VisitTime <= dto.EndTime && d.VisitType != null && d.EmployeeId != "" && d.EmployeeId != null)
             .WhereIF(!string.IsNullOrEmpty(dto.UserID), d => !string.IsNullOrEmpty(d.EmployeeId) && d.EmployeeId == dto.UserID)
             .WhereIF(!string.IsNullOrEmpty(dto.UserName), d => d.Employee.Name == dto.UserName)
             .WhereIF(dto.FieldName == "callVisitCount", d => d.VisitType == EVisitType.CallVisit)
             .WhereIF(dto.FieldName == "defaultVisitCount", d => d.VisitType == EVisitType.ArtificialVisit)
             .WhereIF(dto.FieldName == "smsVisitCount", d => d.VisitType == EVisitType.SmsVisit)
             .WhereIF(dto.FieldName == "totalVisitCount", d => d.VisitType == EVisitType.CallVisit || d.VisitType == EVisitType.ArtificialVisit || d.VisitType == EVisitType.SmsVisit);

        query = query
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No == dto.No)                                                                 // 工单编号
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title!))                                          // 标题
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.Order.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) // 接办部门
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order.AcceptTypeCode == dto.AcceptType)                               // 受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptorName), d => d.Order.AcceptorName == dto.AcceptorName!)                            // 受理人
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName), d => d.Order.ActualHandlerName == dto.ActualHandlerName)              // 接办人
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.Order.FromPhone.Contains(dto.FromPhone!))                              // 来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.Contact), d => d.Order.Contact == dto.Contact)                                            // 联系电话
            .WhereIF(!string.IsNullOrEmpty(dto.FromName), d => d.Order.FromName == dto.FromName)                                         // 来电人姓名
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart)                                 // 受理时间开始
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd)                                     // 受理时间结束
            .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.Order.ExpiredTime >= dto.ExpiredTimeStart)                                    // 期满时间开始
            .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.Order.ExpiredTime <= dto.ExpiredTimeEnd)                                        // 期满时间结束
            .WhereIF(dto.Status.HasValue, d => d.Order.Status == dto.Status)                                                             // 工单状态
            .WhereIF(!string.IsNullOrEmpty(dto.AreaCode), d => d.Order.AreaCode == dto.AreaCode)                                         // 区域
            .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.Order.SourceChannelCode == dto.Channel)                                  // 来源渠道
            .WhereIF(dto.IsScreen.HasValue && dto.IsScreen.Value, d => SqlFunc.Subqueryable<OrderScreen>().Where(q => q.OrderId == d.OrderId && q.VisitDetailId == d.Id).Any())             // 是否甄别
            .WhereIF(dto.IsScreen.HasValue && dto.IsScreen.Value == false, d => SqlFunc.Subqueryable<OrderScreen>().Where(q => q.OrderId == d.OrderId && q.VisitDetailId == d.Id).NotAny())
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepName), d => d.Order.CurrentStepName == dto.CurrentStepName)                    // 当前办理节点
            .WhereIF(dto.FiledTimeStart.HasValue, d => d.Order.FiledTime >= dto.FiledTimeStart)                                          // 办结时间开始
            .WhereIF(dto.FiledTimeEnd.HasValue, d => d.Order.FiledTime <= dto.FiledTimeEnd)                                              // 办结时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot)) // 热点类型
            .WhereIF(dto.IsSecret.HasValue, d => d.Order.IsSecret == dto.IsSecret)                                                       // 是否紧急

            .OrderByIF(_appOptions.Value.IsZiGong == false, d => d.PublishTime, OrderByType.Desc)
            .OrderByIF(dto is { SortField: "publishTime", SortRule: 0 }, x => x.PublishTime, OrderByType.Asc) // 发布时间升序
            .OrderByIF(dto is { SortField: "publishTime", SortRule: 1 }, x => x.PublishTime, OrderByType.Desc)// 发布时间升序
            .OrderByIF(dto is { SortField: "order.creationTime", SortRule: 0 }, x => x.Order.CreationTime, OrderByType.Asc) // 受理时间升序
            .OrderByIF(dto is { SortField: "order.creationTime", SortRule: 1 }, x => x.Order.CreationTime, OrderByType.Desc) // 受理时间升序
            .OrderByIF(dto is { SortField: "order.filedTime", SortRule: 0 }, x => x.Order.FiledTime, OrderByType.Asc) // 办结时间升序
            .OrderByIF(dto is { SortField: "order.filedTime", SortRule: 1 }, x => x.Order.FiledTime, OrderByType.Desc) // 办结时间升序
            .OrderByIF(dto is { SortField: "visitTime", SortRule: 0 }, x => x.VisitTime, OrderByType.Asc) // 回访时间升序
            .OrderByIF(dto is { SortField: "visitTime", SortRule: 1 }, x => x.VisitTime, OrderByType.Desc) // 回访时间升序
            .OrderByIF(_appOptions.Value.IsZiGong && string.IsNullOrEmpty(dto.SortField), d => d.PublishTime, OrderByType.Desc)
            ;
        return query;
    }

    /// <summary>
    /// 回访量明细自贡
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVisitRecord> QueryOrderVisitQuantityListByZgAsync(QueryOrderVisitListDto dto)
    {
        var query = _orderVisitRecordRepository.Queryable()
            .Includes(d => d.Order, d => d.OrderTags)
            .Includes(d => d.Employee)
            .Includes(d => d.Order, d => d.OrderVisits.Where(x => Convert.ToInt32(x.VisitState) == 30).ToList())
            .WhereIF(!string.IsNullOrEmpty(dto.UserID), d => !string.IsNullOrEmpty(d.EmployeeId) && d.EmployeeId == dto.UserID)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), d => d.Employee.Name == dto.UserName)
            .WhereIF(dto.StartTime != null, d => d.VisitTime >= dto.StartTime && d.VisitType != null && d.EmployeeId != "" && d.EmployeeId != null)
            .WhereIF(dto.EndTime != null, d => d.VisitTime <= dto.EndTime && d.VisitType != null && d.EmployeeId != "" && d.EmployeeId != null)
            .WhereIF(dto.FieldName == "callVisitCount", d => d.VisitType == EVisitType.CallVisit)
            .WhereIF(dto.FieldName == "defaultVisitCount", d => d.VisitType == EVisitType.ArtificialVisit)
            .WhereIF(dto.FieldName == "smsVisitCount", d => d.VisitType == EVisitType.SmsVisit)
            .WhereIF(dto.FieldName == "totalVisitCount", d => d.VisitType == EVisitType.CallVisit || d.VisitType == EVisitType.ArtificialVisit || d.VisitType == EVisitType.SmsVisit);

        query = query
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No == dto.No)                                                                 // 工单编号
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title!))                                          // 标题
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.Order.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) // 接办部门
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order.AcceptTypeCode == dto.AcceptType)                               // 受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptorName), d => d.Order.AcceptorName == dto.AcceptorName!)                            // 受理人
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName), d => d.Order.ActualHandlerName == dto.ActualHandlerName)              // 接办人
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.Order.FromPhone.Contains(dto.FromPhone!))                              // 来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.Contact), d => d.Order.Contact == dto.Contact)                                            // 联系电话
            .WhereIF(!string.IsNullOrEmpty(dto.FromName), d => d.Order.FromName == dto.FromName)                                         // 来电人姓名
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart)                                 // 受理时间开始
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd)                                     // 受理时间结束
            .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.Order.ExpiredTime >= dto.ExpiredTimeStart)                                    // 期满时间开始
            .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.Order.ExpiredTime <= dto.ExpiredTimeEnd)                                        // 期满时间结束
            .WhereIF(dto.Status.HasValue, d => d.Order.Status == dto.Status)                                                             // 工单状态
            .WhereIF(!string.IsNullOrEmpty(dto.AreaCode), d => d.Order.AreaCode == dto.AreaCode)                                         // 区域
            .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.Order.SourceChannelCode == dto.Channel)                                  // 来源渠道
            .WhereIF(dto.IsScreen.HasValue && dto.IsScreen.Value, d => SqlFunc.Subqueryable<OrderScreen>().Where(q => q.OrderId == d.OrderId && q.VisitDetailId == d.Id).Any())             // 是否甄别
            .WhereIF(dto.IsScreen.HasValue && dto.IsScreen.Value == false, d => SqlFunc.Subqueryable<OrderScreen>().Where(q => q.OrderId == d.OrderId && q.VisitDetailId == d.Id).NotAny())
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepName), d => d.Order.CurrentStepName == dto.CurrentStepName)                    // 当前办理节点
            .WhereIF(dto.FiledTimeStart.HasValue, d => d.Order.FiledTime >= dto.FiledTimeStart)                                          // 办结时间开始
            .WhereIF(dto.FiledTimeEnd.HasValue, d => d.Order.FiledTime <= dto.FiledTimeEnd)                                              // 办结时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot)) // 热点类型
            .WhereIF(dto.IsSecret.HasValue, d => d.Order.IsSecret == dto.IsSecret)                                                       // 是否紧急

            .OrderByIF(dto is { SortField: "order.creationTime", SortRule: 0 }, x => x.Order.CreationTime, OrderByType.Asc) // 受理时间升序
            .OrderByIF(dto is { SortField: "order.creationTime", SortRule: 1 }, x => x.Order.CreationTime, OrderByType.Desc) // 受理时间升序
            .OrderByIF(dto is { SortField: "order.filedTime", SortRule: 0 }, x => x.Order.FiledTime, OrderByType.Asc) // 办结时间升序
            .OrderByIF(dto is { SortField: "order.filedTime", SortRule: 1 }, x => x.Order.FiledTime, OrderByType.Desc) // 办结时间升序
            .OrderByIF(dto is { SortField: "visitTime", SortRule: 0 }, x => x.VisitTime, OrderByType.Asc) // 回访时间升序
            .OrderByIF(dto is { SortField: "visitTime", SortRule: 1 }, x => x.VisitTime, OrderByType.Desc) // 回访时间升序
            ;
        return query;
    }

    /// <summary>
    /// 热点类型小类统计明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<Order> HotspotStatisticsDetail(HotspotStatisticsRep dto)
    {
        var IsCenter = _sessionContext.OrgIsCenter;
        var query = _orderRepository.Queryable()
            .Includes(d => d.OrderVisits)
            .Where(d => d.CreationTime >= dto.StartTime && d.CreationTime <= dto.EndTime)
            .Where(d => d.HotspotId.StartsWith(dto.HotspotCode))
            .WhereIF(dto.TypeId == 1, d => d.IdentityType == EIdentityType.Citizen)
            .WhereIF(dto.TypeId == 2, d => d.IdentityType == EIdentityType.Enterprise)
            .WhereIF(IsCenter == false, d => d.ActualHandleOrgCode.StartsWith(_sessionContext.RequiredOrgId));
        return query;
    }

    /// <summary>
    /// 坐席总体满意度分析
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<SeatSatisfactionStatisticsDto> SeatSatisfactionStatistics(PagedKeywordRequest dto)
    {
        var list = _orderVisitDetailRepository.Queryable()
            .Includes(x => x.OrderVisit, d => d.Order)
            .Where(x => x.OrderVisit.Order.SourceChannelCode == "RGDH")
            .Where(x => x.OrderVisit.VisitTime >= dto.StartTime.Value && x.OrderVisit.VisitTime <= dto.EndTime.Value &&
                        x.OrderVisit.VisitState == EVisitState.Visited
                        && x.SeatEvaluate != null && x.SeatEvaluate != ESeatEvaluate.VeryNoSatisfied && x.SeatEvaluate != ESeatEvaluate.Normal &&
                        x.VisitTarget == EVisitTarget.Seat
            )
            .GroupBy(x => x.SeatEvaluate)
            .Select(x => new SeatSatisfactionStatisticsDto
            {
                SeatEvaluate = x.SeatEvaluate,
                Count = SqlFunc.AggregateCount(x.Id)
            });
        return list;

        //var list = _orderVisitRepository.Queryable()
        //       .Includes(d => d.Order)
        //       .Where(x => x.VisitTime >= dto.StartTime.Value && x.VisitTime <= dto.EndTime.Value && x.VisitState == EVisitState.Visited && x.Order.SeatEvaluate != null
        //       && x.Order.SeatEvaluate != ESeatEvaluate.VeryNoSatisfied && x.Order.SeatEvaluate != ESeatEvaluate.Normal)
        //       .GroupBy(x => x.Order.SeatEvaluate)
        //       .Select(x => new SeatSatisfactionStatisticsDto
        //       {
        //           SeatEvaluate = x.Order.SeatEvaluate,
        //           Count = SqlFunc.AggregateCount(x.Id)
        //       });
        //return list;
    }

    /// <summary>
    /// 坐席满意度明细表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<SeatSatisfactionStatisticsListDetailDto> SeatSatisfactionStatisticsListDetail(PagedKeywordRequest dto)
    {
        var query = _orderVisitDetailRepository.Queryable()
            .LeftJoin<OrderVisit>((od, ov) => od.VisitId == ov.Id)
            .LeftJoin<Order>((od, ov, o) => ov.OrderId == o.Id)
            .Where((od, ov, o) => ov.VisitTime >= dto.StartTime.Value && ov.VisitTime <= dto.EndTime.Value && ov.VisitState == EVisitState.Visited
                                  && od.SeatEvaluate != null && od.SeatEvaluate != ESeatEvaluate.VeryNoSatisfied
                                  && od.SeatEvaluate != ESeatEvaluate.Normal && od.VisitTarget == EVisitTarget.Seat && o.SourceChannelCode == "RGDH")
            .GroupBy((od, ov, o) => new
            {
                o.AcceptorName,
                o.AcceptorId
            })
            .Select((od, ov, o) => new SeatSatisfactionStatisticsListDetailDto
            {
                UserName = o.AcceptorName,
                UserId = o.AcceptorId,
                DefaultSatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.DefaultSatisfied, 1, 0)),
                VeryNoSatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.VeryNoSatisfied, 1, 0)),
                NoSatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.NoSatisfied, 1, 0)),
                Normal = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.Normal, 1, 0)),
                Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.Satisfied, 1, 0)),
                VerySatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.VerySatisfied, 1, 0)),
                NoConnect = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.NoConnect, 1, 0)),
                NoEvaluate = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.NoEvaluate, 1, 0))
            });
        return query;
    }

    /// <summary>
    /// 坐席满意度工单明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVisitDetail> QuerySeatSatisfactionOrderVisitList(SeatSatisfactionOrderVisitRequest dto)
    {
        var query = _orderVisitDetailRepository.Queryable()
            .Includes(x => x.OrderVisit, d => d.Order)
            .Includes(x => x.OrderVisit, d => d.Employee)
            .Where(x => x.OrderVisit.VisitTime >= dto.StartTime.Value && x.OrderVisit.VisitTime <= dto.EndTime.Value
                                                                      && x.OrderVisit.VisitState == EVisitState.Visited && x.SeatEvaluate != null
                                                                      && x.SeatEvaluate != ESeatEvaluate.VeryNoSatisfied &&
                                                                      x.SeatEvaluate != ESeatEvaluate.Normal && x.VisitTarget == EVisitTarget.Seat &&
                                                                      x.OrderVisit.Order.SourceChannelCode == "RGDH")
            .WhereIF(!string.IsNullOrEmpty(dto.UserId), x => x.OrderVisit.Order.AcceptorId == dto.UserId)
            .WhereIF(dto.SeatEvaluate.HasValue, x => x.SeatEvaluate == dto.SeatEvaluate)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), x => x.OrderVisit.Order.AcceptorName == dto.UserName)
            .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.OrderVisit.Order.Title.Contains(dto.Title))
            .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.OrderVisit.Order.No.Contains(dto.No))
            .OrderByDescending(x => x.OrderVisit.VisitTime);
        return query;
    }

    /// <summary>
    /// 将工单从网格员节点办理至工单标记节点(按照老系统实现方案：办理人统一处理为坐席)
    /// </summary>
    /// <returns></returns>
    public async Task HandleFromWanggeyuanToMaskAsync(string orderId, string opinion, CancellationToken cancellationToken)
    {
        var order = await _orderRepository.GetAsync(orderId, cancellationToken);
        if (order is null)
            throw new UserFriendlyException("无效工单编号");

        var workflow = await _workflowDomainService.GetWorkflowAsync(order.WorkflowId, withDefine: true,
            withSteps: true, cancellationToken: cancellationToken);
        var currentStep = workflow.Steps.FirstOrDefault(d => string.CompareOrdinal(d.Tag, TagDefaults.Wanggeyuan) == 0);
        if (currentStep is null)
            throw new UserFriendlyException($"未查询到网格员节点, workflowId: {workflow.Id}");
        if (currentStep.Status == EWorkflowStepStatus.Handled)
            throw new UserFriendlyException($"网格员节点已办理完, workflowId: {workflow.Id}");
        var markStepDefine = workflow.WorkflowDefinition.FindStepDefineByTag(d =>
            string.Compare(d.Tag, TagDefaults.OrderMark, StringComparison.OrdinalIgnoreCase) == 0);
        if (markStepDefine is null)
            throw new UserFriendlyException("未配置工单标记节点或未正确配置tag");

        var nextDto = new NextWorkflowDto
        {
            WorkflowId = workflow.Id,
            StepId = currentStep.Id,
            NextStepCode = markStepDefine.Code,
            NextStepName = markStepDefine.Name,
            FlowDirection = EFlowDirection.CenterToOrg,
            HandlerType = markStepDefine.HandlerType,
            StepType = markStepDefine.StepType,
            IsSms = false,
            NextHandlers = new(),
            IsStartCountersign = false,
            BusinessType = markStepDefine.BusinessType,
            Opinion = opinion
        };

        var startStep = workflow.Steps.FirstOrDefault(d => d.StepType == EStepType.Start);
        if (startStep is null)
            throw new UserFriendlyException($"未查询到开始节点, workflowId: {workflow.Id}");
        var operater = new FakeSessionContext
        {
            UserId = startStep.HandlerId,
            UserName = startStep.HandlerName,
            OrgId = startStep.HandlerOrgId,
            OrgName = startStep.HandlerOrgName,
        };
        await _sessionContextManager.ChangeSessionContextByUserIdAsync(startStep.HandlerId, cancellationToken);
        var isAutoFillSummaryOpinion = _systemSettingCacheManager.IsAutoFillSummaryOpinion;

        await _workflowDomainService.NextAsync(nextDto,
            expiredTime: order.ExpiredTime,
            isAutoFillSummaryOpinion: isAutoFillSummaryOpinion,
            cancellationToken: cancellationToken);
    }

    /// <summary>
    /// 查询退回操作目标节点的指派对象
    /// </summary>
    public async Task<StepAssignInfo?> GetOrderPreviousAssignInfoAsync(Workflow workflow, StepDefine prevStepDefine, WorkflowStep prevStep,
        CancellationToken cancellationToken)
    {
        //自贡需求：
        // 1. 工单退回、特提、重办到话务部节点时，所有坐席都可以查看和办理
        // 2. 退回到派单组时需执行平均分配逻辑
        //宜宾需求：
        // 1、退回至话务部：所有坐席都可以查看和办理（除某些场景下本来就需指定办理对象，如：发布时退回……）
        // 2、退回至派单组：默认退给之前的派单员（除某些场景下本来就需指定办理对象，如：发布时退回……）
        // 3、话务员特提至话务部：根据特提申请时候选择来，指定的办理对象才能查看和办理
        // 4、派单员特提至派单组：根据特提申请时候选择来，指定的办理对象才能查看和办理
        // 5、班长特提至派单组，办理对象必选（已实现）
        // 6、班长特提至话务部，办理对象非必选，没选择则所有坐席都可以查看和办理
        //泸州需求：
        /* 1、特提(仅针对特提到热线中心节点）
           1.1、工单特提到话务部、派单组或者班长审批等其它热线中心节点，只有之前办理人才能办理
           2、退回功能(仅针对退回到热线中心节点）
           2.1、退回到热线中心各节点，只有之前办理人才能办理；
         */

        if (workflow.FlowType is not EFlowType.Handle) return null;

        StepAssignInfo? rsp = null;
        switch (_appOptions.Value.AppScope)
        {
            case AppDefaults.AppScope.YiBin:
                switch (prevStepDefine.BusinessType)
                {
                    case EBusinessType.Seat:
                        var define = prevStepDefine.HandlerTypeItems.First();
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Role,
                            RoleId = define.Key,
                            RoleName = define.Value,
                            OrgId = prevStep.HandlerOrgId,
                            OrgName = prevStep.HandlerOrgName,
                            Key = define.Key,
                            Value = define.Value,
                        };
                        break;
                    case EBusinessType.Send:
                        break;
                    case EBusinessType.Department:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Org,
                            OrgId = prevStep.HandlerOrgId,
                            OrgName = prevStep.HandlerOrgName,
                            Key = prevStep.HandlerOrgId,
                            Value = prevStep.HandlerOrgName,
                        };
                        break;
                    case EBusinessType.DepartmentLeader:
                        break;
                    case EBusinessType.CenterMonitor:
                        break;
                    case EBusinessType.CenterLeader:
                        break;
                    case EBusinessType.File:
                    case EBusinessType.Unknown:
                    case EBusinessType.Publish:
                    case EBusinessType.Visit:
                    case EBusinessType.TrashEnd:
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                break;
            case AppDefaults.AppScope.ZiGong:
                switch (prevStepDefine.BusinessType)
                {
                    case EBusinessType.Seat:
                        var define = prevStepDefine.HandlerTypeItems.First();
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Role,
                            RoleId = define.Key,
                            RoleName = define.Value,
                            OrgId = prevStep.HandlerOrgId,
                            OrgName = prevStep.HandlerOrgName,
                            Key = define.Key,
                            Value = define.Value,
                        };
                        break;
                    case EBusinessType.Send:
                        // 平均派单
                        var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
                        if (averageSendOrder)
                        {
                            var sendOrderTrace = workflow.Traces
                            .Where(x => x.BusinessType == EBusinessType.Send && x.HandlerId != AppDefaults.SendPoolId)
                            .MaxBy(x => x.CreationTime);
                            var prevSendOrder = sendOrderTrace is not null;
                            if (prevSendOrder)
                            {
                                prevSendOrder = await _orderDomainService.SchedulingAtWork(sendOrderTrace.HandlerId);
                            }
                            if (prevSendOrder)
                            {
                                rsp = new StepAssignInfo()
                                {
                                    Key = sendOrderTrace.HandlerId,
                                    Value = sendOrderTrace.HandlerName,
                                    UserId = sendOrderTrace.HandlerId,
                                    Username = sendOrderTrace.HandlerName,
                                    OrgId = sendOrderTrace.HandlerOrgId,
                                    OrgName = sendOrderTrace.HandlerOrgName,
                                    FlowAssignType = EFlowAssignType.User

                                };
                            }
                            else
                            {
                                rsp = await _orderDomainService.AverageOrder(cancellationToken);
                            }
                        }
                        break;
                    case EBusinessType.Department:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Org,
                            OrgId = prevStep.HandlerOrgId,
                            OrgName = prevStep.HandlerOrgName,
                            Key = prevStep.HandlerOrgId,
                            Value = prevStep.HandlerOrgName,
                        };
                        break;
                    case EBusinessType.DepartmentLeader:
                        break;
                    case EBusinessType.CenterMonitor:
                        break;
                    case EBusinessType.CenterLeader:
                        break;
                    case EBusinessType.File:
                    case EBusinessType.Unknown:
                    case EBusinessType.Publish:
                    case EBusinessType.Visit:
                    case EBusinessType.TrashEnd:
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                break;
            case AppDefaults.AppScope.LuZhou:
                switch (prevStepDefine.BusinessType)
                {
                    case EBusinessType.Seat:
                        break;
                    case EBusinessType.Send:
                        break;
                    case EBusinessType.Department:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Org,
                            OrgId = prevStep.HandlerOrgId,
                            OrgName = prevStep.HandlerOrgName,
                            Key = prevStep.HandlerOrgId,
                            Value = prevStep.HandlerOrgName,
                        };
                        break;
                    case EBusinessType.DepartmentLeader:
                        break;
                    case EBusinessType.CenterMonitor:
                        break;
                    case EBusinessType.CenterLeader:
                        break;
                    case EBusinessType.File:
                    case EBusinessType.Unknown:
                    case EBusinessType.Publish:
                    case EBusinessType.Visit:
                    case EBusinessType.TrashEnd:
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                break;
            default:
                throw new ArgumentOutOfRangeException();
        }

        return rsp;
    }

    /// <summary>
    /// 查询特提操作目标节点的指派对象
    /// </summary>
    public async Task<StepAssignInfo?> GetOrderRecallAssignInfoAsync(
        Workflow workflow, StepDefine targetStepDefine, WorkflowStep targetStep,
        BasicWorkflowDto dto, CancellationToken cancellationToken)
    {
        //自贡需求：
        // 1. 工单退回、特提、重办到话务部节点时，所有坐席都可以查看和办理
        // 2. 退回到派单组时需执行平均分配逻辑
        //宜宾需求：
        // 1、退回至话务部：所有坐席都可以查看和办理（除某些场景下本来就需指定办理对象，如：发布时退回……）
        // 2、退回至派单组：默认退给之前的派单员（除某些场景下本来就需指定办理对象，如：发布时退回……）
        // 3、话务员特提至话务部：根据特提申请时候选择来，指定的办理对象才能查看和办理
        // 4、派单员特提至派单组：根据特提申请时候选择来，指定的办理对象才能查看和办理
        // 5、班长特提至派单组，办理对象必选（已实现）
        // 6、班长特提至话务部，办理对象非必选，没选择则所有坐席都可以查看和办理
        //泸州需求：
        /* 1、特提(仅针对特提到热线中心节点）
             1.1、工单特提到话务部、派单组或者班长审批等其它热线中心节点，只有之前办理人才能办理
             2、退回功能(仅针对退回到热线中心节点）
             2.1、退回到热线中心各节点，只有之前办理人才能办理；
        */

        if (workflow.FlowType is not EFlowType.Handle) return null;

        StepAssignInfo? rsp = null;
        switch (_appOptions.Value.AppScope)
        {
            case AppDefaults.AppScope.YiBin:
                switch (targetStepDefine.BusinessType)
                {
                    case EBusinessType.Seat:
                    case EBusinessType.CenterMonitor:
                    case EBusinessType.CenterLeader:
                        if (!dto.NextHandlers.Any())
                        {
                            var define = targetStepDefine.HandlerTypeItems.First();
                            rsp = new StepAssignInfo
                            {
                                FlowAssignType = EFlowAssignType.Role,
                                RoleId = define.Key,
                                RoleName = define.Value,
                                OrgId = targetStep.HandlerOrgId,
                                OrgName = targetStep.HandlerOrgName,
                                Key = define.Key,
                                Value = define.Value,
                            };
                        }

                        break;
                    case EBusinessType.Send:
                        break;
                    case EBusinessType.Department:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Org,
                            OrgId = targetStep.HandlerOrgId,
                            OrgName = targetStep.HandlerOrgName,
                            Key = targetStep.HandlerOrgId,
                            Value = targetStep.HandlerOrgName,
                        };
                        break;
                    case EBusinessType.DepartmentLeader:
                        if (targetStep.FlowAssignType is EFlowAssignType.OrgAndRole &&
                            !string.IsNullOrEmpty(targetStep.HandlerOrgId) &&
                            !string.IsNullOrEmpty(targetStep.RoleId))
                        {
                            rsp = targetStep.GetWorkflowStepHandler();
                        }
                        else
                        {
                            var define = targetStepDefine.HandlerTypeItems.First();
                            rsp = new StepAssignInfo
                            {
                                FlowAssignType = EFlowAssignType.OrgAndRole,
                                OrgId = targetStep.HandlerOrgId,
                                OrgName = targetStep.HandlerOrgName,
                                RoleId = define.Key,
                                RoleName = define.Value,
                                Key = targetStep.HandlerOrgId,
                                Value = targetStep.HandlerOrgName,
                            };
                        }

                        break;
                    case EBusinessType.File:
                    case EBusinessType.Unknown:
                    case EBusinessType.Publish:
                    case EBusinessType.Visit:
                    case EBusinessType.TrashEnd:
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                break;
            case AppDefaults.AppScope.ZiGong:
                switch (targetStepDefine.BusinessType)
                {
                    case EBusinessType.Seat:
                    case EBusinessType.CenterMonitor:
                    case EBusinessType.CenterLeader:
                        var define = targetStepDefine.HandlerTypeItems.First();
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Role,
                            RoleId = define.Key,
                            RoleName = define.Value,
                            OrgId = targetStep.HandlerOrgId,
                            OrgName = targetStep.HandlerOrgName,
                            Key = define.Key,
                            Value = define.Value,
                        };
                        break;
                    case EBusinessType.Send:
                        // 平均派单
                        var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
                        if (averageSendOrder)
                        {
                            var sendOrderTrace = workflow.Traces
                            .Where(x => x.BusinessType == EBusinessType.Send && x.HandlerId != AppDefaults.SendPoolId)
                            .MaxBy(x => x.CreationTime);
                            var prevSendOrder = sendOrderTrace is not null;
                            if (prevSendOrder)
                            {
                                prevSendOrder = await _orderDomainService.SchedulingAtWork(sendOrderTrace.HandlerId);
                            }
                            if (prevSendOrder)
                            {
                                //todo
                                rsp = new StepAssignInfo()
                                {
                                    Key = sendOrderTrace.HandlerId,
                                    Value = sendOrderTrace.HandlerName,
                                    UserId = sendOrderTrace.HandlerId,
                                    Username = sendOrderTrace.HandlerName,
                                    OrgId = sendOrderTrace.HandlerOrgId,
                                    OrgName = sendOrderTrace.HandlerOrgName,
                                    FlowAssignType = EFlowAssignType.User

                                };
                            }
                            else
                            {
                                rsp = await _orderDomainService.AverageOrder(cancellationToken);
                            }
                        }
                        break;
                    case EBusinessType.Department:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Org,
                            OrgId = targetStep.HandlerOrgId,
                            OrgName = targetStep.HandlerOrgName,
                            Key = targetStep.HandlerOrgId,
                            Value = targetStep.HandlerOrgName,
                        };
                        break;
                    case EBusinessType.DepartmentLeader:
                        if (targetStep.FlowAssignType is EFlowAssignType.OrgAndRole &&
                            !string.IsNullOrEmpty(targetStep.HandlerOrgId) &&
                            !string.IsNullOrEmpty(targetStep.RoleId))
                        {
                            rsp = targetStep.GetWorkflowStepHandler();
                        }
                        else
                        {
                            define = targetStepDefine.HandlerTypeItems.First();
                            rsp = new StepAssignInfo
                            {
                                FlowAssignType = EFlowAssignType.OrgAndRole,
                                OrgId = targetStep.HandlerOrgId,
                                OrgName = targetStep.HandlerOrgName,
                                RoleId = define.Key,
                                RoleName = define.Value,
                                Key = targetStep.HandlerOrgId,
                                Value = targetStep.HandlerOrgName,
                            };
                        }

                        break;
                    case EBusinessType.File:
                    case EBusinessType.Unknown:
                    case EBusinessType.Publish:
                    case EBusinessType.Visit:
                    case EBusinessType.TrashEnd:
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                break;
            case AppDefaults.AppScope.LuZhou:
                switch (targetStepDefine.BusinessType)
                {
                    case EBusinessType.Seat:
                    case EBusinessType.Send:
                    case EBusinessType.CenterMonitor:
                    case EBusinessType.CenterLeader:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.User,
                            UserId = targetStep.HandlerId,
                            Username = targetStep.HandlerName,
                            OrgId = targetStep.HandlerOrgId,
                            OrgName = targetStep.HandlerOrgName,
                            Key = targetStep.HandlerId,
                            Value = targetStep.HandlerName,
                        };
                        break;
                    case EBusinessType.Department:
                        rsp = new StepAssignInfo
                        {
                            FlowAssignType = EFlowAssignType.Org,
                            OrgId = targetStep.HandlerOrgId,
                            OrgName = targetStep.HandlerOrgName,
                            Key = targetStep.HandlerOrgId,
                            Value = targetStep.HandlerOrgName,
                        };
                        break;
                    case EBusinessType.DepartmentLeader:
                        if (targetStep.FlowAssignType is EFlowAssignType.OrgAndRole &&
                            !string.IsNullOrEmpty(targetStep.HandlerOrgId) &&
                            !string.IsNullOrEmpty(targetStep.RoleId))
                        {
                            rsp = targetStep.GetWorkflowStepHandler();
                        }
                        else
                        {
                            var define = targetStepDefine.HandlerTypeItems.First();
                            rsp = new StepAssignInfo
                            {
                                FlowAssignType = EFlowAssignType.OrgAndRole,
                                OrgId = targetStep.HandlerOrgId,
                                OrgName = targetStep.HandlerOrgName,
                                RoleId = define.Key,
                                RoleName = define.Value,
                                Key = targetStep.HandlerOrgId,
                                Value = targetStep.HandlerOrgName,
                            };
                        }

                        break;
                    case EBusinessType.File:
                    case EBusinessType.Unknown:
                    case EBusinessType.Publish:
                    case EBusinessType.Visit:
                    case EBusinessType.TrashEnd:
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                break;
            default:
                throw new ArgumentOutOfRangeException();
        }

        return rsp;
    }

    /// <summary>
    /// 工单特提
    /// </summary>
    public async Task<(Workflow, StepDefine, WorkflowStep, WorkflowStep, WorkflowStep, bool)> RecallAsync
        (AuditOrderSpecialDto dto, OrderSpecial special, Order? order, CancellationToken cancellation)
    {
        var recall = new RecallDto
        {
            WorkflowId = special.WorkflowId!,
            NextStepCode = special.NextStepCode,
            NextStepName = special.NextStepName,
            NextHandlers = special.NextHandlers,
            // Opinion = dto.Opinion,
            Opinion = "【特提理由】" + special.Reason,
            FlowDirection = special.FlowDirection,
            HandlerType = special.HandlerType.Value,
            BusinessType = special.BusinessType.Value
        };

        if (dto.FlowDirection is not EFlowDirection.OrgToOrg)
        {
            //重新计算期满时间
            ExpiredTimeWithConfig expiredTime;
            if (_appOptions.Value.IsZiGong)
            {
                if (dto.FlowDirection != null)
                {
                    expiredTime = await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, dto.FlowDirection.Value,
                        order.Adapt<OrderTimeClacInfo>());
                }
                else
                {
                    expiredTime = await _expireTime.CalcEndTime(DateTime.Now, DateTime.Now, order.AcceptTypeCode);
                }
            }
            else
            {
                expiredTime = await _expireTime.CalcEndTime(DateTime.Now, DateTime.Now, order.AcceptTypeCode);
            }

            if (expiredTime?.ExpiredTime > order.ExpiredTime)
            {
                order.ExpiredTime = expiredTime.ExpiredTime;
                order.NearlyExpiredTime = expiredTime.NearlyExpiredTime;
                order.NearlyExpiredTimeOne = expiredTime.NearlyExpiredTimeOne;

                var orderDto = _mapper.Map<OrderDto>(order);
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderExpiredTimeUpdate, orderDto,
                    cancellationToken: cancellation);
            }
        }

        order.ProcessType = special.FlowDirection is EFlowDirection.OrgToCenter or EFlowDirection.CenterToCenter or EFlowDirection.FiledToCenter
            ? EProcessType.Zhiban
            : EProcessType.Jiaoban;

        //todo 特提重办，按审批通过时间依据中心派至部门的规则计算期满时间，更新order

        var (workflow, targetStepDefine, currentStep, targetStep, newStep, isOrgToCenter) =
            await _workflowDomainService.RecallAsync(
                recall, recall.NextHandlers.FirstOrDefault(), EWorkflowTraceType.Recall,
                order.ExpiredTime, order.Status >= EOrderStatus.Filed, EHandleMode.Recall,
                (workflow, currentStep, targetStepDefine, targetStep, targetStepNew) =>
                {
                    var stepAssignInfo = recall.NextHandlers.FirstOrDefault()
                                         ?? GetOrderRecallAssignInfoAsync(workflow, targetStepDefine, targetStep,
                                             recall, cancellation).Result; //todo 优化异步
                    if (stepAssignInfo is null) return;
                    var validator = new StepAssignInfoValidator();
                    validator.ValidateAndThrow(stepAssignInfo);
                    targetStepNew.Assign(stepAssignInfo);
                },
                cancellation);


        if (_appOptions.Value.IsYiBin && order.ActualHandleOrgCode != OrgSeedData.CenterId && order.Status < EOrderStatus.Filed)
        {
            await _circularRecordDomainService.OrderSpecialCircularMessage(special, order, cancellation);
        }

        if (_appOptions.Value.IsZiGong && dto.BusinessType == EBusinessType.Send)
        {
            special.NextHandlers = new List<StepAssignInfo> { newStep.GetWorkflowStepHandler() };
        }

        if (dto.BusinessType == EBusinessType.Send)
        {
            order.CenterToOrgHandlerId = newStep.HandlerId;
            order.CenterToOrgHandlerName = newStep.HandlerName;
        }

        _mapper.Map(workflow, order);
        order.FileEmpty();
        order.Status = targetStepDefine.StepType is EStepType.Start
            ? EOrderStatus.SpecialToUnAccept
            : EOrderStatus.Special;

        await _orderRepository.UpdateAsync(order, cancellation);

        return (workflow, targetStepDefine, currentStep, targetStep, newStep, isOrgToCenter);
    }

    #region private

    /// <summary>
    /// 接受外部工单（除省平台）
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<AddOrderResponse> ReceiveOrderFromOtherPlatformAsync(AddOrderDto dto, List<FileDto> files, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(dto.ExternalId))
            throw new UserFriendlyException("工单外部编号不能为空");

        var order = await _orderRepository.Queryable()
            .FirstAsync(d => d.ExternalId == dto.ExternalId, cancellationToken);
        if (order == null)
        {
            order = _mapper.Map<Order>(dto);
            if (order.IsSecret == true && _appOptions.Value.IsYiBin == false)
            {
                order.FocusOnEventsName = "保密";
                order.FocusOnEvents = "99";
            }

            order.InitId();
            if (files != null && files.Any())
                order.FileJson = await _fileRepository.AddFileAsync(files, order.Id, "", cancellationToken);
            await _orderDomainService.AddAsync(order, cancellationToken: cancellationToken);
        }
        else
        {
            _mapper.Map(dto, order);
            if (files != null && files.Any())
                order.FileJson = await _fileRepository.AddFileAsync(files, order.Id, "", cancellationToken);
            else
                order.FileJson = new List<Share.Dtos.File.FileJson>();
            await _orderRepository.UpdateAsync(order, cancellationToken);
        }

        return _mapper.Map<AddOrderResponse>(order);
    }

    /// <summary>
    /// 接受省平台工单
    /// </summary>
    private async Task<AddOrderResponse> ReceiveOrderFromProvinceAsync(AddOrderDto dto, List<FileDto> files, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(dto.ReceiveProvinceNo))
            throw new UserFriendlyException("无效省工单编号");

        var orderExtension = await _orderDomainService.GetOrderExtensionsAsync(dto.ReceiveProvinceNo, cancellationToken);

        var order = await _orderRepository.Queryable().Includes(d => d.Workflow).FirstAsync(d => d.ReceiveProvinceNo == dto.ReceiveProvinceNo);

        //处理省下行数据，热点名称为空
        if (!string.IsNullOrEmpty(dto.HotspotId) && string.IsNullOrEmpty(dto.HotspotName))
        {
            var hotData = await _hotspotRepository.GetAsync(p => p.Id == dto.HotspotId, cancellationToken);
            if (hotData != null)
            {
                dto.HotspotName = hotData.HotSpotName;
                dto.HotspotSpliceName = hotData.HotSpotFullName;
            }
        }

        if (order is null)
        {
            order = _mapper.Map<Order>(dto);
            order.InitId();

            //如果手里类型不等于空 并且受理类型名称等于空
            if (!string.IsNullOrEmpty(order.AcceptTypeCode))
            {
                var acceptModel = _sysDicDataCacheManager.AcceptType.Where(x => x.DicDataValue == order.AcceptTypeCode).FirstOrDefault();
                if (acceptModel != null)
                {
                    order.AcceptType = acceptModel.DicDataName;
                }
            }

            if (order.IsSecret == true && _appOptions.Value.IsYiBin == false)
            {
                order.FocusOnEventsName = "保密";
                order.FocusOnEvents = "99";
            }

            if (files != null && files.Any())
                order.FileJson = await _fileRepository.AddFileAsync(files, order.Id, "", cancellationToken);
            await _orderDomainService.AddAsync(order, cancellationToken: cancellationToken);

            if (orderExtension is not null)
            {
                orderExtension.Id = order.Id;
                if (dto.OrderExtension != null)
                    _mapper.Map(dto.OrderExtension, orderExtension);
                await _orderDomainService.UpdateExtensionAsync(orderExtension, cancellationToken);
            }
        }
        else
        {
            _mapper.Map(dto, order);
            if (files != null && files.Any())
                order.FileJson = await _fileRepository.AddFileAsync(files, order.Id, "", cancellationToken);
            else
                order.FileJson = new List<Share.Dtos.File.FileJson>();
            //order.ReTransactNum++;
            if (order.ProvinceReTransactNum.HasValue)
                order.ProvinceReTransactNum = order.ProvinceReTransactNum + 1;
            else
                order.ProvinceReTransactNum = 1;

            if (order.IsSecret == true)
            {
                order.FocusOnEventsName = "保密";
                order.FocusOnEvents = "99";
            }
            //await _orderRepository.UpdateAsync(order, cancellationToken);

            if (orderExtension is not null)
            {
                orderExtension.Id = order.Id;
                if (dto.OrderExtension != null)
                    _mapper.Map(dto.OrderExtension, orderExtension);
                await _orderDomainService.UpdateExtensionAsync(orderExtension, cancellationToken);
            }

            //计算order 期满时间
            ExpiredTimeWithConfig expiredTimeConfig;
            if (_appOptions.Value.IsZiGong)
            {
                expiredTimeConfig = await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToCenter,
                    order.Adapt<OrderTimeClacInfo>());
            }
            else
            {
                //期满时间
                //expiredTimeConfig = _timeLimitDomainService.CalcExpiredTime(DateTime.Now, EFlowDirection.CenterToOrg, order.AcceptTypeCode);
                expiredTimeConfig =
                    await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToOrg, order.Adapt<OrderTimeClacInfo>());
            }

            _mapper.Map(expiredTimeConfig, order);
            //await _orderRepository.UpdateAsync(order, cancellationToken);

            //特提（撤回至发起)
            if (!string.IsNullOrEmpty(order.WorkflowId))
            {
                // FlowStepHandler? handler = null;
                // if (_appOptions.Value.IsZiGong)
                // {
                //     // 平均派单
                //     var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
                //     if (averageSendOrder)
                //     {
                //         handler = await _orderDomainService.AverageOrder(cancellationToken);
                //     }
                // }
                //
                // StepAssignInfo? stepAssignInfo = null;
                // if (handler is not null)
                // {
                //     stepAssignInfo = _mapper.Map<StepAssignInfo>(handler);
                //     stepAssignInfo.FlowAssignType = EFlowAssignType.User;
                // }
                //
                // var reverseFlowStepAssignInfo = stepAssignInfo is null
                //     ? new ReverseFlowStepAssignInfo(EReverseFlowStepCreationPolicy.OriginStep)
                //     : new ReverseFlowStepAssignInfo(EReverseFlowStepCreationPolicy.OriginStepUser, stepAssignInfo);
                //await _workflowDomainService.RecallToStartStepAsync(order.WorkflowId, "省工单重派", current, order.Status >= EOrderStatus.Filed, cancellationToken);

                var flowAssignType = _appOptions.Value.IsYiBin
                    ? EFlowAssignType.User
                    : EFlowAssignType.Role;

                var (isPaiDan, workflow) = await _workflowDomainService.RecallToCenterFirstToSendAsync(order.WorkflowId, "省工单重派",
                    order.Status >= EOrderStatus.Filed, order.ExpiredTime, EHandleMode.Redo, flowAssignType, cancellationToken);

                order.FileEmpty();

                order.CurrentStepName = workflow.CurrentStepName;
                order.CurrentStepCode = workflow.CurrentStepCode;
                order.CurrentStepId = workflow.CurrentStepId;
                order.CurrentStepCreateTime = workflow.CurrentStepCreateTime;
                order.CurrentHandleTime = workflow.CurrentHandleTime;
                order.CurrentHandlerId = workflow.CurrentHandlerId;
                order.CurrentHandlerName = workflow.CurrentHandlerName;
                order.CurrentHandleOrgName = workflow.CurrentHandleOrgName;
                order.CurrentHandleOrgId = workflow.CurrentHandleOrgId;
                order.CurrentHandleOrgLevel = workflow.CurrentHandleOrgLevel;
                order.CurrentHandleOrgAreaCode = workflow.CurrentHandleOrgAreaCode;
                order.CurrentHandleOrgAreaName = workflow.CurrentHandleOrgAreaName;

                order.Status = EOrderStatus.WaitForAccept;
                if (isPaiDan)
                {
                    order.Status = EOrderStatus.Special;
                }
                //await _orderRepository.Updateable().SetColumns(o => new Order { Status = status }).Where(o => o.Id == order.Id).ExecuteCommandAsync(cancellationToken);

                //处理回访和发布信息

                var publish = await _orderPublishRepository.GetAsync(x => x.OrderId == order.Id);
                if (publish != null)
                {
                    var publishHistory = _mapper.Map<OrderPublishHistory>(publish);
                    publishHistory.OrderPublishId = publish.Id;
                    publishHistory.ArrangeTitleAfter = publish.ArrangeTitle;
                    publishHistory.ArrangeTitleBefor = publish.ArrangeTitle;
                    publishHistory.ArrangeContentAfter = publish.ArrangeContent;
                    publishHistory.ArrangeContentBefor = publish.ArrangeContent;
                    publishHistory.ArrangeOpinionAfter = publish.ArrangeOpinion;
                    publishHistory.ArrangeOpinionBefor = publish.ArrangeOpinion;
                    await _orderPublishHistoryRepository.AddAsync(publishHistory, cancellationToken);
                    await _orderPublishRepository.RemoveAsync(publish, false, cancellationToken);
                }

                var visit = await _orderVisitRepository.GetAsync(x => x.OrderId == order.Id && x.VisitState != EVisitState.None);
                if (visit != null)
                {
                    visit.VisitState = EVisitState.None;
                    await _orderVisitRepository.UpdateAsync(visit, cancellationToken);
                }
            }

            await _orderRepository.UpdateAsync(order, cancellationToken);
            //await _workflowDomainService.RecallToStartStepAsync(order.WorkflowId, "省工单重派", current, cancellationToken);

            //删除甄别、延期、二次办理等数据
            await SpecialNewVerify(order, cancellationToken);
        }

        return _mapper.Map<AddOrderResponse>(order);
    }

    /// <summary>
    /// 派单量统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<List<SendOrderReportOutDto>> SendOrderReportAsync(QuerySendOrderRequest dto)
    {
        if (_appOptions.Value.IsLuZhou)
        {
            return await SendOrderReportAsync_LZ(dto);
        }
        var itemsHandled = _workflowTraceRepository.Queryable()
            .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
            .InnerJoin<SchedulingUser>((x, w, su) => x.HandlerId == su.UserId)
            .Where((x, w, su) => w.ModuleCode == "OrderHandle" && x.BusinessType == EBusinessType.Send && x.Status == EWorkflowStepStatus.Handled)
            .Where((x, w, su) => x.HandleTime >= dto.StartTime.Value)
            .Where((x, w, su) => x.HandleTime <= dto.EndTime.Value)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), (x, w, su) => su.UserName == dto.UserName)
            .GroupBy((x, w, su) => new { su.UserId, su.UserName })
            .Select((x, w, su) => new BiOrderSendVo
            {
                UserId = su.UserId,
                UserName = su.UserName,
                SendOrderNum = SqlFunc.AggregateDistinctCount(w.ExternalId),
                NoSendOrderNum = 0,
            });
        var itemsNo = _workflowTraceRepository.Queryable()
            .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
            .InnerJoin<SchedulingUser>((x, w, su) => x.HandlerId == su.UserId)
            .Where((x, w, su) => w.ModuleCode == "OrderHandle" && x.BusinessType == EBusinessType.Send && x.Status != EWorkflowStepStatus.Handled)
            .Where((x, w, su) => x.CreationTime >= dto.StartTime.Value)
            .Where((x, w, su) => x.CreationTime <= dto.EndTime.Value)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), (x, w, su) => su.UserName == dto.UserName)
            .GroupBy((x, w, su) => new { su.UserId, su.UserName })
            .Select((x, w, su) => new BiOrderSendVo
            {
                UserId = su.UserId,
                UserName = su.UserName,
                SendOrderNum = 0,
                NoSendOrderNum = SqlFunc.AggregateDistinctCount(w.ExternalId),
            });
        var items = await _schedulingUserRepository.Queryable()
            .LeftJoin(itemsHandled, (all, hand) => all.UserId == hand.UserId)
            .LeftJoin(itemsNo, (all, hand, nohand) => hand.UserId == nohand.UserId)
            .GroupBy((all, hand, nohand) => new { all.UserId, all.UserName })
            .Select((all, hand, nohand) => new BiOrderSendVo
            {
                UserId = all.UserId,
                UserName = all.UserName,
                SendOrderNum = SqlFunc.AggregateSum(hand.SendOrderNum),
                NoSendOrderNum = SqlFunc.AggregateSum(nohand.NoSendOrderNum),
            }).MergeTable().Where(vo => vo.SendOrderNum > 0 || vo.NoSendOrderNum > 0).ToListAsync();

        var items2 = await _workflowTraceRepository.Queryable()
            .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
            //.LeftJoin<WorkflowStepHandler>((x, w, wfsh) => x.StepId == wfsh.WorkflowStepId && wfsh.IsActualHandler == true)
            .InnerJoin<SchedulingUser>((x, w, su) => x.HandlerId == su.UserId)
            .Where((x, w, su) => w.ModuleCode == WorkflowModuleConsts.OrderHandle && x.BusinessType == EBusinessType.Send &&
                                 x.Status == EWorkflowStepStatus.Handled
                                 && !string.IsNullOrEmpty(x.NextMainHandler) && x.NextMainHandler != OrgSeedData.CenterId)
            .Where((x, w, su) => x.CreationTime >= dto.StartTime.Value)
            .Where((x, w, su) => x.CreationTime <= dto.EndTime.Value)
            .GroupBy((x, w, su) => x.WorkflowId)
            .Having((x, w, su) => SqlFunc.AggregateCount(x.WorkflowId) > 1)
            .Select((x, w, su) => new { Id = x.WorkflowId, CreationTime = SqlFunc.AggregateMin(x.CreationTime) })
            .MergeTable()
            .LeftJoin<WorkflowTrace>((a, wt) => a.Id == wt.WorkflowId)
            .LeftJoin<Workflow>((a, wt, wf) => wt.WorkflowId == wf.Id)
            //.LeftJoin<WorkflowStepHandler>((a, wt, wf, wsh) => wt.StepId == wsh.WorkflowStepId && wsh.CreationTime == a.CreationTime)
            .InnerJoin<SchedulingUser>((a, wt, wf, su) => wt.HandlerId == su.UserId)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), ((a, wt, wf, su) => su.UserName == dto.UserName))
            .GroupBy((a, wt, wf, su) => new { su.UserId, su.UserName })
            .Select((a, wt, wf, su) => new BiOrderSendVo
            {
                UserId = su.UserId,
                UserName = su.UserName,
                SendOrderNum = 0,
                NoSendOrderNum = 0,
                ReSendOrderNum = SqlFunc.AggregateDistinctCount(wf.ExternalId),
            }).ToListAsync();

        var res = (from t1 in items
                   join t2 in items2 on t1.UserId equals t2.UserId into t1_t2
                   from item in t1_t2.DefaultIfEmpty()
                   select new SendOrderReportOutDto
                   {
                       UserId = t1.UserId,
                       UserName = t1.UserName,
                       SendOrderNum = t1.SendOrderNum,
                       NoSendOrderNum = t1.NoSendOrderNum,
                       ReSendOrderNum = t1_t2.Select(x => x.ReSendOrderNum).FirstOrDefault(),
                       ChainRate = t1_t2.Select(x => x.ReSendOrderNum).FirstOrDefault() > 0
                           ? ((double.Parse(t1.SendOrderNum.ToString()) - double.Parse(t1_t2.Select(x => x.ReSendOrderNum).FirstOrDefault().ToString())) /
                               double.Parse(t1.SendOrderNum.ToString()) * 100).ToString("F2") + "%"
                           : "100.00%",
                   }).ToList();
        return res;
    }

    /// <summary>
    /// 泸州派单量统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<List<SendOrderReportOutDto>> SendOrderReportAsync_LZ(QuerySendOrderRequest dto)
    {
        var itemsHandled = _workflowTraceRepository.Queryable()
               .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
               .Where((x, w) => w.ModuleCode == WorkflowModuleConsts.OrderHandle && x.Status == EWorkflowStepStatus.Handled && !SqlFunc.JsonListObjectAny(x.NextHandlers, "OrgId", OrgSeedData.CenterId) && (x.Name == "派单组" || x.Name == "班长审批"))
               .Where((x, w) => x.HandleTime >= dto.StartTime.Value)
               .Where((x, w) => x.HandleTime <= dto.EndTime.Value)
               .WhereIF(!string.IsNullOrEmpty(dto.UserName), (x, w) => x.HandlerName == dto.UserName)
               .GroupBy((x, w) => new { x.HandlerId, x.HandlerName, x.Name })
               .Select((x, w) => new BiOrderSendVo
               {
                   UserId = x.HandlerId,
                   UserName = x.HandlerName,
                   StepName = x.Name,
                   SendOrderNum = SqlFunc.AggregateDistinctCount(w.ExternalId),
                   NoSendOrderNum = 0,
                   ReSendOrderNum = 0,
               });
        var itemsNo = _workflowTraceRepository.Queryable()
            .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
            .Where((x, w) => w.ModuleCode == WorkflowModuleConsts.OrderHandle && x.Status != EWorkflowStepStatus.Handled && (x.Name == "派单组" || x.Name == "班长审批"))
            .Where((x, w) => x.CreationTime >= dto.StartTime.Value)
            .Where((x, w) => x.CreationTime <= dto.EndTime.Value)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), (x, w) => x.HandlerName == dto.UserName)
            .GroupBy((x, w) => new { x.HandlerId, x.HandlerName, x.Name })
            .Select((x, w) => new BiOrderSendVo
            {
                UserId = x.HandlerId,
                UserName = x.HandlerName,
                StepName = x.Name,
                SendOrderNum = 0,
                NoSendOrderNum = SqlFunc.AggregateDistinctCount(w.ExternalId),
                ReSendOrderNum = 0,
            });

        var items2 = _workflowTraceRepository.Queryable()
            .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
            .Where((x, w) => w.ModuleCode == WorkflowModuleConsts.OrderHandle &&
                                 x.Status == EWorkflowStepStatus.Handled
                                 && !string.IsNullOrEmpty(x.NextMainHandler) && x.NextMainHandler != OrgSeedData.CenterId && (x.Name == "派单组" || x.Name == "班长审批"))
            .Where((x, w) => x.CreationTime >= dto.StartTime.Value)
            .Where((x, w) => x.CreationTime <= dto.EndTime.Value)
            .GroupBy((x, w) => x.WorkflowId)
            .Having((x, w) => SqlFunc.AggregateCount(x.WorkflowId) > 1)
            .Select((x, w) => new { Id = x.WorkflowId, CreationTime = SqlFunc.AggregateMin(x.CreationTime) })
            .MergeTable()
            .LeftJoin<WorkflowTrace>((a, wt) => a.Id == wt.WorkflowId)
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), ((a, wt) => wt.HandlerName == dto.UserName))
            .GroupBy((a, wt) => new { wt.HandlerId, wt.HandlerName, wt.Name })
            .Select((a, wt) => new BiOrderSendVo
            {
                UserId = wt.HandlerId,
                UserName = wt.HandlerName,
                StepName = wt.Name,
                SendOrderNum = 0,
                NoSendOrderNum = 0,
                ReSendOrderNum = SqlFunc.AggregateDistinctCount(wt.ExternalId),
            });

        var items = await _orderRepository.UnionAll(itemsHandled, itemsNo, items2)
         .GroupBy(x => new { x.UserId, x.UserName, x.StepName })
         .Select(x => new BiOrderSendVo
         {
             UserId = x.UserId,
             UserName = x.UserName,
             StepName = x.StepName,
             SendOrderNum = SqlFunc.AggregateSum(x.SendOrderNum),
             NoSendOrderNum = SqlFunc.AggregateSum(x.NoSendOrderNum),
             ReSendOrderNum = SqlFunc.AggregateSum(x.ReSendOrderNum)
         }).ToListAsync();
        var res = items.Select(p => new SendOrderReportOutDto
        {
            UserId = p.UserId,
            UserName = p.UserName,
            StepName = p.StepName,
            SendOrderNum = p.SendOrderNum,
            NoSendOrderNum = p.NoSendOrderNum,
            ReSendOrderNum = p.ReSendOrderNum,
            ChainRate = p.AccuracyRate
        }).ToList();
        return res;
    }


    public ISugarQueryable<Order> QuerySendOrderDetail(QuerySendOrderDetailRequest dto)
    {
        if (_appOptions.Value.IsLuZhou)
        {
            return QuerySendOrderDetail_LZ(dto);

        }
        if (dto.TitleCode.ToUpper() == "RESENDORDERNUM")
        {
            var query = _workflowTraceRepository.Queryable()
                          .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
                          .InnerJoin<SchedulingUser>((x, w, su) => x.HandlerId == su.UserId)
                          .Where((x, w, su) => w.ModuleCode == WorkflowModuleConsts.OrderHandle && x.BusinessType == EBusinessType.Send && x.Status == EWorkflowStepStatus.Handled
                                               && !string.IsNullOrEmpty(x.NextMainHandler) && x.NextMainHandler != OrgSeedData.CenterId)
                          .Where((x, w, su) => x.CreationTime >= dto.StartTime.Value)
                          .Where((x, w, su) => x.CreationTime <= dto.EndTime.Value)
                          .GroupBy((x, w, su) => x.WorkflowId)
                          .Having((x, w, su) => SqlFunc.AggregateCount(x.WorkflowId) > 1)
                           .Select((x, w, su) => new { Id = x.WorkflowId, CreationTime = SqlFunc.AggregateMin(x.CreationTime) })
                          .MergeTable()
                          .LeftJoin<WorkflowTrace>((a, wt) => a.Id == wt.WorkflowId)
                          .LeftJoin<Workflow>((a, wt, wf) => wt.WorkflowId == wf.Id)
                          .InnerJoin<SchedulingUser>((a, wt, wf, su) => wt.HandlerId == su.UserId)
                          .Where((a, wt, wf, su) => su.UserId == dto.UserId)
                          .GroupBy((a, wt, wf, su) => wf.ExternalId)
                          .Select((a, wt, wf, su) => new { Id = wf.ExternalId })
                          .MergeTable()
                          .LeftJoin<Order>((a, b) => a.Id == b.Id)
                          .Select((a, b) => b);
            return query;
        }
        var query2 = _workflowTraceRepository.Queryable()
                .InnerJoin<SchedulingUser>((x, su) => x.HandlerId == su.UserId)
                .Where((x, su) => x.ModuleCode == WorkflowModuleConsts.OrderHandle && x.BusinessType == EBusinessType.Send)
                .Where((x, su) => x.CreationTime >= dto.StartTime.Value && x.CreationTime <= dto.EndTime.Value && su.UserId == dto.UserId)
                .WhereIF(dto.TitleCode.ToUpper() == "NOSENDORDERNUM", (x, su) => x.Status != EWorkflowStepStatus.Handled)
                .WhereIF(dto.TitleCode.ToUpper() == "SENDORDERNUM", (x, su) => x.Status == EWorkflowStepStatus.Handled)
                .GroupBy((x, su) => x.ExternalId)
                .Select((x, su) => new { Id = x.ExternalId })
                .MergeTable()
                .LeftJoin<Order>((a, b) => a.Id == b.Id)
                .Select((a, b) => b);
        return query2;
    }

    public ISugarQueryable<Order> QuerySendOrderDetail_LZ(QuerySendOrderDetailRequest dto)
    {
        if (dto.TitleCode.ToUpper() == "RESENDORDERNUM")
        {
            var query = _workflowTraceRepository.Queryable()
                          .LeftJoin<Workflow>((x, w) => x.WorkflowId == w.Id)
                          .Where((x, w) => w.ModuleCode == WorkflowModuleConsts.OrderHandle && x.Status == EWorkflowStepStatus.Handled
                                               && !string.IsNullOrEmpty(x.NextMainHandler) && x.NextMainHandler != OrgSeedData.CenterId && (x.Name == "派单组" || x.Name == "班长审批"))
                          .Where((x, w) => x.CreationTime >= dto.StartTime.Value)
                          .Where((x, w) => x.CreationTime <= dto.EndTime.Value)
                          .WhereIF(dto.RoleName is "派单员", (x, w) => x.Name == "派单组")
                          .WhereIF(dto.RoleName is "中心班长", (x, w) => x.Name == "班长审批")
                          .GroupBy((x, w) => x.WorkflowId)
                          .Having((x, w) => SqlFunc.AggregateCount(x.WorkflowId) > 1)
                           .Select((x, w) => new { Id = x.WorkflowId, CreationTime = SqlFunc.AggregateMin(x.CreationTime) })
                          .MergeTable()
                          .LeftJoin<WorkflowTrace>((a, wt) => a.Id == wt.WorkflowId)
                          .LeftJoin<Workflow>((a, wt, wf) => wt.WorkflowId == wf.Id)
                          .Where((a, wt, wf) => wt.HandlerId == dto.UserId)
                          .GroupBy((a, wt, wf) => wf.ExternalId)
                          .Select((a, wt, wf) => new { Id = wf.ExternalId })
                          .MergeTable()
                          .LeftJoin<Order>((a, b) => a.Id == b.Id)
                          .Select((a, b) => b);
            return query;
        }
        var query2 = _workflowTraceRepository.Queryable()
                .Where(x => x.ModuleCode == WorkflowModuleConsts.OrderHandle && (x.Name == "派单组" || x.Name == "班长审批"))
                .Where(x => x.CreationTime >= dto.StartTime.Value && x.CreationTime <= dto.EndTime.Value && x.HandlerId == dto.UserId)
                .WhereIF(dto.TitleCode.ToUpper() == "NOSENDORDERNUM", x => x.Status != EWorkflowStepStatus.Handled)
                .WhereIF(dto.TitleCode.ToUpper() == "SENDORDERNUM", x => x.Status == EWorkflowStepStatus.Handled && !SqlFunc.JsonListObjectAny(x.NextHandlers, "OrgId", OrgSeedData.CenterId))
                .WhereIF(dto.RoleName is "派单员", x => x.Name == "派单组")
                .WhereIF(dto.RoleName is "中心班长", x => x.Name == "班长审批")
                .GroupBy(x => x.ExternalId)
                .Select(x => new { Id = x.ExternalId })
                .MergeTable()
                .LeftJoin<Order>((a, b) => a.Id == b.Id)
                .Select((a, b) => b);
        return query2;
    }

    /// <summary>
    /// 扭转信件统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderVisitJudeStatisticsRep> OrderVisitJudeStatistics(OrderVisitJudeStatisticsReq dto)
    {
        if (!dto.EndTime.HasValue)
        {
            dto.EndTime = dto.StartTime?.AddDays(1).AddSeconds(-1);
        }
        else
        {
            dto.EndTime = dto.EndTime?.AddDays(1).AddSeconds(-1);
        }

        return _orderVisitRepository.Queryable()
            .WhereIF(dto.StartTime.HasValue, x => x.VisitTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, x => x.VisitTime <= dto.EndTime)
            .GroupBy(x => new { EmployeeId = x.EmployeeId, Name = x.Employee.Name })
            .Select(x => new OrderVisitJudeStatisticsRep()
            {
                EmpId = x.EmployeeId,
                EmpName = x.Employee.Name,
                OrgJudeCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.OrgJudge.HasValue && x.OrgJudge == true && x.JudgeState != null, 1, 0)), //部门扭转总件
                OrgJudeApprovalingCount =
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.OrgJudge.HasValue && x.OrgJudge == true && x.JudgeState == EJudgeState.Judging, 1, 0)),
                OrgJudeSuccessCount =
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.OrgJudge.HasValue && x.OrgJudge == true && x.JudgeState == EJudgeState.Agreed, 1, 0)),
                OrgJudeFailCount =
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.OrgJudge.HasValue && x.OrgJudge == true && x.JudgeState == EJudgeState.UnAgreed, 1, 0)),
                SeatJudeCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.SeatJudge.HasValue && x.SeatJudge == true && x.JudgeState != null, 1, 0)),
                SeatJudeApprovalingCount =
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.SeatJudge.HasValue && x.SeatJudge == true && x.JudgeState == EJudgeState.Judging, 1, 0)),
                SeatJudeSuccessCount =
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.SeatJudge.HasValue && x.SeatJudge == true && x.JudgeState == EJudgeState.Agreed, 1, 0)),
                SeatJudeFailCount =
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.SeatJudge.HasValue && x.SeatJudge == true && x.JudgeState == EJudgeState.UnAgreed, 1, 0))
            });
    }

    /// <summary>
    /// 观察关注列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderObserve> OrderObserveList(OrderObserveListDto dto)
    {
        return _orderObserveRepository.Queryable()
            .Includes(d => d.Order)
            .WhereIF(dto.IsProvince.HasValue, d => d.Order.IsProvince == dto.IsProvince)
            //.WhereIF(!string.IsNullOrEmpty(dto.Keyword),
            //    x => x.Order.No.Contains(dto.Keyword!) || x.Order.Title.Contains(dto.Keyword!))
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot)) //热点类型
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName),
                d => d.Order.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
            .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.Order.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
            .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.Order.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
            .WhereIF(dto.StartTime.HasValue, d => d.CreationTime >= dto.StartTime) //受理时间开始
            .WhereIF(dto.EndTime.HasValue, d => d.CreationTime <= dto.EndTime) //受理时间结束
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title!))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Order.No.Contains(dto.No!))
            .OrderByDescending(d => d.CreationTime);
    }

    /// <summary>
    /// 终止列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderTerminate> OrderTerminateList(OrderTerminateListDto dto)
    {
        var handler = dto.AuditStatus is 2 or 0 || dto.QueryType is 0;
        var isAdmin = _orderDomainService.IsCheckAdmin();
        return _orderTerminateRepository.Queryable(hasHandled: handler, isAdmin: isAdmin)
            .Includes(d => d.Order)
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Order.No!.Contains(dto.No!))
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title!.Contains(dto.Title!))
            .WhereIF(dto.ApplyStartTime.HasValue && dto.ApplyEndTime.HasValue,
                d => d.CreationTime >= dto.ApplyStartTime && d.CreationTime <= dto.ApplyEndTime)
            //.WhereIF(dto.AuditStatus is 1 , d=>d.Status == ETerminateStatus.Approval || d.Status == ETerminateStatus.SendBack )
            //.WhereIF(dto.AuditStatus is 2, d => d.Status == ETerminateStatus.End || dto.Status == ETerminateStatus.Refuse)
            .WhereIF(dto.QueryType is 1, d => d.CreatorId == _sessionContext.UserId)
            .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status)
            .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, d => d.Order.StartTime >= dto.StartTime && d.Order.StartTime <= dto.EndTime)
            .OrderByDescending(d => d.CreationTime);
    }

    public ISugarQueryable<Order> QueryWaitedForSeat(QueryOrderWaitedDto dto)
    {
        //EOrderStatus[] handleStatuses = EnumExts.GetFields<EOrderStatus>().Select(d => (EOrderStatus)d.Key).ToArray();
        //handleStatuses = handleStatuses.WhereIF(dto.IsHandled.HasValue,
        //        d => dto.IsHandled!.Value
        //            ? d is not EOrderStatus.WaitForAccept and not EOrderStatus.BackToUnAccept and not EOrderStatus.SpecialToUnAccept and not EOrderStatus.HandOverToUnAccept
        //            : d is EOrderStatus.WaitForAccept or EOrderStatus.BackToUnAccept or EOrderStatus.SpecialToUnAccept or EOrderStatus.HandOverToUnAccept or EOrderStatus.Handling
        //            or EOrderStatus.Countersigning)
        //    .ToArray();

        //var query = _orderRepository.Queryable()
        //    .Includes(d => d.WorkflowSteps.Where(step =>
        //            ((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)) ||
        //             (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) && _sessionContext.Roles.Contains(step.RoleId)
        //              && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId)))
        //        .OrderByDescending(step => step.CreationTime)
        //        .Take(1)
        //        .ToList()
        //    );
        var query = _orderRepository.Queryable();

        switch (dto.TypeCode)
        {
            case 0: //待办
                query.Includes(d => d.WorkflowSteps.Where(step =>
                            ((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)) ||
                             (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) &&
                              _sessionContext.Roles.Contains(step.RoleId)
                              && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId))
                            && step.Status < EWorkflowStepStatus.Handled)
                        .OrderByDescending(step => step.CreationTime)
                        .Take(1)
                        .ToList())
                    .Where(d => d.WorkflowSteps
                                    .Any(step =>
                                        ((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)) ||
                                         (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) &&
                                          _sessionContext.Roles.Contains(step.RoleId)
                                          && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId))
                                        && step.Status < EWorkflowStepStatus.Handled)
                                || (SqlFunc.IsNullOrEmpty(d.WorkflowId)
                                    && (SqlFunc.IsNullOrEmpty(d.SignerId) ||
                                        (!SqlFunc.IsNullOrEmpty(d.SignerId) && d.SignerId == _sessionContext.UserId)))
                    )
                    .Where(d => d.Status <= EOrderStatus.HandOverToUnAccept
                                || d.Status == EOrderStatus.Handling //指派给班长再指派回坐席时
                                                                     //|| d.Status == EOrderStatus.Countersigning//跨级派单业务如发起会签再回到坐席会签汇总时
                    )
                    ;

                break;
            case 1: //交办: 已派单其他节点的工单，该选项卡下工单若办结就不显示
                query.Includes(d => d.WorkflowSteps.Where(step =>
                        !string.IsNullOrEmpty(step.HandlerId)
                        && step.HandlerId == _sessionContext.UserId
                        && step.Status == EWorkflowStepStatus.Handled
                    ).ToList())
                    .Where(d => d.WorkflowSteps
                                    .Any(step =>
                                        !string.IsNullOrEmpty(step.HandlerId)
                                        && step.HandlerId == _sessionContext.UserId
                                        && step.Status == EWorkflowStepStatus.Handled)
                                && d.Status < EOrderStatus.Filed);
                break;
            case 2: //办结: 当前登录坐席作为最初受理人已办结的工单
                query.Where(d =>
                    d.Status >= EOrderStatus.Filed
                    && d.AcceptorId == _sessionContext.RequiredUserId);
                break;
        }


        //query = query.Where(d => SqlFunc.Subqueryable<WorkflowTrace>()
        //.Where(step => step.ExternalId == d.Id &&
        //    (hasHandled || step.Status != EWorkflowStepStatus.Handled) &&
        //    (!hasHandled || step.Status == EWorkflowStepStatus.Handled &&
        //    step.TraceState != EWorkflowTraceState.StepRemoveByPrevious) &&
        //    ((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() ||
        //    (string.IsNullOrEmpty(d.WorkflowId) && (string.IsNullOrEmpty(d.SignerId) || d.SignerId == _sessionContext.RequiredUserId))
        //);

        //随手拍

        if (_systemSettingCacheManager.Snapshot && !string.IsNullOrEmpty(dto.IndustryId))
        {
            query.Where(d => d.OrderSnapshot.IndustryId == dto.IndustryId);
        }

        return query
                //// 交办件：已派单其他节点的工单，该选项卡下工单若办结就不显示
                //.WhereIF(dto.TypeCode.HasValue == true && dto.TypeCode == 1, d => /*d.ProcessType == EProcessType.Jiaoban &&*/ d.Status < EOrderStatus.Filed)
                //// 办结件：当前登录坐席作为最初受理人已办结的工单
                //.WhereIF(dto.TypeCode.HasValue == true && dto.TypeCode == 2, d => d.Status >= EOrderStatus.Filed && d.AcceptorId == _sessionContext.RequiredUserId)
                .WhereIF(dto.IsProvince.HasValue, d => d.IsProvince == dto.IsProvince)
                //.WhereIF(dto.IsHandled.HasValue, d => handleStatuses.Contains(d.Status))
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.StartsWith(dto.Keyword!))
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No == dto.No)
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode), d => d.AreaCode == dto.AreaCode)
                .WhereIF(dto.IsCounterSign.HasValue && dto.IsCounterSign == true, d => d.CounterSignType.HasValue)
                .WhereIF(dto.IsCounterSign.HasValue && dto.IsCounterSign == false, d => d.CounterSignType == null)
                .WhereIF(dto.ExpiredOrAlmostOverdue.HasValue && dto.ExpiredOrAlmostOverdue == true,
                    d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                         (d.ExpiredTime < d.ActualHandleTime && d.Status >= EOrderStatus.Filed)) //超期 未办
                .WhereIF(dto.ExpiredOrAlmostOverdue.HasValue && dto.ExpiredOrAlmostOverdue == false,
                    d => d.NearlyExpiredTime < DateTime.Now && d.ExpiredTime > DateTime.Now) //即将超期 未办
                .WhereIF(dto.StartTime.HasValue, d => d.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, d => d.CreationTime <= dto.EndTime)
                //.Where(d => (string.IsNullOrEmpty(d.WorkflowId) && (string.IsNullOrEmpty(d.SignerId) || d.SignerId == _sessionContext.RequiredUserId)))
                //.Where(d => string.IsNullOrEmpty(d.SignerId) || d.SignerId == _sessionContext.RequiredUserId)
                .WhereIF(dto.IsUrgent.HasValue, d => d.IsUrgent == dto.IsUrgent.Value)
                .Where(x => x.Source < ESource.MLSQ || x.Source > ESource.WZSC)
                .Where(x => x.Status != EOrderStatus.BackToProvince)
                //.WhereIF(dto.TypeCode.HasValue == false, m => m.Status < EOrderStatus.Filed)
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptorName), d => d.AcceptorName == dto.AcceptorName)
                //.OrderBy(d => d.Status)

                .OrderByIF(dto.TypeCode != 0, d => d.StartTime, OrderByType.Desc)
                .OrderByIF(dto.IsHandled == false && !string.IsNullOrEmpty(dto.SortField), d => new { IsUrgent = d.IsUrgent }, OrderByType.Desc)
                //.OrderByIF(dto.IsHandled == false, d => new { d.Status })
                //.OrderByIF(dto.TypeCode == 0 && string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc)
                .OrderByIF(dto.TypeCode == 0 && string.IsNullOrEmpty(dto.SortField), d => d.IsUrgent, OrderByType.Desc)
                .OrderByIF(dto.TypeCode == 0 && string.IsNullOrEmpty(dto.SortField), d => d.CreationTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, d => d.CreationTime, OrderByType.Asc) //创建时间升序
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, d => d.CreationTime, OrderByType.Desc) //创建时间降序
                .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, d => d.StartTime, OrderByType.Asc) //受理时间升序
                .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, d => d.StartTime, OrderByType.Desc) //受理时间降序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, d => d.ExpiredTime, OrderByType.Asc) //期满时间升序
                .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, d => d.ExpiredTime, OrderByType.Desc) //期满时间降序
            ;
        return query;
    }

    public ISugarQueryable<Order> QueryWaited(QueryOrderWaitedDto dto)
    {
        var query = _orderRepository.Queryable()
            .Includes(d => d.WorkflowSteps.Where(step =>
                    ((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)) ||
                     (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) &&
                      _sessionContext.Roles.Contains(step.RoleId)
                      && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId)))
                .OrderByDescending(step => step.CreationTime)
                .Take(1)
                .ToList()
            ).Includes(d => d.OrderTags);
        var hasHandled = dto.IsHandled.HasValue && dto.IsHandled.Value;
        if (hasHandled)
            dto.QueryType = null;

        var isAdmin = _orderDomainService.IsCheckAdmin();
        if (!isAdmin)
        {
            if (hasHandled)
            {
                query.Where(d => d.WorkflowSteps
                    .Any(step =>
                        ((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)) ||
                         (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) &&
                          _sessionContext.Roles.Contains(step.RoleId)
                          && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId))
                        && step.Status == EWorkflowStepStatus.Handled));
            }
            else
            {
                query.Where(d => d.WorkflowSteps
                    .Any(step =>
                        ((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)) ||
                         (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) &&
                          _sessionContext.Roles.Contains(step.RoleId)
                          && !string.IsNullOrEmpty(step.HandlerOrgId) && step.HandlerOrgId == _sessionContext.RequiredOrgId))
                        && step.Status < EWorkflowStepStatus.Handled));
            }
        }

        if (dto.QueryType is 1 || dto.QueryType is 2)
        {
            query.WhereIF(dto.QueryType is 1, d => d.IsForwarded == false)
                .WhereIF(dto.QueryType is 2, d => d.IsForwarded == true)
                .Where(d => SqlFunc.Subqueryable<OrderSpecial>()
                    .Where(os => os.OrderId == d.Id && os.IsDeleted == false && os.SpecialType == ESpecialType.ReTransact)
                    .NotAny())
                ;
        }

        query.Where(d => d.Status != EOrderStatus.WaitForAccept &&
                         d.Status != EOrderStatus.BackToUnAccept &&
                         d.Status != EOrderStatus.SpecialToUnAccept &&
                         d.Status != EOrderStatus.HandOverToUnAccept)
            .WhereIF(dto.QueryType is 3,
                d => SqlFunc.Subqueryable<OrderSpecial>()
                    .Where(os => os.OrderId == d.Id && os.IsDeleted == false && os.SpecialType == ESpecialType.ReTransact).Any())
            .WhereIF(_appOptions.Value.IsZiGong,
                d => SqlFunc.Subqueryable<OrderDelay>()
                    .Where(od => od.OrderId == d.Id && od.IsDeleted == false && od.DelayState == EDelayState.Examining).NotAny())
            .WhereIF(_appOptions.Value.IsZiGong, d => SqlFunc.Subqueryable<OrderSendBackAudit>()
                .Where(osba => osba.OrderId == d.Id && osba.IsDeleted == false && osba.State == ESendBackAuditState.Apply)
                .NotAny())
            .Where(d => SqlFunc.Subqueryable<OrderSpecial>().Where(s => s.OrderId == d.Id && s.State == 0 && s.IsDeleted == false).NotAny())
            .WhereIF(dto.IsProvince.HasValue, d => d.IsProvince == dto.IsProvince)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.StartsWith(dto.Keyword))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No == dto.No)
            .WhereIF(!string.IsNullOrEmpty(dto.AreaCode), d => d.AreaCode == dto.AreaCode)
            .WhereIF(dto.IsCounterSign.HasValue && dto.IsCounterSign == true, d => d.CounterSignType.HasValue)
            .WhereIF(dto.IsCounterSign.HasValue && dto.IsCounterSign == false, d => d.CounterSignType == null)
            .WhereIF(dto.ExpiredOrAlmostOverdue.HasValue && dto.ExpiredOrAlmostOverdue == true,
                d => (d.ExpiredTime < DateTime.Now && d.Status < EOrderStatus.Filed) ||
                     (d.ExpiredTime < d.ActualHandleTime && d.Status >= EOrderStatus.Filed)) //超期 未办
            .WhereIF(dto.ExpiredOrAlmostOverdue.HasValue && dto.ExpiredOrAlmostOverdue == false,
                d => d.NearlyExpiredTime < DateTime.Now && d.ExpiredTime > DateTime.Now) //即将超期 未办
            .Where(d => d.Source < ESource.MLSQ || d.Source > ESource.WZSC)
            .Where(d => d.Status != EOrderStatus.BackToProvince)
            //.WhereIF(!hasHandled, d => d.Status < EOrderStatus.Filed)
            .WhereIF(!hasHandled || _appOptions.Value.IsYiBin, d => d.Status < EOrderStatus.Filed)
            //.Where(d => SqlFunc.Subqueryable<OrderSpecial>().Where(os => os.OrderId == d.Id).NotAny())
            //.Where(d => d.OrderSpecials.Any() == false || d.OrderSpecials.Any(s => s.State > 0))
            .WhereIF(dto.StartTime.HasValue, d => d.StartTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, d => d.StartTime <= dto.EndTime)
            .WhereIF(dto.IsUrgent.HasValue, d => d.IsUrgent == dto.IsUrgent!.Value)
            .WhereIF(dto.Status.HasValue, d => d.Status == dto.Status) //工单状态
            .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepCode), d => d.CurrentStepCode == dto.CurrentStepCode) //当前办理节点
            .WhereIF(!string.IsNullOrEmpty(dto.OrderTagCode), d => d.OrderTags.Any(ot => ot.DicDataValue == dto.OrderTagCode)) //工单标签
                                                                                                                               //.OrderByDescending(d => d.IsUrgent)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.IsUrgent, OrderByType.Desc)
            .OrderByIF(string.IsNullOrEmpty(dto.SortField), d => d.StartTime, OrderByType.Desc)
            .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, d => d.CreationTime, OrderByType.Asc) //创建时间升序
            .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, d => d.CreationTime, OrderByType.Desc) //创建时间降序
            .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, d => d.StartTime, OrderByType.Asc) //受理时间升序
            .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, d => d.StartTime, OrderByType.Desc) //受理时间降序
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, d => d.ExpiredTime, OrderByType.Asc) //期满时间升序
            .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, d => d.ExpiredTime, OrderByType.Desc) //期满时间降序
            .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 0 }, d => d.CurrentStepAcceptTime, OrderByType.Asc) //接办时间升序
            .OrderByIF(dto is { SortField: "currentStepAcceptTime", SortRule: 1 }, d => d.CurrentStepAcceptTime, OrderByType.Desc) //接办时间降序
            ;

        return query;
    }

    /// <summary>
    /// 受理前十
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="isExport"></param>
    /// <returns></returns>
    public async Task<(List<SystemDicData> acceptTypes, object items, DataTable data)> AcceptTypeTop10List(ReportPagedRequest dto, bool isExport)
    {
        var dicList = _systemDicDataRepository.Queryable().Where(x => x.DicTypeCode == "AcceptType").OrderBy(x => x.Sort).MergeTable();
        var IsCenter = _sessionContext.OrgIsCenter;

        var hotspotList = _hotspotRepository.Queryable().Where(x => SqlFunc.Length(x.Id) == 2)
            .Select(x => new
            {
                HotspotId = x.Id,
                HotspotName = x.HotSpotFullName,
            }).MergeTable();

        var orderList = _orderRepository.Queryable()
            .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
            .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
            .WhereIF(IsCenter == false, x => x.ActualHandleOrgCode.StartsWith(_sessionContext.RequiredOrgId))
            .Select(x => new
            {
                HotspotId = x.HotspotId.Substring(0, 2),
                AcceptTypeCode = x.AcceptTypeCode,
            }).MergeTable();

        var hotListAndOrder = hotspotList.LeftJoin(orderList, (it, o) => it.HotspotId == o.HotspotId)
            .GroupBy((it, o) => new
            {
                it.HotspotId,
                it.HotspotName,
                AcceptTypeCode = o.AcceptTypeCode,
            })
            .OrderBy((it, o) => it.HotspotId)
            .Select((it, o) => new
            {
                HotspotId = it.HotspotId,
                HotspotName = it.HotspotName,
                AcceptTypeCode = o.AcceptTypeCode,
                Count = SqlFunc.AggregateCount(it.HotspotId)
            }).MergeTable();

        var returnList = await dicList.LeftJoin(hotListAndOrder, (pp, dd) => pp.DicDataValue == dd.AcceptTypeCode)
            .GroupBy((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AcceptTypeCode = pp.DicDataValue,
                AcceptType = pp.DicDataName,
            })
            .OrderBy((pp, dd) => dd.HotspotId)
            .Select((pp, dd) => new
            {
                HotspotId = dd.HotspotId,
                HotspotName = dd.HotspotName,
                AcceptTypeCode = pp.DicDataValue,
                AcceptType = pp.DicDataName,
                Count = SqlFunc.AggregateSum(dd.Count)
            }).ToPivotTableAsync(q => q.AcceptType, q => new { q.HotspotName }, q => q.Sum(x => x.Count));
        DataColumn totalColumn = new DataColumn("有效受理量", typeof(int));
        returnList.Columns.Add(totalColumn);

        returnList.Columns["HotspotName"].ColumnName = "省一级热点名称";
        var titleList = await _systemDicDataRepository.Queryable().Where(x => x.DicTypeCode == "AcceptType").OrderBy(x => x.Sort).ToListAsync();
        for (int z = 0; z < returnList.Rows.Count; z++)
        {
            if (string.IsNullOrEmpty(returnList.Rows[z]["省一级热点名称"].ToString()))
            {
                returnList.Rows.Remove(returnList.Rows[z]);
            }
            else
            {
                int num = 0;
                var colTotal = returnList.Columns.Count - 1;
                for (int i = 1; i < colTotal; i++)
                {
                    num += int.Parse(returnList.Rows[z][i].ToString());
                }

                returnList.Rows[z]["有效受理量"] = num;
            }
        }

        returnList.Columns["有效受理量"].SetOrdinal(1);
        DataTable list = new DataTable();
        if (returnList.Rows.Count > 0)
            list = returnList.Select("", "有效受理量 DESC").Take(10).CopyToDataTable();
        if (isExport)
        {
            return (new List<SystemDicData>(), null, list);
        }

        var listDy = ToDynamicList(list);
        return (titleList, listDy, list);
    }

    public static List<dynamic> ToDynamicList(DataTable dataTable)
    {
        var list = new List<dynamic>();

        foreach (DataRow row in dataTable.Rows)
        {
            dynamic expando = new ExpandoObject();
            var expandoDic = (IDictionary<string, object>)expando;

            foreach (DataColumn column in dataTable.Columns)
            {
                expandoDic.Add(column.ColumnName, row[column]);
            }

            list.Add(expando);
        }

        return list;
    }

    #endregion

    /// <summary>
    /// 工单热词分析
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderTsDetailsDto> QueryOrderTsDetailsList(PagedKeywordRequest dto)
    {
        var query = _orderTsDetailsRepository.Queryable()
            .Where(p => p.CreationTime >= dto.StartTime && p.CreationTime <= dto.EndTime)
            .GroupBy(p => p.Terms)
            .Select(p => new OrderTsDetailsDto
            {
                Name = p.Terms,
                CountNum = SqlFunc.AggregateCount(p.Terms),
            })
            .MergeTable()
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), p => p.Name.Contains(dto.Keyword))
            .OrderByIF(dto is { SortField: "countNum", SortRule: 0 }, p => p.CountNum, OrderByType.Asc)
            .OrderByIF(dto is { SortField: "countNum", SortRule: 1 }, p => p.CountNum, OrderByType.Desc);

        return query;
    }

    /// <summary>
    /// 知识库引用
    /// </summary>
    /// <param name="orderId"></param>
    /// <param name="title"></param>
    /// <param name="no"></param>
    /// <param name="knowledgeQuote"></param>
    /// <returns></returns>
    public async Task AddKnowledgeQuote(string orderId, string title, string no, List<Kv> knowledgeQuote, CancellationToken cancellationToken)
    {
        await _knowledgeQuoteRepository.RemoveAsync(p => p.OrderId == orderId, false, cancellationToken);
        if (knowledgeQuote != null && knowledgeQuote.Count > 0)
        {
            List<KnowledgeQuote> list = [];
            foreach (var item in knowledgeQuote)
            {
                list.Add(new KnowledgeQuote
                {
                    KnowledgeId = item.Key,
                    KnowledgeTitle = item.Value,
                    OrderId = orderId,
                    Title = title,
                    No = no
                });
            }

            if (list != null && list.Count > 0)
                await _knowledgeQuoteRepository.AddRangeAsync(list, cancellationToken);
        }
    }

    /// <summary>
    /// 知识库引用
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderTsDetailsDto> QueryKnowledgeQuoteList(PagedKeywordRequest dto)
    {
        var query = _knowledgeQuoteRepository.Queryable()
            .LeftJoin<Hotline.KnowledgeBase.Knowledge>((kq, kn) => kq.KnowledgeId == kn.Id)
            .Where((kq, kn) => kq.CreationTime >= dto.StartTime && kq.CreationTime <= dto.EndTime && kn.Id != null)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), (kq, kn) => kn.Title.Contains(dto.Keyword))
            .GroupBy((kq, kn) => new { kn.Id, kn.Title })
            .Select((kq, kn) => new OrderTsDetailsDto
            {
                Id = kn.Id,
                Name = kn.Title,
                CountNum = SqlFunc.AggregateCount(kn.Id),
            }).MergeTable()
            .OrderByIF(dto is { SortField: "countNum", SortRule: 0 }, p => p.CountNum, OrderByType.Asc)
            .OrderByIF(dto is { SortField: "countNum", SortRule: 1 }, p => p.CountNum, OrderByType.Desc);

        return query;
    }


    /// <summary>
    /// 超期退回统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<ExtendedSendBackVo> ExtendedSendBackStatistics(PagedKeywordRequest dto)
    {
        var query = _orderSendBackAuditRepository.Queryable()
            .Where(x => x.ApplyOrgId.Length == 6 && x.CreationTime > x.OrderExpiredTime)
            .WhereIF(!_sessionContext.OrgIsCenter, x => x.ApplyOrgId == _sessionContext.OrgId)
            .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
            .GroupBy(x => new { x.ApplyOrgId, x.ApplyOrgName })
            .Select(x => new ExtendedSendBackVo()
            {
                OrgId = x.ApplyOrgId,
                OrgName = x.ApplyOrgName,
                TotalNum = SqlFunc.AggregateSum(1),
                PassNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.State == ESendBackAuditState.End, 1, 0)),
                NoPassNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.State == ESendBackAuditState.Refuse, 1, 0)),
                AuditNum = SqlFunc.AggregateSum(SqlFunc.IIF(x.State == ESendBackAuditState.Apply, 1, 0))
            });
        return query;
    }


    /// <summary>
    /// 超期退回明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderSendBackAudit> ExtendedSendBackDetail(ExtendedSendBackRequest dto)
    {
        var query = _orderSendBackAuditRepository.Queryable()
                .Includes(x => x.Order)
                .Where(x => x.ApplyOrgId.Length == 6 && x.CreationTime > x.OrderExpiredTime)
                .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .WhereIF(!_sessionContext.OrgIsCenter, x => x.ApplyOrgId == _sessionContext.RequiredOrgId)
                .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.Order.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Order.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.OrgId), x => x.ApplyOrgId == dto.OrgId)
                .WhereIF(dto.Type is ExtendedSendBackType.PassNum, x => x.State == ESendBackAuditState.End)
                .WhereIF(dto.Type is ExtendedSendBackType.NoPassNum, x => x.State == ESendBackAuditState.Refuse)
                .WhereIF(dto.Type is ExtendedSendBackType.AuditNum, x => x.State == ESendBackAuditState.Apply)
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.Order.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.Order.SourceChannelCode == dto.Channel) //来源渠道
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    x => x.Order.HotspotSpliceName != null && x.Order.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .WhereIF(dto.CreationTimeStart.HasValue, x => x.Order.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, x => x.Order.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(!string.IsNullOrEmpty(dto.ApplyOrgName), x => x.ApplyOrgName == dto.ApplyOrgName!) //申请部门
                .WhereIF(!string.IsNullOrEmpty(dto.ApplyUserName), x => x.CreatorName == dto.ApplyUserName!) //申请人
                .WhereIF(dto.State.HasValue, x => x.State == dto.State) //退回审批状态
                .WhereIF(!string.IsNullOrEmpty(dto.AuditUser), x => x.AuditUser == dto.AuditUser!) //审批人
                .WhereIF(dto.AuditTimeStart.HasValue && dto.AuditTimeEnd.HasValue,
                    x => x.AuditTime >= dto.AuditTimeStart && x.AuditTime <= dto.AuditTimeEnd) // 审批时间
                .WhereIF(!string.IsNullOrEmpty(dto.AuditContent), x => x.AuditContent.Contains(dto.AuditContent!)) //审批意见
                .OrderByIF(string.IsNullOrEmpty(dto.SortField), x => x.CreationTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "order.startTime", SortRule: 0 }, x => x.Order.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "order.startTime", SortRule: 1 }, x => x.Order.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, x => x.CreationTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, x => x.CreationTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "auditTime", SortRule: 0 }, x => x.AuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "auditTime", SortRule: 1 }, x => x.AuditTime, OrderByType.Desc)
            ;
        return query;
    }


    /// <summary>
    /// 延期列表
    /// </summary>
    /// <returns></returns>
    public ISugarQueryable<OrderDelay> DelayList(DelayListDto dto)
    {
        var isAdmin = _orderDomainService.IsCheckAdmin();
        var query = _orderDelayRepository.Queryable();
        if (!isAdmin && _appOptions.Value.IsZiGong == false)
        {
            query.Where(d => SqlFunc.Subqueryable<WorkflowTrace>()
                .Where(step => step.ExternalId == d.Id &&
                               ((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)) ||
                                (step.FlowAssignType == EFlowAssignType.OrgAndRole && !string.IsNullOrEmpty(step.RoleId) &&
                                 _sessionContext.Roles.Contains(step.RoleId) && !string.IsNullOrEmpty(step.HandlerOrgId) &&
                                 step.HandlerOrgId == _sessionContext.RequiredOrgId)
                               ))
                .Any());
            //if (!_sessionContext.OrgIsCenter)
            //{
            //    query.Where(d => d.AutomaticDelayNum == 0 || d.AutomaticDelayNum == null);
            //}
        }

        return query
                .Includes(d => d.Order)
                .Includes(d => d.Workflow)
                //如果查询全部
                //1.1、热线中心用户看系统中所有已申请延期的工单（需排除取消延期的工单）和自动延期的工单
                //1.2、部门用户看部门及其下级部门已申请延期的工单（需排除取消延期的工单）和部门办理中时自动延期的工单
                // .WhereIF(dto.DataScope is 0, d => (d.AutomaticDelayNum == 0 || d.AutomaticDelayNum == null) && d.DelayState != EDelayState.Withdraw)
                .WhereIF(dto.DataScope is 0, d => d.DelayState != EDelayState.Withdraw)
                .WhereIF(dto.DataScope is 0 && !_sessionContext.OrgIsCenter, d => d.CreatorOrgId.StartsWith(_sessionContext.RequiredOrgId))
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Order.Title.Contains(dto.Keyword!) || d.Order.No.Contains(dto.Keyword!))
                .WhereIF(dto.IsApply == true, d => d.DelayState != EDelayState.Examining)
                .WhereIF(dto.IsApply == false, d => d.DelayState == EDelayState.Examining)
                .WhereIF(dto.DelayState != null, d => d.DelayState == dto.DelayState)
                //延期列表页面数据范围快捷查询条件选中“我的“时需排除取消延期的工单
                .WhereIF(dto.DataScope is 1, d => d.CreatorId == _sessionContext.RequiredUserId && d.DelayState != EDelayState.Withdraw)
                .WhereIF(dto.QueryDelayState is EQueryDelayState.Examining, d => d.DelayState == EDelayState.Examining)
                .WhereIF(dto.QueryDelayState is EQueryDelayState.Pass, d => d.DelayState == EDelayState.Pass)
                .WhereIF(dto.QueryDelayState is EQueryDelayState.NoPass, d => d.DelayState == EDelayState.NoPass)
                .WhereIF(!string.IsNullOrEmpty(dto.CurrentStepName),
                    d => !SqlFunc.IsNullOrEmpty(d.WorkflowId) && d.Workflow.ActualHandleStepName == dto.CurrentStepName) //当前节点
                .WhereIF(!string.IsNullOrEmpty(dto.ActualHandlerName),
                    d => !SqlFunc.IsNullOrEmpty(d.WorkflowId) && d.Workflow.ActualHandlerName == dto.ActualHandlerName) // 审批人
                .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.Order.OrgLevelOneName == dto.OrgLevelOneName) //一级部门
                .WhereIF(dto.StartCreationTime.HasValue && dto.EndCreationTime.HasValue,
                    d => d.CreationTime >= dto.StartCreationTime && d.CreationTime <= dto.EndCreationTime) // 申请时间
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.Order.SourceChannelCode == dto.Channel)//来源渠道
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot))//热点名称
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.Order.ExpiredTime >= dto.ExpiredTimeStart) //期满时间开始
                .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.Order.ExpiredTime <= dto.ExpiredTimeEnd) //期满时间结束
                .WhereIF(!string.IsNullOrEmpty(dto.DelayApplyName), d => d.EmployeeName.Contains(dto.DelayApplyName))//申请人
                .WhereIF(!string.IsNullOrEmpty(dto.DelayApplyOrgName), d => d.ApplyOrgName.Contains(dto.DelayApplyOrgName))//申请部门
                .WhereIF(dto.IsAutomaticDelay.HasValue && dto.IsAutomaticDelay == true, d => d.AutomaticDelayNum != null && d.AutomaticDelayNum > 0)//自动延期
                .WhereIF(dto.IsAutomaticDelay.HasValue && dto.IsAutomaticDelay == false, d => d.AutomaticDelayNum == null || d.AutomaticDelayNum == 0)//非自动延期
                .OrderByDescending(d => d.ApplyDelayTime)
            ;
    }

    /// <summary>
    /// 延期待审批
    /// </summary>
    /// <returns></returns>
    public ISugarQueryable<OrderDelay> WaitDelayList(DelayListDto dto)
    {
        var isAdmin = _orderDomainService.IsCheckAdmin();
        var isHandled = dto.IsApply.HasValue && dto.IsApply.Value;
        var query = _orderDelayRepository
                .Queryable(hasHandled: isHandled, isAdmin: isAdmin)
                .Includes(d => d.Order)
                .Includes(d => d.Workflow)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Order.Title.Contains(dto.Keyword!) || d.No.Contains(dto.Keyword!))
                .WhereIF(dto.IsApply == false, d => d.DelayState == EDelayState.Examining)
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Order.No.Contains(dto.No))                                   //工单编号
                .WhereIF(dto.IsProvince.HasValue && dto.IsProvince == true, d => d.Order.IsProvince == true)      //是否省工单
                .WhereIF(dto.IsProvince.HasValue && dto.IsProvince == false, d => d.Order.IsProvince == false)
                .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title))                          //工单标题
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), d => d.Order.SourceChannelCode == dto.Channel)                 //来源渠道
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart)                //受理时间Start
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd)                    //受理时间End
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptorName), d => d.Order.AcceptorName == dto.AcceptorName!)           //受理人
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot)) //热点
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptTypeCode), d => d.Order.AcceptTypeCode == dto.AcceptTypeCode)      //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.OrgLevelOneName), d => d.Order.OrgLevelOneName.Contains(dto.OrgLevelOneName)) //一级部门
                .WhereIF(!string.IsNullOrEmpty(dto.CurrentHandleOrgName), d => d.Order.CurrentHandleOrgName.Contains(dto.CurrentHandleOrgName)) //接办部门
                .WhereIF(dto.CurrentHandleTimeStart.HasValue, d => d.Order.CurrentHandleTime >= dto.CurrentHandleTimeStart) //接办时间Start
                .WhereIF(dto.CurrentHandleTimeEnd.HasValue, d => d.Order.CurrentHandleTime <= dto.CurrentHandleTimeEnd)     //接办时间End
                .WhereIF(dto.ApplyTimeStart.HasValue, d => d.CreationTime >= dto.ApplyTimeStart)                            //延期申请时间Start
                .WhereIF(dto.ApplyTimeEnd.HasValue, d => d.CreationTime <= dto.ApplyTimeEnd)                                //延期申请时间End
                .WhereIF(!string.IsNullOrEmpty(dto.ApplyName), d => d.CreatorName.Contains(dto.ApplyName))                  //延期申请人
                .WhereIF(!string.IsNullOrEmpty(dto.ApplyOrgName), d => d.CreatorOrgName.Contains(dto.ApplyOrgName))         //延期申请部门
                .WhereIF(dto.DelayNum.HasValue, d => d.DelayNum == dto.DelayNum)                                            //延期申请时限
                .WhereIF(dto.DelayUnit.HasValue, d => d.DelayUnit == dto.DelayUnit)                                         //延期申请单位
                .WhereIF(!string.IsNullOrEmpty(dto.DelayReason), d => d.DelayReason.Contains(dto.DelayReason))              //申请理由
                .WhereIF(dto.BeforeDelayStart.HasValue, d => d.BeforeDelay >= dto.BeforeDelayStart)                         //申请前期满时间Start
                .WhereIF(dto.BeforeDelayEnd.HasValue, d => d.BeforeDelay <= dto.BeforeDelayEnd)                             //申请前期满时间End
                .OrderByDescending(d => d.ApplyDelayTime)
            ;

        return query;
    }

    #region 退回重写

    public async Task OrderPrevious(OrderSendBackAudit sendBack, Order order, CancellationToken cancellationToken)
    {
        var handleMode = EHandleMode.Previous;
        WorkflowStep? currentStep, prevStep, newStep, startStep = null;
        EFlowDirection flowDirection;
        var userId = sendBack.WorkflowUserId;
        var orgId = sendBack.WorkflowOrgId;
        var roles = sendBack.WorkflowRoleIds.ToArray();
        do
        {
            (_, currentStep, _, prevStep, newStep, flowDirection) =
                await _workflowApplication.PreviousAsync(sendBack.SendBackData,
                    userId, orgId, roles, handleMode,
                    (workflow1, currentStep1, prevStepDefine, prevStep1, newStep) =>
                    {
                        var stepAssignInfo = GetOrderPreviousAssignInfoAsync(workflow1, prevStepDefine, prevStep1, cancellationToken).Result;//todo 优化异步
                        if (stepAssignInfo is null) return;
                        var validator = new StepAssignInfoValidator();
                        validator.Validate(stepAssignInfo);
                        newStep.Assign(stepAssignInfo);
                    },
                    cancellationToken);

            if (sendBack.AssignStepId != prevStep.Id) handleMode = EHandleMode.PreviousNoDisplay;
            startStep ??= currentStep;
            userId = prevStep.HandlerId;
            orgId = prevStep.HandlerOrgId;
            roles = [prevStep.RoleId];
        } while (!string.IsNullOrEmpty(sendBack.AssignStepId) &&
                 sendBack.AssignStepId != prevStep.Id &&
                 prevStep.StepType is not EStepType.Start);

        sendBack.ApplyOrgId = currentStep.AcceptorOrgId;
        sendBack.ApplyOrgName = currentStep!.AcceptorOrgName;
        sendBack.SendBackOrgId = prevStep.HandlerOrgId;
        sendBack.SendBackOrgName = prevStep.HandlerOrgName;
        sendBack.SendBackStepName = prevStep.Name;
        sendBack.WorkflowStepSendBackCrTime = currentStep.CreationTime;
        sendBack.TraceId = currentStep.Id;
        //记录退回后最新的流程节点
        if (newStep != null && !string.IsNullOrEmpty(newStep.Id))
            sendBack.NewCurrentStepId = newStep.Id;

        var processType = flowDirection == EFlowDirection.OrgToCenter || flowDirection == EFlowDirection.CenterToCenter
            ? EProcessType.Zhiban
            : EProcessType.Jiaoban;
        if (currentStep.AcceptorOrgId != OrgSeedData.CenterId && prevStep.BusinessType == EBusinessType.Send)
            order.SendBackNum = order.SendBackNum.HasValue ? order.SendBackNum.Value + 1 : 1;

        if (prevStep.BusinessType == EBusinessType.Send)
        {
            await _orderRepository.Updateable().SetColumns(o => new Order()
            {
                CenterToOrgHandlerId = newStep.HandlerId,
                CenterToOrgHandlerName = newStep.HandlerName,
                ProcessType = processType,
                SendBackNum = order.SendBackNum
            })
                .Where(o => o.Id == order.Id).ExecuteCommandAsync(cancellationToken);
        }
        else
        {
            await _orderRepository.Updateable().SetColumns(o => new Order() { ProcessType = processType, SendBackNum = order.SendBackNum })
                .Where(o => o.Id == order.Id).ExecuteCommandAsync(cancellationToken);
        }

        if (_appOptions.Value.IsYiBin && order.IsProvince && sendBack.ApplyOrgId.Length == 6 && sendBack.SendBackOrgId == OrgSeedData.CenterId)
        {
            if (newStep.FlowAssignType == EFlowAssignType.User)
            {
                await _circularRecordDomainService.OrderSendBackCircularMessage(newStep.HandlerId, newStep.HandlerName, order, cancellationToken);
            }
            else if (newStep.FlowAssignType == EFlowAssignType.Role && !string.IsNullOrEmpty(newStep.RoleId))
            {
                var role = await _roleRepository.Queryable().Includes(x => x.Accounts).FirstAsync(x => x.Name == newStep.RoleId, cancellationToken);
                foreach (var user in role.Accounts)
                {
                    await _circularRecordDomainService.OrderSendBackCircularMessage(user.Id, user.Name, order, cancellationToken);
                }
            }
        }
    }

    /// <summary>
    /// 依据当前待办节点获取任意一个合法办理人
    /// </summary>
    public async Task<User> GetHandlerRandomAsync(WorkflowStep step, CancellationToken cancellationToken)
    {
        User user;
        switch (step.BusinessType)
        {
            case EBusinessType.Seat:
                var roleSeat = _systemSettingCacheManager.GetSetting(SettingConstants.RoleZuoXi)?.SettingValue.FirstOrDefault();
                if (string.IsNullOrEmpty(roleSeat))
                    throw new UserFriendlyException($"未配置坐席角色, {SettingConstants.RoleZuoXi}", "未配置坐席角色");
                user = await _userRepository.Queryable()
                    .Where(d => d.Roles.Any(x => x.Name == roleSeat))
                    .FirstAsync(cancellationToken);
                if (user is null)
                    throw UserFriendlyException.SameMessage("坐席角色未设置用户");
                break;
            case EBusinessType.Send:
                var roleSend = _systemSettingCacheManager.GetSetting(SettingConstants.RolePaiDan)?.SettingValue.FirstOrDefault();
                if (string.IsNullOrEmpty(roleSend))
                    throw new UserFriendlyException($"未配置派单角色, {SettingConstants.RolePaiDan}", "未配置派单角色");
                user = await _userRepository.Queryable()
                    .Where(d => d.Roles.Any(x => x.Name == roleSend))
                    .FirstAsync(cancellationToken);
                if (user is null)
                    throw UserFriendlyException.SameMessage("派单角色未设置用户");
                break;
            case EBusinessType.CenterMonitor:
                var roleCenterMonitor = _systemSettingCacheManager.GetSetting(SettingConstants.SeatsMonitor)?.SettingValue.FirstOrDefault();
                if (string.IsNullOrEmpty(roleCenterMonitor))
                    throw new UserFriendlyException($"未配置中心班长角色, {SettingConstants.SeatsMonitor}", "未配置中心班长角色");
                user = await _userRepository.Queryable()
                    .Where(d => d.Roles.Any(x => x.Name == roleCenterMonitor))
                    .FirstAsync(cancellationToken);
                if (user is null)
                    throw UserFriendlyException.SameMessage("中心班长角色未设置用户");
                break;
            case EBusinessType.CenterLeader:
                var roleCenterLeader = _systemSettingCacheManager.GetSetting(SettingConstants.RoleCenterLeader)?.SettingValue.FirstOrDefault();
                if (string.IsNullOrEmpty(roleCenterLeader))
                    throw new UserFriendlyException($"未配置中心领导角色, {SettingConstants.RoleCenterLeader}", "未配置中心领导角色");
                user = await _userRepository.Queryable()
                    .Where(d => d.Roles.Any(x => x.Name == roleCenterLeader))
                    .FirstAsync(cancellationToken);
                if (user is null)
                    throw UserFriendlyException.SameMessage("中心领导角色未设置用户");
                break;
            case EBusinessType.Department:
                var roleJingBanRen = _systemSettingCacheManager.GetSetting(SettingConstants.RoleJingBanRen)?.SettingValue.FirstOrDefault();
                if (string.IsNullOrEmpty(roleJingBanRen))
                    throw new UserFriendlyException($"未配置部门经办人角色, {SettingConstants.RoleJingBanRen}", "未配置部门经办人角色");
                user = await _userRepository.Queryable()
                    .Where(d => d.OrgId == step.HandlerOrgId && d.Roles.Any(x => x.Name == roleJingBanRen))
                    .FirstAsync(cancellationToken);
                if (user is null)
                    throw new UserFriendlyException($"该部门经办人角色未设置用户，部门：{step.HandlerOrgId}, 角色：{SettingConstants.RoleJingBanRen}");
                break;
            case EBusinessType.DepartmentLeader:
                var roleBuMenLingDao = _systemSettingCacheManager.GetSetting(SettingConstants.RoleLingDao)?.SettingValue.FirstOrDefault();
                if (string.IsNullOrEmpty(roleBuMenLingDao))
                    throw new UserFriendlyException($"未配置部门领导角色, {SettingConstants.RoleJingBanRen}", "未配置部门领导角色");
                user = await _userRepository.Queryable()
                    .Where(d => d.OrgId == step.HandlerOrgId && d.Roles.Any(x => x.Name == roleBuMenLingDao))
                    .FirstAsync(cancellationToken);
                if (user is null)
                    throw new UserFriendlyException($"该部门领导角色未设置用户，部门：{step.HandlerOrgId}, 角色：{SettingConstants.RoleJingBanRen}");
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(GetHandlerRandomAsync));
        }

        return user;
    }

    #endregion

    /// <summary>
    /// 部门退回中心统计
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>

    public ISugarQueryable<OrgSendBackAuditListVo> OrgSendBackAuditList(OrgSendBackAuditListDto dto)
    {
        var query = _orderSendBackAuditRepository.Queryable()
            .Where(x => x.State == ESendBackAuditState.End && x.ApplyOrgId != OrgSeedData.CenterId && x.SendBackOrgId == OrgSeedData.CenterId)
            .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.AuditTime >= dto.StartTime && x.AuditTime <= dto.EndTime)
            .WhereIF(!string.IsNullOrEmpty(dto.OrgName), x => x.ApplyOrgName == dto.OrgName)
            .GroupBy(x => new { x.ApplyOrgId, x.ApplyOrgName })
            .Select(x => new OrgSendBackAuditListVo
            {
                OrgId = x.ApplyOrgId,
                OrgName = x.ApplyOrgName,
                Num = SqlFunc.AggregateCount(1)
            });
        return query;
    }

    public ISugarQueryable<OrderSendBackAudit> OrgSendBackAuditDetail(OrgSendBackAuditListDto dto)
    {
        var query = _orderSendBackAuditRepository.Queryable()
                .Includes(x => x.Order)
                .Where(x => x.State == ESendBackAuditState.End && x.ApplyOrgId != OrgSeedData.CenterId && x.SendBackOrgId == OrgSeedData.CenterId)
                .WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue, x => x.AuditTime >= dto.StartTime && x.AuditTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.OrgId), x => x.ApplyOrgId == dto.OrgId)
                .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.Order.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Order.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.OrgId), x => x.ApplyOrgId == dto.OrgId)
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.Order.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.Order.SourceChannelCode == dto.Channel) //来源渠道
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    x => x.Order.HotspotSpliceName != null && x.Order.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .WhereIF(dto.CreationTimeStart.HasValue, x => x.Order.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, x => x.Order.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(!string.IsNullOrEmpty(dto.ApplyOrgName), x => x.ApplyOrgName == dto.ApplyOrgName!) //申请部门
                .WhereIF(!string.IsNullOrEmpty(dto.ApplyUserName), x => x.CreatorName == dto.ApplyUserName!) //申请人
                .WhereIF(dto.State.HasValue, x => x.State == dto.State) //退回审批状态
                .WhereIF(!string.IsNullOrEmpty(dto.AuditUser), x => x.AuditUser == dto.AuditUser!) //审批人
                .WhereIF(dto.AuditTimeStart.HasValue && dto.AuditTimeEnd.HasValue,
                    x => x.AuditTime >= dto.AuditTimeStart && x.AuditTime <= dto.AuditTimeEnd) // 审批时间
                .WhereIF(!string.IsNullOrEmpty(dto.AuditContent), x => x.AuditContent.Contains(dto.AuditContent!)) //审批意见
                .OrderByIF(string.IsNullOrEmpty(dto.SortField), x => x.CreationTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "order.startTime", SortRule: 0 }, x => x.Order.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "order.startTime", SortRule: 1 }, x => x.Order.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 0 }, x => x.CreationTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "creationTime", SortRule: 1 }, x => x.CreationTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "auditTime", SortRule: 0 }, x => x.AuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "auditTime", SortRule: 1 }, x => x.AuditTime, OrderByType.Desc)
            ;
        return query;
    }


    #region 坐席退回统计表
    /// <summary>
    /// 坐席退回统计表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<SeatSendBackStatisticsVo> SeatSendBackStatistics(PagedKeywordRequest dto)
    {
        var setting = _systemSettingCacheManager.GetSetting(SettingConstants.RoleZuoXi);
        var roles = setting?.SettingValue.ToList();
        var seats = _userRepository.Queryable()
            .Includes(d => d.Organization)
            .Includes(d => d.Roles)
            .Where(d => d.Roles.Any(x => roles.Contains(x.Name)));
        var send = _workflowTraceRepository.Queryable()
            .LeftJoin<Order>((x, o) => x.ExternalId == o.Id)
            .Where((x, o) => x.HandlerOrgId != OrgSeedData.CenterId && (x.PrevStepName == "班长审批" || x.PrevStepName == "派单组") && o.CreationTime >= dto.StartTime && o.CreationTime <= dto.EndTime && x.CreationTime >= dto.StartTime)
            .GroupBy((x, o) => new { o.AcceptorId })
            .Select((x, o) => new SeatSendBackStatisticsVo { UserId = o.AcceptorId, SendOrderNum = SqlFunc.AggregateDistinctCount(x.ExternalId) });

        //  var sendBack = _workflowTraceRepository.Queryable()
        //.LeftJoin<Order>((x, o) => x.ExternalId == o.Id)
        //         .Where((x, o) => o.CreationTime >= dto.StartTime && o.CreationTime <= dto.EndTime && x.CreationTime >= dto.StartTime && x.BusinessType == EBusinessType.Seat && (x.PrevStepName == "班长审批" || x.PrevStepName == "派单组"))
        //.GroupBy((x, o) => new { o.AcceptorId})
        //.Select((x, o) => new { UserId = o.AcceptorId, SendOrderBackNum = SqlFunc.AggregateDistinctCount(x.ExternalId), SendOrderBackNumber = SqlFunc.AggregateCount(x.ExternalId) });
        var sendBack = _orderSendBackAuditRepository.Queryable()
            .LeftJoin<Order>((x, o) => x.OrderId == o.Id)
            .Where((x, o) => (x.SendBackStepName == "话务部") && o.CreationTime >= dto.StartTime && o.CreationTime <= dto.EndTime)
            .GroupBy((x, o) => new { o.AcceptorId })
            .Select((x, o) => new SeatSendBackStatisticsVo { UserId = o.AcceptorId, SendOrderBackNum = SqlFunc.AggregateDistinctCount(x.OrderId), SendOrderBackNumber = SqlFunc.AggregateCount(x.Id) });


        var filed = _orderRepository.Queryable()
            .Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime && x.Status >= EOrderStatus.Filed && x.FileOrgIsCenter == true && x.FileUserRole == EFileUserType.Seat)
            .GroupBy(x => x.AcceptorId)
            .Select(x => new SeatSendBackStatisticsVo { UserId = x.AcceptorId, CentreFileNum = SqlFunc.AggregateDistinctCount(x.Id) });

        var back = _orderSpecialRepository.Queryable()
             .LeftJoin<Order>((x, o) => x.OrderId == o.Id)
             .Where((x, o) => o.CreationTime >= dto.StartTime && o.CreationTime <= dto.EndTime && x.SpecialType == ESpecialType.SendBack && x.NextStepCode == "start")
             .GroupBy((x, o) => new { o.AcceptorId })
             .Select((x, o) => new SeatSendBackStatisticsVo { UserId = o.AcceptorId, CentreFileBackNum = SqlFunc.AggregateDistinctCount(x.OrderId), CentreFileBackNumber = SqlFunc.AggregateCount(x.OrderId) });

        var query = seats.LeftJoin(send, (s, sd) => s.Id == sd.UserId)
              .LeftJoin(sendBack, (s, sd, sb) => s.Id == sb.UserId)
              .LeftJoin(filed, (s, sd, sb, f) => s.Id == f.UserId)
              .LeftJoin(back, (s, sd, sb, f, b) => s.Id == b.UserId)
              .GroupBy((s, sd, sb, f, b) => new { s.Id, s.Name })
              .Select((s, sd, sb, f, b) => new SeatSendBackStatisticsVo
              {
                  UserId = s.Id,
                  UserName = s.Name,
                  SendOrderNum = SqlFunc.AggregateSum(sd.SendOrderNum),
                  SendOrderBackNum = SqlFunc.AggregateSum(sb.SendOrderBackNum),
                  SendOrderBackNumber = SqlFunc.AggregateSum(sb.SendOrderBackNumber),
                  CentreFileNum = SqlFunc.AggregateSum(f.CentreFileNum),
                  CentreFileBackNum = SqlFunc.AggregateSum(b.CentreFileBackNum),
                  CentreFileBackNumber = SqlFunc.AggregateSum(b.CentreFileBackNumber),
              });
        return query;
    }


    /// <summary>
    /// 坐席退回统计表明细
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public ISugarQueryable<OrderDto> SeatSendBackStatisticsDetail(SeatSendBackStatisticsDetail dto)
    {

        if (dto.StatisticsType == "sendOrderNum")
        {
            var query = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                 .WhereIF(!string.IsNullOrEmpty(dto.UserId), x => x.AcceptorId == dto.UserId)
                 .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.No.Contains(dto.No!))
                 .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Title.Contains(dto.Title!))
                 .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.AcceptTypeCode == dto.AcceptType) //受理类型
                 .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.SourceChannelCode == dto.Channel) //来源渠道
                  .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                     x => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                 .Where(x => SqlFunc.Subqueryable<WorkflowTrace>().Where(wt => wt.ExternalId == x.Id && wt.HandlerOrgId != OrgSeedData.CenterId && (wt.PrevStepName == "班长审批" || wt.PrevStepName == "派单组")).Any())
                 .Select(x => new OrderDto() { Id = x.Id.SelectAll() })
                 .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
                 .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
                 .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
                 .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
                 .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 0 }, x => x.SendBackAuditTime, OrderByType.Asc)
                 .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 1 }, x => x.SendBackAuditTime, OrderByType.Desc);
            return query;
        }
        else if (dto.StatisticsType == "sendOrderBackNum")
        {
            var query = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.UserId), x => x.AcceptorId == dto.UserId)
                .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.SourceChannelCode == dto.Channel) //来源渠道
                 .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    x => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .Where(x => SqlFunc.Subqueryable<OrderSendBackAudit>().Where(os => os.OrderId == x.Id && (os.SendBackStepName == "话务部")).Any())
                .Select(x => new OrderDto() { Id = x.Id.SelectAll() })
                .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 0 }, x => x.SendBackAuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 1 }, x => x.SendBackAuditTime, OrderByType.Desc);
            return query;
        }
        else if (dto.StatisticsType == "sendOrderBackNumber")
        {
            var query = _orderRepository.Queryable()
                .LeftJoin<OrderSendBackAudit>((x, os) => x.Id == os.OrderId && (os.SendBackStepName == "话务部"))
                .WhereIF(!string.IsNullOrEmpty(dto.No), (x, os) => x.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), (x, os) => x.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), (x, os) => x.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), (x, os) => x.SourceChannelCode == dto.Channel) //来源渠道
                 .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    (x, os) => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .Where((x, os) => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.UserId), (x, os) => x.AcceptorId == dto.UserId)
                .Select((x, os) => new OrderDto() { Id = x.Id.SelectAll(), SendBackOpinion = os.Content, SendBackAuditTime = os.AuditTime })
                .MergeTable()
                .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 0 }, x => x.SendBackAuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 1 }, x => x.SendBackAuditTime, OrderByType.Desc);
            return query;
        }
        else if (dto.StatisticsType == "centreFileNum")
        {
            var query = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime && x.FileUserRole == EFileUserType.Seat)
                .WhereIF(!string.IsNullOrEmpty(dto.UserId), x => x.AcceptorId == dto.UserId)
                .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.SourceChannelCode == dto.Channel) //来源渠道
                 .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    x => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .Where(x => x.Status >= EOrderStatus.Filed && x.FileOrgIsCenter == true).Select(x => new OrderDto() { Id = x.Id.SelectAll() })
                .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 0 }, x => x.SendBackAuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 1 }, x => x.SendBackAuditTime, OrderByType.Desc);
            return query;
        }
        else if (dto.StatisticsType == "centreFileBackNum")
        {
            var query = _orderRepository.Queryable().Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.UserId), x => x.AcceptorId == dto.UserId)
                .WhereIF(!string.IsNullOrEmpty(dto.No), x => x.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), x => x.SourceChannelCode == dto.Channel) //来源渠道
                 .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    x => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .Where(x => SqlFunc.Subqueryable<OrderSpecial>().Where(os => os.OrderId == x.Id && os.SpecialType == ESpecialType.SendBack && os.NextStepCode == "start").Any())
                .Select(x => new OrderDto() { Id = x.Id.SelectAll() })
                .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 0 }, x => x.SendBackAuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 1 }, x => x.SendBackAuditTime, OrderByType.Desc);
            return query;
        }
        else if (dto.StatisticsType == "centreFileBackNumber")
        {
            var query = _orderRepository.Queryable().LeftJoin<OrderSpecial>((x, os) => x.Id == os.OrderId && os.SpecialType == ESpecialType.SendBack && os.NextStepCode == "start")
                .WhereIF(!string.IsNullOrEmpty(dto.No), (x, os) => x.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), (x, os) => x.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), (x, os) => x.AcceptTypeCode == dto.AcceptType) //受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Channel), (x, os) => x.SourceChannelCode == dto.Channel) //来源渠道
                 .WhereIF(!string.IsNullOrEmpty(dto.Hotspot),
                    (x, os) => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot)) //热点分类
                .Where((x, os) => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.UserId), (x, os) => x.AcceptorId == dto.UserId)
                .Select((x, os) => new OrderDto() { Id = x.Id.SelectAll(), SendBackOpinion = os.Reason, SendBackAuditTime = os.CreationTime })
                .MergeTable()
                .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, x => x.StartTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, x => x.StartTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, x => x.FiledTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, x => x.FiledTime, OrderByType.Desc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 0 }, x => x.SendBackAuditTime, OrderByType.Asc)
                .OrderByIF(dto is { SortField: "sendBackAuditTime", SortRule: 1 }, x => x.SendBackAuditTime, OrderByType.Desc);
            return query;
        }
        return null;
    }


    #region 自动延期

    /// <summary>
    /// 自动延期记录写入
    /// </summary>
    /// <returns></returns>
    public async Task OrderDelayAutomatic()
    {

        var data = new List<OrderDelayAutomatic>();
        var automatic = await _orderRepository.Queryable()
           .Where(x => x.Status < EOrderStatus.Filed && x.ExpiredTime <= DateTime.Now.AddHours(1) && x.ExpiredTime >= DateTime.Now)
           .Where(x => SqlFunc.Subqueryable<OrderDelay>().Where(od => od.OrderId == x.Id && od.DelayState == EDelayState.Examining).NotAny())
           .Where(x => SqlFunc.Subqueryable<OrderDelayAutomatic>().Where(oda => oda.OrderId == x.Id && oda.Status == EOrderDelayAutomaticStatus.Pending && oda.Type == EOrderDelayAutomaticType.Automatic).NotAny())
           .Select(x => new OrderDelayAutomatic
           {
               OrderId = x.Id,
               WorkflowId = x.WorkflowId,
               Title = x.Title,
               No = x.No,
               ExpiredTime = x.ExpiredTime,
               CenterToOrgTime = x.CenterToOrgTime,
               AcceptTypeCode = x.AcceptTypeCode,
               Type = EOrderDelayAutomaticType.Automatic
           })
           .ToListAsync();
        if (automatic.Any())
        {
            data.AddRange(automatic);
        }
        var automaticSMS = await _orderRepository.Queryable()
            .Where(x => x.Status < EOrderStatus.Filed && x.ExpiredTime <= DateTime.Now.AddHours(2) && x.ExpiredTime > DateTime.Now.AddHours(1) && x.ExpiredTime >= DateTime.Now)
            .Where(x => SqlFunc.Subqueryable<OrderDelay>().Where(od => od.OrderId == x.Id && od.DelayState == EDelayState.Examining).NotAny())
            .Where(x => SqlFunc.Subqueryable<OrderDelayAutomatic>().Where(oda => oda.OrderId == x.Id && oda.Status == EOrderDelayAutomaticStatus.Pending && oda.Type == EOrderDelayAutomaticType.Sms).NotAny())
            .Select(x => new OrderDelayAutomatic
            {
                OrderId = x.Id,
                WorkflowId = x.WorkflowId,
                Title = x.Title,
                No = x.No,
                ExpiredTime = x.ExpiredTime,
                CenterToOrgTime = x.CenterToOrgTime,
                AcceptTypeCode = x.AcceptTypeCode,
                Type = EOrderDelayAutomaticType.Sms
            })
            .ToListAsync();
        if (automaticSMS.Any())
        {
            data.AddRange(automaticSMS);
        }
        if (data.Any())
        {
            await _orderDelayAutomaticRepository.AddRangeAsync(data);
        }
    }

    /// <summary>
    /// 自动延期处理
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task OrderDelayAutomaticHandle(EOrderDelayAutomaticType type)
    {
        var copy = new List<OrderDelayAutomatic>();
        var tasks = await _orderDelayAutomaticRepository.Queryable()
            .Where(x => x.Status == EOrderDelayAutomaticStatus.Pending && x.Type == type)
            .ToListAsync();
        foreach (var task in tasks)
        {
            task.Status = EOrderDelayAutomaticStatus.BeingProcessed;
            var row = await _orderDelayAutomaticRepository.Updateable(task).ExecuteCommandWithOptLockAsync();
            if (row > 0)
            {
                copy.Add(task);
            }
        }
        if (type == EOrderDelayAutomaticType.Sms)
        {
            if (copy.Any())
            {
                foreach (var item in copy)
                {
                    var workflow = await _workflowDomainService.GetWorkflowAsync(item.WorkflowId, withSteps: true);
                    var steps = workflow.Steps.Where(x => x.Status == EWorkflowStepStatus.WaitForAccept || x.Status == EWorkflowStepStatus.WaitForHandle).ToList();
                    if (steps.Any())
                    {
                        foreach (var step in steps)
                        {
                            var setting = step.HandlerOrgId == OrgSeedData.CenterId ? SettingConstants.AutomaticDelayCenterRoles : SettingConstants.AutomaticDelayDepartmentRoles;
                            var roleIds = _systemSettingCacheManager.GetSetting(setting)?.SettingValue;
                            if (step.HandlerOrgId == OrgSeedData.CenterId && string.IsNullOrEmpty(step.RoleId))
                            {
                                roleIds.Add(step.RoleId);
                            }
                            var userList = await _userRepository.Queryable().Where(x => x.OrgId == step.HandlerOrgId && x.Roles.Any(r => roleIds.Contains(r.Name))).ToListAsync();
                            foreach (var user in userList)
                            {
                                if (!string.IsNullOrEmpty(user.PhoneNo))
                                {
                                    //发送短信
                                    var messageDto = new Share.Dtos.Push.MessageDto
                                    {
                                        PushBusiness = EPushBusiness.AutomaticDelay,
                                        ExternalId = item.Id,
                                        OrderId = item.Id,
                                        PushPlatform = EPushPlatform.Sms,
                                        Remark = item.Title,
                                        Name = user.Name,
                                        TemplateCode = "1015",
                                        Params = new List<string>() { item.No },
                                        TelNumber = user.PhoneNo,
                                    };
                                    await _mediator.Publish(new PushMessageNotify(messageDto));
                                }
                            }
                        }
                    }
                    await _orderDelayAutomaticRepository.Updateable().SetColumns(x => x.Status == EOrderDelayAutomaticStatus.Processed).Where(x => x.Id == item.Id).ExecuteCommandAsync();
                }
            }
        }
        if (type == EOrderDelayAutomaticType.Automatic)
        {
            if (copy.Any())
            {
                foreach (var item in copy)
                {
                    var delayAny = await _orderDelayRepository.Queryable().Where(x => x.OrderId == item.OrderId && x.DelayState == EDelayState.Examining).AnyAsync();
                    if (!delayAny)
                    {
                        var delays = await _orderDelayRepository.Queryable().Where(x => x.OrderId == item.OrderId && x.AutomaticDelayNum > 0).ToListAsync();
                        var delay = new OrderDelay();
                        if (delays.Any())
                        {
                            delay = delays.First();
                            var startTime = DateTime.Now;
                            if (item.CenterToOrgTime.HasValue)
                            {
                                startTime = item.CenterToOrgTime.Value;
                            }
                            var beforeDelay = DateTime.Now;
                            if (!_appOptions.Value.IsYiBin)
                            {
                                beforeDelay = item.ExpiredTime.Value;
                            }
                            delay.AfterDelay = (await _expireTime
                                .CalcEndTime(beforeDelay, startTime, delay.DelayUnit, delay.DelayNum, item.AcceptTypeCode))?.EndTime; //todo
                            await _orderDelayRepository.Updateable().SetColumns(x => new OrderDelay() { AutomaticDelayNum = x.AutomaticDelayNum + 1, ApplyDelayTime = DateTime.Now, AfterDelay = delay.AfterDelay })
                                .Where(x => x.Id == delay.Id).ExecuteCommandAsync();
                        }
                        else
                        {
                            delay.OrderId = item.OrderId;
                            delay.EmployeeId = "";
                            delay.EmployeeName = "系统自动延期";
                            delay.ApplyOrgName = OrgSeedData.CenterName;
                            delay.ApplyOrgCode = OrgSeedData.CenterId;
                            delay.DelayApplyType = EDelayApplyType.LocalApply;
                            delay.BeforeDelay = item.ExpiredTime;
                            delay.DelayState = EDelayState.Pass;
                            delay.DelayReason = "系统自动延期";
                            delay.ApplyDelayTime = DateTime.Now;
                            delay.No = item.No;
                            delay.AutomaticDelayNum = 1;
                            delay.DelayNum = 1;
                            delay.DelayUnit = Share.Enums.Settings.ETimeType.WorkDay;
                            delay.IsProDelay = false;
                            delay.CreatorOrgId = OrgSeedData.CenterId;
                            delay.CreatorOrgName = OrgSeedData.CenterName;
                            delay.CreatorName = "系统自动延期";
                            var startTime = DateTime.Now;
                            if (item.CenterToOrgTime.HasValue)
                            {
                                startTime = item.CenterToOrgTime.Value;
                            }
                            if (delay.BeforeDelay != null)
                            {
                                delay.AfterDelay = (await _expireTime
                                    .CalcEndTime(delay.BeforeDelay.Value, startTime, delay.DelayUnit, delay.DelayNum, item.AcceptTypeCode))?.EndTime; //todo
                            }
                            await _orderDelayRepository.AddAsync(delay, false);
                        }
                        //处理工单延期
                        await DelayOrderExpiredTimeAsync(item.OrderId, delay.DelayNum, delay.DelayUnit, delay.IsProDelay, default);
                    }
                    await _orderDelayAutomaticRepository.Updateable().SetColumns(x => x.Status == EOrderDelayAutomaticStatus.Processed).Where(x => x.Id == item.Id).ExecuteCommandAsync();
                }
            }
        }
    }

    /// <summary>
    /// 批量发送短信
    /// </summary>
    /// <param name="dto"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task SendLeaderSMS(PublishLeaderSMSDto dto, CancellationToken cancellationToken)
    {
        //发送短信
        var messageDto = new Share.Dtos.Push.MessageDto
        {
            PushBusiness = EPushBusiness.OrderSend,
            ExternalId = dto.OrderId,
            OrderId = dto.OrderId,
            PushPlatform = EPushPlatform.Sms,
            Remark = string.Empty,
            Name = dto.Name,
            TemplateCode = "1014",
            Params = new(),
            TelNumber = dto.TelNumber,
        };
        await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
    }
    #endregion
    #endregion
}