using Hotline.Api.Filter;
using Hotline.Application.ExportExcel;
using Hotline.Application.FlowEngine;
using Hotline.Application.OrderApp;
using Hotline.Application.StatisticalReport;
using Hotline.Application.Systems;
using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Calls;
using Hotline.Configurations;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.KnowledgeBase;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Schedulings;
using Hotline.SeedData;
using Hotline.Settings;
using Hotline.Settings.Hotspots;
using Hotline.Settings.TimeLimitDomain;
using Hotline.Settings.TimeLimits;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Bi;
using Hotline.Share.Dtos.Bigscreen;
using Hotline.Share.Dtos.CallCenter;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Order.OrderDelay;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Order;
using Hotline.Share.Requests;
using Hotline.Share.Tools;
using Hotline.Tools;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SqlSugar;
using System.Data;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;
using XF.Utility.EnumExtensions;
using Hotline.Statistics;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Bibliography;
using NPOI.SS.Formula.Functions;
using Hotline.Share.Dtos.File;
using Hotline.File;
using Hotline.KnowledgeBase;
using DocumentFormat.OpenXml.Vml.Spreadsheet;
using Hotline.Share.Tools;
using MediatR;
using static Hotline.AppDefaults;
using Hotline.Ai.Visit;
using Hotline.Application.OrderApp.OrderVisitApp;

namespace Hotline.Api.Controllers.Bi
{
    public class BiOrderController : BaseController
    {
        private readonly IExportApplication _exportApplication;
        private readonly BaseDataApplication _baseDataApplication;
        private readonly IOrderRepository _orderRepository;
        private readonly IRepository<Hotspot> _hotspotTypeRepository;
        private readonly ISystemDicDataCacheManager _sysDicDataCacheManager;
        private readonly IRepository<OrderVisitDetail> _orderVisitDetailRepository;
        private readonly IRepository<OrderDelay> _orderDelayRepository;
        private readonly IMapper _mapper;
        private readonly IRepository<WorkflowCountersign> _workflowCountersignRepository;
        private readonly IRepository<OrderSpecial> _orderSpecialRepository;
        private readonly IRepository<OrderVisit> _orderVisitRepository;
        private readonly IRepository<TrCallRecord> _trCallRecordRepository;
        private readonly IRepository<OrderPublish> _orderPublishRepository;
        private readonly ISystemOrganizeRepository _systemOrganizeRepository;
        private readonly IRepository<AiOrderVisitDetail> _aiOrderVisitDetailRepository;
        private readonly ISessionContext _sessionContext;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
        private readonly IRepository<OrderSpecialDetail> _orderSpecialDetailRepository;
        private readonly IRepository<WorkflowTrace> _workflowTraceRepository;
        private readonly IRepository<WorkflowStep> _workflowStepRepository;
        private readonly IRepository<OrderScreen> _orderScreenRepository;
        private readonly IOrderSecondaryHandlingApplication _orderSecondaryHandlingApplication;
        private readonly IOrderApplication _orderApplication;
        private readonly IOrderVisitApplication _orderVisitApplication;
        //private readonly ITimeLimitDomainService _timeLimitDomainService;
        private readonly IOrderReportApplication _orderReportApplication;
        private readonly IRepository<SystemArea> _systemAreaRepository;
        private readonly IRepository<Hotspot> _hotspotRepository;
        private readonly IRepository<SystemDicData> _systemDicDataRepository;
        private readonly ISystemDicDataCacheManager _systemDicDataCacheManager;
        private readonly ICalcExpireTime _expireTime;
        private readonly IWorkflowApplication _workflowApplication;
        private readonly ISystemOrganizeRepository _organizeRepository;
        private readonly IRepository<CallNative> _callNativeRepository;
        private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
        private readonly IRepository<OrderTsDetails> _orderTsDetailsRepository;
        private readonly IRepository<KnowledgeQuote> _knowledgeQuoteRepository;
        private readonly IRepository<OrderUrge> _orderUrgeRepository;

        public BiOrderController(
            IOrderRepository orderRepository,
            IRepository<Hotspot> hotspotTypeRepository,
            ISystemDicDataCacheManager sysDicDataCacheManager,
            IRepository<OrderVisitDetail> orderVisitDetailRepository,
            IRepository<OrderDelay> orderDelayRepository,
            IRepository<WorkflowCountersign> workflowCountersignRepository,
            IRepository<OrderSpecial> orderSpecialRepository,
            IMapper mapper,
            IRepository<OrderVisit> orderVisitRepository,
            IRepository<TrCallRecord> trCallRecordRepository,
            IRepository<OrderPublish> orderPublishRepository,
            ISystemOrganizeRepository systemOrganizeRepository,
            IRepository<AiOrderVisitDetail> aiOrderVisitDetailRepository,
            ISessionContext sessionContext,
            ISystemSettingCacheManager systemSettingCacheManager,
            IRepository<OrderSpecialDetail> orderSpecialDetailRepository,
            IRepository<WorkflowTrace> workflowTraceRepository,
            IRepository<OrderScreen> orderScreenRepository,
            IOrderSecondaryHandlingApplication orderSecondaryHandlingApplication,
            IOrderApplication orderApplication,
            //ITimeLimitDomainService timeLimitDomainService,
            IOrderReportApplication orderReportApplication,
            IRepository<SystemArea> systemAreaRepository,
            IRepository<Hotspot> hotspotRepository,
            IRepository<SystemDicData> systemDicDataRepository,
            ISystemDicDataCacheManager systemDicDataCacheManager,
            IRepository<WorkflowStep> workflowStepRepository,
            IWorkflowApplication workflowApplication,
            ICalcExpireTime expireTime,
            ISystemOrganizeRepository organizeRepository,
            BaseDataApplication baseDataApplication,
            IExportApplication exportApplication,
            IOrderVisitApplication orderVisitApplication,
            IRepository<CallNative> callNativeRepository,
            IOptionsSnapshot<AppConfiguration> appOptions,
            IRepository<OrderTsDetails> orderTsDetailsRepository,
            IRepository<KnowledgeQuote> knowledgeQuoteRepository,
            IRepository<OrderUrge> orderUrgeRepository)
        {
            _orderRepository = orderRepository;
            _hotspotTypeRepository = hotspotTypeRepository;
            _sysDicDataCacheManager = sysDicDataCacheManager;
            _orderVisitDetailRepository = orderVisitDetailRepository;
            _orderDelayRepository = orderDelayRepository;
            _workflowCountersignRepository = workflowCountersignRepository;
            _orderSpecialRepository = orderSpecialRepository;
            _mapper = mapper;
            _orderVisitRepository = orderVisitRepository;
            _trCallRecordRepository = trCallRecordRepository;
            _orderPublishRepository = orderPublishRepository;
            _systemOrganizeRepository = systemOrganizeRepository;
            _aiOrderVisitDetailRepository = aiOrderVisitDetailRepository;
            _sessionContext = sessionContext;
            _systemSettingCacheManager = systemSettingCacheManager;
            _orderSpecialDetailRepository = orderSpecialDetailRepository;
            _workflowTraceRepository = workflowTraceRepository;
            _orderScreenRepository = orderScreenRepository;
            _orderSecondaryHandlingApplication = orderSecondaryHandlingApplication;
            _orderApplication = orderApplication;
            //_timeLimitDomainService = timeLimitDomainService;
            _orderReportApplication = orderReportApplication;
            _systemAreaRepository = systemAreaRepository;
            _hotspotRepository = hotspotRepository;
            _systemDicDataRepository = systemDicDataRepository;
            _systemDicDataCacheManager = systemDicDataCacheManager;
            _workflowStepRepository = workflowStepRepository;
            _workflowApplication = workflowApplication;
            _expireTime = expireTime;
            _organizeRepository = organizeRepository;
            _baseDataApplication = baseDataApplication;
            _exportApplication = exportApplication;
            _orderVisitApplication = orderVisitApplication;
            _callNativeRepository = callNativeRepository;
            _appOptions = appOptions;
            _orderTsDetailsRepository = orderTsDetailsRepository;
            _knowledgeQuoteRepository = knowledgeQuoteRepository;
            _orderUrgeRepository = orderUrgeRepository;
        }

        /// <summary>
        /// 部门发布量统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("published/statistics/department")]
        public async Task<PagedDto<PublishedOrderStatisticsDto>> QueryPublishedOrderDepartmentAsync([FromQuery] QueryOrderPublishStatisticsAllDto dto)
        {
            var (total, items) = await _orderApplication.QueryPublishedOrderDepartmentAsync(dto, false);
            return new PagedDto<PublishedOrderStatisticsDto>(total, _mapper.Map<IReadOnlyList<PublishedOrderStatisticsDto>>(items));
        }

        /// <summary>
        /// 部门发布量统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("published/statistics/department/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryPublishedOrderDepartmentAsync([FromBody] ExportExcelDto<QueryOrderPublishStatisticsAllDto> dto)
        {
            var (total, list) = await _orderApplication.QueryPublishedOrderDepartmentAsync(dto.QueryDto, dto.IsExportAll);
            if (list != null && list.Count > 0)
            {
                list.Add(new PublishedOrderStatisticsDto()
                {
                    Name = "合计",
                    PrivateCount = list.Sum(m => m.PrivateCount),
                    // TotalCount = list.Sum(p => p.TotalCount),
                    PublicCount = list.Sum(m => m.PublicCount),
                    WaitCount = list.Sum(m => m.WaitCount)
                });
            }
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<PublishedOrderStatisticsDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(PublishedOrderStatisticsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门发布量统计");
        }

        /// <summary>
        /// 发布量统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("published/statistics/user")]
        public async Task<PagedDto<PublishedOrderStatisticsDto>> QueryPublishedOrderUserAsync([FromQuery] QueryOrderPublishStatisticsDto dto)
        {
            var (total, list) = await _orderApplication.QueryPublishedOrderAsync(dto, false);
            return new PagedDto<PublishedOrderStatisticsDto>(total, _mapper.Map<IReadOnlyList<PublishedOrderStatisticsDto>>(list));
        }

        /// <summary>
        /// 发布量统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("published/statistics/user/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryPublishedOrder([FromBody] ExportExcelDto<QueryOrderPublishStatisticsDto> dto)
        {
            var (total, list) = await _orderApplication.QueryPublishedOrderAsync(dto.QueryDto, dto.IsExportAll);
            if (list != null && list.Count > 0)
            {
                list.Add(new PublishedOrderStatisticsDto()
                {
                    Name = "合计",
                    PrivateCount = list.Sum(m => m.PrivateCount),
                    //TotalCount = list.Sum(p => p.TotalCount),
                    PublicCount = list.Sum(m => m.PublicCount),
                    WaitCount = list.Sum(m => m.WaitCount)
                });
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<PublishedOrderStatisticsDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(PublishedOrderStatisticsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "发布量统计");
        }

        /// <summary>
        /// 发布量统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("published/statistics")]
        public async Task<PublishedOrderStatisticsDto> QueryPublishedOrderAsync([FromQuery] QueryOrderPublishStatisticsAllDto dto)
        {
            var waitCount = await _orderRepository.Queryable()
             .Where(order => order.Status == EOrderStatus.Filed)
             .Select(order => SqlFunc.AggregateCount(order.Id))
             .FirstAsync();

            var publicCount = await _orderPublishRepository.Queryable()
                .Where(publish => publish.CreationTime >= dto.StartTime && publish.CreationTime <= dto.EndTime)
                .Where(publish => publish.PublishState == true)
                .Select(publish => SqlFunc.AggregateCount(publish.Id))
                .FirstAsync();

            var privateCount = await _orderPublishRepository.Queryable()
                .Where(publish => publish.CreationTime >= dto.StartTime && publish.CreationTime <= dto.EndTime)
                .Where(publish => publish.PublishState == false)
                .Select(publish => SqlFunc.AggregateCount(publish.Id))
                .FirstAsync();


            return new PublishedOrderStatisticsDto
            {
                // TotalCount = totalCount,
                PrivateCount = privateCount,
                PublicCount = publicCount,
                WaitCount = waitCount
            };
        }

        /// <summary>
        /// 回访来源统计
        /// </summary>
        /// <returns></returns>
        [HttpGet("visit/source")]
        public async Task<IList<OrderVisitSourceChannelDto>> QueryOrderVisitSourceChannelAsync([FromQuery] QueryOrderVisitSourceChannelDto dto)
            => await _orderApplication.QueryOrderVisitSourceChannelAsync(dto);

        /// <summary>
        /// 回访来源统计--导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("visit/source/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QueryOrderVisitSourceChannelExportAsync([FromBody] ExportExcelDto<QueryOrderVisitSourceChannelDto> dto)
        {
            var list = await _orderApplication.QueryOrderVisitSourceChannelAsync(dto.QueryDto);
            return _exportApplication.GetExcelFile(dto, list, "回访来源统计", "SourceChannel");
        }

        /// <summary>
        /// 回访量统计
        /// </summary>
        /// <returns></returns>
        [HttpGet("visit/quantity")]
        public async Task<TotalList<OrderVisitQuantityOutDto>> QueryOrderVisitQuantityAsync([FromQuery] QueryOrderVisitQuantity dto)
        {
            var items = await _orderVisitApplication.QueryOrderVisitQuantityAsync(dto);
            var total = new OrderVisitQuantityOutDto
            {
                EmployeeName = "合计",
                EmployeeId = "",
                CallVisitCount = items.Sum(m => m.CallVisitCount),
                DefaultVisitCount = items.Sum(m => m.DefaultVisitCount),
                SmsVisitCount = items.Sum(m => m.SmsVisitCount)
            };
            return new TotalList<OrderVisitQuantityOutDto>(items, total);

        }

        /// <summary>
        /// 回访量统计--导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("visit/quantity/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QueryOrderVisitQuantityExportAsync([FromBody] ExportExcelDto<QueryOrderVisitQuantity> dto)
        {
            var items = await _orderVisitApplication.QueryOrderVisitQuantityAsync(dto.QueryDto);
            return _exportApplication.GetExcelFile(dto, items, "回访量统计");
        }

        /// <summary>
        /// 回访量明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit/quantity/list")]
        public async Task<PagedDto<OrderVisitDto>> QueryOrderVisitQuantityListAsync([FromQuery] QueryOrderVisitListDto dto)
        {
            if (_appOptions.Value.IsZiGong == true)
            {
                var (total, items) = await _orderApplication.QueryOrderVisitQuantityListByZgAsync(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
                return new PagedDto<OrderVisitDto>(total, _mapper.Map<IReadOnlyList<OrderVisitDto>>(items));
            }
            else
            {
                var (total, items) = await _orderApplication.QueryOrderVisitQuantityListAsync(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
                return new PagedDto<OrderVisitDto>(total, _mapper.Map<IReadOnlyList<OrderVisitDto>>(items));
            }
        }

        /// <summary>
        /// 回访量明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit/quantity/list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QueryOrderVisitQuantityExport([FromBody] ExportExcelDto<QueryOrderVisitListDto> dto)
        {
            if (_appOptions.Value.IsZiGong == true)
            {
                var query = _orderApplication.QueryOrderVisitQuantityListByZgAsync(dto.QueryDto);
                List<OrderVisitRecord> orders;
                if (dto.IsExportAll)
                {
                    orders = await query.ToListAsync(HttpContext.RequestAborted);
                }
                else
                {
                    var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                    orders = items;
                }


                var orderDtos = _mapper.Map<ICollection<OrderVisitDto>>(orders);
                dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVisitDto>(dto.ColumnInfos);

                var dtos = orderDtos
                    .Select(stu => _mapper.Map(stu, typeof(OrderVisitDto), dynamicClass))
                    .Cast<object>()
                    .ToList();

                var stream = ExcelHelper.CreateStream(dtos);
                var excelTitle = "回访量明细";
                return ExcelStreamResult(stream, excelTitle);
            }
            else
            {
                var query = _orderApplication.QueryOrderVisitQuantityListAsync(dto.QueryDto);
                List<OrderVisit> orders;
                if (dto.IsExportAll)
                {
                    orders = await query.ToListAsync(HttpContext.RequestAborted);
                }
                else
                {
                    var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                    orders = items;
                }


                var orderDtos = _mapper.Map<ICollection<OrderVisitDto>>(orders);
                dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVisitDto>(dto.ColumnInfos);

                var dtos = orderDtos
                    .Select(stu => _mapper.Map(stu, typeof(OrderVisitDto), dynamicClass))
                    .Cast<object>()
                    .ToList();

                var stream = ExcelHelper.CreateStream(dtos);
                var excelTitle = "回访量明细";
                return ExcelStreamResult(stream, excelTitle);
            }
        }


        /// <summary>
        /// 部门超期统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("org_data_list_detail")]
        public async Task<PagedDto<OrderDto>> OrgDataListDetail([FromQuery] OrgDataListDetailRequest dto)
        {
            var quer = _orderApplication.QueryOrgDataListDetail(dto);
            var (total, items) = await quer.ToPagedListAsync(dto.PageIndex, dto.PageSize);

            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 部门超期统计明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("org_data_list_detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrgDataListDetailExport([FromBody] ExportExcelDto<OrgDataListDetailRequest> dto)
        {
            var query = _orderApplication.QueryOrgDataListDetail(dto.QueryDto);
            List<Order> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<OrderDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门超期统计明细数据");
        }

        /// <summary>
        /// 全量部门超期统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("org_data_list_detail_all")]
        public async Task<PagedDto<OrderDto>> OrgDataListDetail([FromQuery] OrgDataListAllDetailRequest dto)
        {
            var quer = _orderApplication.QueryOrgDataListDetail(dto);
            var (total, items) = await quer.ToPagedListAsync(dto.PageIndex, dto.PageSize);

            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 部门超期统计明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("org_data_list_detail_all/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrgDataListDetailExport([FromBody] ExportExcelDto<OrgDataListAllDetailRequest> dto)
        {
            var query = _orderApplication.QueryOrgDataListDetail(dto.QueryDto);
            List<Order> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<OrderDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门超期统计明细数据");
        }

        /// <summary>
        /// 列表页面基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("org_data_list_detail_all/base-data")]
        public async Task<object> BaseData()
        {
            var rsp = new
            {
                OrderStatusOptions = EnumExts.GetDescriptions<EOrderStatus>()
            };
            return rsp;
        }

        /// <summary>
        /// 部门超期统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("org_data_list")]
        public async Task<PagedDto<OrderBiOrgDataListVo>> OrgDataList([FromQuery] ReportPagedRequest dto)
        {
            var query = _orderApplication.QueryOrgDataList(dto);
            var (total, items) = await query.ToPagedListAsync(dto, HttpContext.RequestAborted);
            items.Add(new OrderBiOrgDataListVo
            {
                OrgName = "合计",
                HandlerExtendedNum = items.Select(s => s.HandlerExtendedNum).Sum(),
                CounterHandlerExtendedNum = items.Select(s => s.CounterHandlerExtendedNum).Sum(),
                NoHandlerExtendedNum = items.Select(s => s.NoHandlerExtendedNum).Sum(),
                CounterNoHandlerExtendedNum = items.Select(s => s.CounterNoHandlerExtendedNum).Sum(),
            });
            return new PagedDto<OrderBiOrgDataListVo>(total, items);
        }

        /// <summary>
        /// 部门超期统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("org_data_list/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrgDataListExport([FromBody] ExportExcelDto<ReportPagedRequest> dto)
        {
            var query = _orderApplication.QueryOrgDataList(dto.QueryDto);
            List<OrderBiOrgDataListVo> data;
            data = await query.ToListAsync(HttpContext.RequestAborted);
            data.Add(new OrderBiOrgDataListVo
            {
                OrgName = "合计",
                HandlerExtendedNum = data.Select(s => s.HandlerExtendedNum).Sum(),
                CounterHandlerExtendedNum = data.Select(s => s.CounterHandlerExtendedNum).Sum(),
                NoHandlerExtendedNum = data.Select(s => s.NoHandlerExtendedNum).Sum(),
                CounterNoHandlerExtendedNum = data.Select(s => s.CounterNoHandlerExtendedNum).Sum(),
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderBiOrgDataListVo>(dto.ColumnInfos);
            var dtos = data
             .Select(stu => _mapper.Map(stu, typeof(OrderBiOrgDataListVo), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门超期统计数据");
        }

        /// <summary>
        /// 话务员办件统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("centre_data_list")]
        public async Task<TotalList<OrderBiCentreDataListVo>> CentreDataList([FromQuery] ReportPagedRequest dto)
        {
            ISugarQueryable<OrderBiCentreDataListVo> query;
            if (_appOptions.Value.IsZiGong)
                query = _orderApplication.CentreDataListZG(dto);
            else
                query = _orderApplication.CentreDataList(dto);

            var list = await query.Where(x => (x.CentreArchive + x.CentreCareOf + x.NoCentreCareOf + x.Invalid + x.Repeat) != 0).ToListAsync(HttpContext.RequestAborted);

            var total = new OrderBiCentreDataListVo
            {
                UserName = "合计",
                UserId = "",
                CentreArchive = list.Select(s => s.CentreArchive).Sum(),
                CentreCareOf = list.Select(s => s.CentreCareOf).Sum(),
                NoCentreCareOf = list.Select(s => s.NoCentreCareOf).Sum(),
                Invalid = list.Select(s => s.Invalid).Sum(),
                Repeat = list.Select(s => s.Repeat).Sum(),
                Subtotal = list.Select(s => s.Subtotal).Sum()
            };

            return new TotalList<OrderBiCentreDataListVo>(list, total);
        }

        /// <summary>
        /// 话务员办件统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("centre_data_list_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> CentreDataListExport([FromBody] ExportExcelDto<ReportPagedRequest> dto)
        {
            ISugarQueryable<OrderBiCentreDataListVo> query;
            if (_appOptions.Value.IsZiGong)
                query = _orderApplication.CentreDataListZG(dto.QueryDto);
            else
                query = _orderApplication.CentreDataList(dto.QueryDto);

            //var query = _orderApplication.CentreDataList(dto.QueryDto);
            List<OrderBiCentreDataListVo> data = await query.Where(x => (x.CentreArchive + x.CentreCareOf + x.NoCentreCareOf + x.Invalid + x.Repeat) != 0).ToListAsync(HttpContext.RequestAborted);
            data.Add(new OrderBiCentreDataListVo
            {
                UserName = "合计",
                CentreArchive = data.Select(s => s.CentreArchive).Sum(),
                CentreCareOf = data.Select(s => s.CentreCareOf).Sum(),
                NoCentreCareOf = data.Select(s => s.NoCentreCareOf).Sum(),
                Invalid = data.Select(s => s.Invalid).Sum(),
                Repeat = data.Select(s => s.Repeat).Sum(),
                Subtotal = data.Select(s => s.Subtotal).Sum()
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderBiCentreDataListVo>(dto.ColumnInfos);
            var dtos = data
             .Select(stu => _mapper.Map(stu, typeof(OrderBiCentreDataListVo), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "话务员办件统计");
        }

        /// <summary>
        /// 话务员办件统计明细列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("centre_data_list_detail")]
        public async Task<PagedDto<OrderDto>> CentreDataListDetailExport([FromQuery] CentreDataListDetailRequest dto)
        {
            var (total, items) = await _orderApplication.CentreDataListDetailZG(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<List<OrderDto>>(items));
        }

        /// <summary>
        /// 话务员办件统计明细列表--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("centre_data_list_detail_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> CentreDataListDetailExport([FromBody] ExportExcelDto<CentreDataListDetailRequest> dto)
        {
            var query = _orderApplication.CentreDataListDetailZG(dto.QueryDto);
            List<Order> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }

            var orderDtos = _mapper.Map<ICollection<OrderDto>>(orders);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "话务员办件统计明细列表");
        }

        /// <summary>
        /// 工单业务量统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order/volume/statistics")]
        public async Task<List<OrderVolumeDataListVo>> OrderVolumeStatistics([FromQuery] ReportPagedRequest dto)
        {
            var query = _orderApplication.OrderVolumeStatistics(dto);
            var list = await query.ToListAsync(HttpContext.RequestAborted);
            return list.OrderByDescending(p => p.Subtotal).ToList();
        }

        /// <summary>
        /// 工单业务量统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order/volume/statistics/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderVolumeStatisticsExport([FromBody] ExportExcelDto<ReportPagedRequest> dto)
        {
            var query = _orderApplication.OrderVolumeStatistics(dto.QueryDto);
            List<OrderVolumeDataListVo> data = await query.ToListAsync(HttpContext.RequestAborted);
            data = data.OrderByDescending(p => p.Subtotal).ToList();
            data.Add(new OrderVolumeDataListVo
            {
                UserName = "合计",
                VisitCenter = data.Select(s => s.VisitCenter).Sum(),
                VisitOrg = data.Select(s => s.VisitOrg).Sum(),
                PublishCenter = data.Select(s => s.PublishCenter).Sum(),
                PublishOrg = data.Select(s => s.PublishOrg).Sum(),
                PublishOpen = data.Select(s => s.PublishOpen).Sum(),
                DispatchCenter = data.Select(s => s.DispatchCenter).Sum(),
                DispatchOrg = data.Select(s => s.DispatchOrg).Sum(),
                ReTransact = data.Select(s => s.ReTransact).Sum(),
                Subtotal = data.Select(s => s.Subtotal).Sum()
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVolumeDataListVo>(dto.ColumnInfos);
            var dtos = data
             .Select(stu => _mapper.Map(stu, typeof(OrderVolumeDataListVo), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "工单业务量统计");
        }

        /// <summary>
        /// 工单业务量列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order/volume/list")]
        public async Task<IReadOnlyList<OrderDto>> OrderVolumeList([FromQuery] QueryOrderVolumeDto dto)
        {
            var orders = await _orderApplication.OrderVolumeList(dto)
                .ToPageListWithoutTotalAsync(dto, HttpContext.RequestAborted);
            var list = _mapper.Map<IReadOnlyList<OrderDto>>(orders);
            if (_appOptions.Value.IsLuZhou && !_sessionContext.OrgIsCenter)
                list = list.Select(p => p.DataMask(false)).ToList();
            return list;
        }

        /// <summary>
        /// 工单业务量列表总数
        /// </summary>
        [HttpGet("order/volume/list/count")]
        public async Task<int> OrderVolumeListCount([FromQuery] QueryOrderVolumeDto dto)
        {
            var query = _orderApplication.OrderVolumeList(dto);
            return await query.CountAsync(HttpContext.RequestAborted);
        }

        /// <summary>
        /// 工单业务量列表导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order/volume/list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderVolumeListExport([FromBody] ExportExcelDto<QueryOrderVolumeDto> dto)
        {
            var query = _orderApplication.OrderVolumeList(dto.QueryDto);
            List<Order> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }

            var orderDtos = _mapper.Map<ICollection<OrderDto>>(orders);

            if (_appOptions.Value.IsLuZhou)
                orderDtos = orderDtos.Select(p => p.DataMask(false)).ToList();

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "工单业务量列表");
        }



        /// <summary>
        /// 热点数据小计统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot_subtotal_data_list")]
        public async Task<PagedDto<HotspotDataLsitVo>> HotspotSubtotalDataLsit([FromQuery] HotspotSubtotalReportPagedRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var query = _hotspotTypeRepository.Queryable(false, true)
                .LeftJoin<Order>((x, o) => o.HotspotSpliceName != null && (x.HotSpotFullName == o.HotspotSpliceName || o.HotspotSpliceName.Contains(x.HotSpotFullName)) && o.IsDeleted == false)
                .WhereIF(dto.StartTime.HasValue, (x, o) => o.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, (x, o) => o.CreationTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), (x, o) => x.HotSpotName.Contains(dto.Keyword!))
                .Where((x, o) => x.ParentId == dto.Id)
                .Where((x, o) => x.IsDeleted == false)
                .GroupBy((x, o) => new { x.Id, x.HotSpotName })
                .Select((x, o) => new HotspotDataLsitVo
                {
                    Id = x.Id,
                    Name = x.HotSpotName,
                    Num = SqlFunc.AggregateSum(SqlFunc.IIF(o.Id != null, 1, 0)),
                }).MergeTable();
            var (total, items) = await query.ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<HotspotDataLsitVo>(total, items);
        }

        /// <summary>
        /// 热点数据统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotspot_data_list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotDataLsitExprot([FromBody] ExportExcelDto<HotspotReportPagedRequest> dto)
        {
            if (!dto.QueryDto.StartTime.HasValue || !dto.QueryDto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");
            if (dto.QueryDto.Type == 0 && (!dto.QueryDto.ChainStartTime.HasValue || !dto.QueryDto.ChainEndTime.HasValue)) throw UserFriendlyException.SameMessage("请选择环比时间!");

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

            var IsCenter = _sessionContext.OrgIsCenter;

            if (dto.QueryDto.Type == 0)
            {
                dto.QueryDto.ChainEndTime = dto.QueryDto.ChainEndTime.Value.AddDays(1).AddSeconds(-1);
            }

            var items = await _hotspotTypeRepository.Queryable(false, true)
                .LeftJoin<Order>((x, o) => o.HotspotSpliceName != null && (x.HotSpotName == o.HotspotSpliceName || o.HotspotSpliceName.Contains(x.HotSpotName)) && o.IsDeleted == false)
                .WhereIF(dto.QueryDto.StartTime.HasValue, (x, o) => o.CreationTime >= dto.QueryDto.StartTime)
                .WhereIF(dto.QueryDto.EndTime.HasValue, (x, o) => o.CreationTime <= dto.QueryDto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.Keyword), (x, o) => x.HotSpotName.Contains(dto.QueryDto.Keyword!))
                .WhereIF(IsCenter == false, (x, o) => o.ActualHandleOrgCode == _sessionContext.RequiredOrgId)
                .Where((x, o) => x.ParentId == dto.QueryDto.Id)
                .Where((x, o) => x.IsDeleted == false)
                .GroupBy((x, o) => new { x.Id, x.HotSpotName })
                .Select((x, o) => new HotspotDataLsitVo
                {
                    Id = x.Id,
                    Name = x.HotSpotName,
                    Num = SqlFunc.AggregateSum(SqlFunc.IIF(o.Id != null, 1, 0)),
                    Sublevel = SqlFunc.AggregateSum(SqlFunc.IIF(x.HotSpotName != o.HotspotName, 1, 0)) > 0,
                }).MergeTable().ToListAsync();
            var chainStartTime = dto.QueryDto.StartTime;
            var chainEndTime = dto.QueryDto.EndTime;
            switch (dto.QueryDto.Type)
            {
                case 1://日
                    chainStartTime = dto.QueryDto.StartTime.Value.AddDays(-1);
                    chainEndTime = dto.QueryDto.EndTime.Value.AddDays(-1);
                    break;
                case 2://月
                    chainStartTime = dto.QueryDto.StartTime.Value.AddMonths(-1);
                    chainEndTime = dto.QueryDto.EndTime.Value.AddMonths(-1);
                    break;
                case 3://年
                    chainStartTime = dto.QueryDto.StartTime.Value.AddYears(-1);
                    chainEndTime = dto.QueryDto.EndTime.Value.AddYears(-1);
                    break;
                case 0:
                    chainStartTime = dto.QueryDto.ChainStartTime.Value;
                    chainEndTime = dto.QueryDto.ChainEndTime.Value;
                    break;
            }
            var chainItems = await _hotspotTypeRepository.Queryable(false, true)
                .LeftJoin<Order>((x, o) => o.HotspotSpliceName != null && (x.HotSpotName == o.HotspotSpliceName || o.HotspotSpliceName.Contains(x.HotSpotName)) && o.IsDeleted == false)
                .WhereIF(dto.QueryDto.StartTime.HasValue, (x, o) => o.CreationTime >= chainStartTime)
                .WhereIF(dto.QueryDto.EndTime.HasValue, (x, o) => o.CreationTime <= chainEndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.Keyword), (x, o) => x.HotSpotName.Contains(dto.QueryDto.Keyword!))
                .WhereIF(IsCenter == false, (x, o) => o.ActualHandleOrgCode == _sessionContext.RequiredOrgId)
                .Where((x, o) => x.ParentId == dto.QueryDto.Id)
                .Where((x, o) => x.IsDeleted == false)
                .GroupBy((x, o) => new { x.Id, x.HotSpotName })
                .Select((x, o) => new
                {
                    Id = x.Id,
                    ChainNum = SqlFunc.AggregateSum(SqlFunc.IIF(o.Id != null, 1, 0)),
                }).MergeTable().ToListAsync();
            var res = (from t1 in items
                       join t2 in chainItems on t1.Id equals t2.Id into t1_t2
                       from item in t1_t2.DefaultIfEmpty()
                       select new HotspotDataLsitVo
                       {
                           Id = t1.Id,
                           Name = t1.Name,
                           Num = t1.Num,
                           Sublevel = t1.Sublevel,
                           Children = new List<HotspotDataLsitVo>(),
                           ChainNum = t1_t2.Select(x => x.ChainNum).FirstOrDefault(),
                           ChainRate = t1_t2.Select(x => x.ChainNum).FirstOrDefault() > 0 ?
                           ((double.Parse(t1.Num.ToString()) - double.Parse(t1_t2.Select(x => x.ChainNum).FirstOrDefault().ToString())) / double.Parse(t1_t2.Select(x => x.ChainNum).FirstOrDefault().ToString()) * 100).ToString("F2") + "%" : "100.00%",
                       }).ToList();
            var total = new HotspotDataLsitVo()
            {
                Id = "0",
                Name = "合计",
                Num = res.Sum(x => x.Num),
                Sublevel = false,
                Children = new List<HotspotDataLsitVo>(),
                ChainNum = res.Sum(x => x.ChainNum),
                ChainRate = res.Sum(x => x.ChainNum) > 0 ? ((double.Parse(res.Sum(x => x.Num).ToString()) - double.Parse(res.Sum(x => x.ChainNum).ToString())) / double.Parse(res.Sum(x => x.ChainNum).ToString()) * 100).ToString("F2") + "%" : "100.00%"
            };
            res.Add(total);

            List<HotspotDataLsitVo> data;
            data = res;

            var dataDtos = _mapper.Map<ICollection<HotspotDataLsitVo>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<HotspotDataLsitVo>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(HotspotDataLsitVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "热点类型统计");
            //return new { List = res, Total = total };
        }

        /// <summary>
        /// 热点数据统计 TODO和前端沟通
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot_data_list")]
        public async Task<object> HotspotDataLsit([FromQuery] HotspotReportPagedRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");
            if (dto.Type == 0 && (!dto.ChainStartTime.HasValue || !dto.ChainEndTime.HasValue)) throw UserFriendlyException.SameMessage("请选择环比时间!");

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

            var IsCenter = _sessionContext.OrgIsCenter;

            if (dto.Type == 0)
            {
                dto.ChainEndTime = dto.ChainEndTime.Value.AddDays(1).AddSeconds(-1);
            }

            var items = await _hotspotTypeRepository.Queryable(false, true)
                .LeftJoin<Order>((x, o) => o.HotspotSpliceName != null && (x.HotSpotName == o.HotspotSpliceName || o.HotspotSpliceName.Contains(x.HotSpotName)) && o.IsDeleted == false)
                .WhereIF(dto.StartTime.HasValue, (x, o) => o.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, (x, o) => o.CreationTime <= dto.EndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), (x, o) => x.HotSpotName.Contains(dto.Keyword!))
                .WhereIF(IsCenter == false, (x, o) => o.ActualHandleOrgCode == _sessionContext.RequiredOrgId)
                .Where((x, o) => x.ParentId == dto.Id)
                .Where((x, o) => x.IsDeleted == false)
                .GroupBy((x, o) => new { x.Id, x.HotSpotName })
                .Select((x, o) => new HotspotDataLsitVo
                {
                    Id = x.Id,
                    Name = x.HotSpotName,
                    Num = SqlFunc.AggregateSum(SqlFunc.IIF(o.Id != null, 1, 0)),
                    Sublevel = SqlFunc.AggregateSum(SqlFunc.IIF(x.HotSpotName != o.HotspotName, 1, 0)) > 0,
                }).MergeTable().ToListAsync();
            var chainStartTime = dto.StartTime;
            var chainEndTime = dto.EndTime;
            switch (dto.Type)
            {
                case 1://日
                    chainStartTime = dto.StartTime.Value.AddDays(-1);
                    chainEndTime = dto.EndTime.Value.AddDays(-1);
                    break;
                case 2://月
                    chainStartTime = dto.StartTime.Value.AddMonths(-1);
                    chainEndTime = dto.EndTime.Value.AddMonths(-1);
                    break;
                case 3://年
                    chainStartTime = dto.StartTime.Value.AddYears(-1);
                    chainEndTime = dto.EndTime.Value.AddYears(-1);
                    break;
                case 0:
                    chainStartTime = dto.ChainStartTime.Value;
                    chainEndTime = dto.ChainEndTime.Value;
                    break;
            }
            var chainItems = await _hotspotTypeRepository.Queryable(false, true)
                .LeftJoin<Order>((x, o) => o.HotspotSpliceName != null && (x.HotSpotName == o.HotspotSpliceName || o.HotspotSpliceName.Contains(x.HotSpotName)) && o.IsDeleted == false)
                .WhereIF(dto.StartTime.HasValue, (x, o) => o.CreationTime >= chainStartTime)
                .WhereIF(dto.EndTime.HasValue, (x, o) => o.CreationTime <= chainEndTime)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), (x, o) => x.HotSpotName.Contains(dto.Keyword!))
                .WhereIF(IsCenter == false, (x, o) => o.ActualHandleOrgCode == _sessionContext.RequiredOrgId)
                .Where((x, o) => x.ParentId == dto.Id)
                .Where((x, o) => x.IsDeleted == false)
                .GroupBy((x, o) => new { x.Id, x.HotSpotName })
                .Select((x, o) => new
                {
                    Id = x.Id,
                    ChainNum = SqlFunc.AggregateSum(SqlFunc.IIF(o.Id != null, 1, 0)),
                }).MergeTable().ToListAsync();
            var res = (from t1 in items
                       join t2 in chainItems on t1.Id equals t2.Id into t1_t2
                       from item in t1_t2.DefaultIfEmpty()
                       select new HotspotDataLsitVo()
                       {
                           Id = t1.Id,
                           Name = t1.Name,
                           Num = t1.Num,
                           Sublevel = t1.Sublevel,
                           Children = new List<HotspotDataLsitVo>(),
                           ChainNum = t1_t2.Select(x => x.ChainNum).FirstOrDefault(),
                           ChainRate = t1_t2.Select(x => x.ChainNum).FirstOrDefault() > 0 ?
                           ((double.Parse(t1.Num.ToString()) - double.Parse(t1_t2.Select(x => x.ChainNum).FirstOrDefault().ToString())) / double.Parse(t1_t2.Select(x => x.ChainNum).FirstOrDefault().ToString()) * 100).ToString("F2") + "%" : "100.00%",
                       }).ToList();
            var total = new HotspotDataLsitVo()
            {
                Id = "0",
                Name = "合计",
                Num = res.Sum(x => x.Num),
                Sublevel = false,
                Children = new List<HotspotDataLsitVo>(),
                ChainNum = res.Sum(x => x.ChainNum),
                ChainRate = res.Sum(x => x.ChainNum) > 0 ? ((double.Parse(res.Sum(x => x.Num).ToString()) - double.Parse(res.Sum(x => x.ChainNum).ToString())) / double.Parse(res.Sum(x => x.ChainNum).ToString()) * 100).ToString("F2") + "%" : "100.00%"
            };
            return new { List = res, Total = total };
        }

        /// <summary>
        /// 部门不满意统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-nosatisfied/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryVisitNoSatisfied([FromBody] QueryVisitNoSatisfiedDto dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");
            if (dto.AddColumnName is null || dto.AddColumnName.Count == 0) throw UserFriendlyException.SameMessage("导出字段不能为空");
            if (dto.AddColumnName.FirstOrDefault() != "部门名称") throw UserFriendlyException.SameMessage("导出字段第一个必须是'部门名称'");

            var (dissatisfiedReason, list) = await _orderReportApplication.QueryVisitNoSatisfiedAsync(dto, _sessionContext.OrgIsCenter);
            var dataTable = await _orderReportApplication.ExportQueryVisitNoSatisfiedAsync(dissatisfiedReason, list, dto.AddColumnName);

            return ExcelStreamResult(ExcelHelper.CreateStream(dataTable), "回访不满意原因统计");
        }

        /// <summary>
        /// 部门不满意统计
        /// 已加验证部门
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-nosatisfied")]
        public async Task<object> QueryVisitNoSatisfied([FromQuery] QueryVisitNoSatiisfiedRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var (dissatisfiedReason, list) = await _orderReportApplication
                .QueryVisitNoSatisfiedAsync(_mapper.Map<QueryVisitNoSatisfiedDto>(dto), _sessionContext.OrgIsCenter);
            return new { DicReason = dissatisfiedReason, Data = list };
        }

        /// <summary>
        /// 部门不满意统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-nosatisfied-detail")]
        public async Task<PagedDto<OrderVisitDetailDto>> BiQueryVisitNoSatisfiedDetail([FromQuery] BiQueryVisitNoSatisfiedDetailDto dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var IsCenter = _sessionContext.OrgIsCenter;

            var (total, items) = await _orderReportApplication.BiQueryVisitNoSatisfiedDetail(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<OrderVisitDetailDto>(total, _mapper.Map<IReadOnlyList<OrderVisitDetailDto>>(items));
        }


        /// <summary>
        /// 部门不满意统计明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-nosatisfied-detail-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> BiQueryVisitNoSatisfiedDetailExport([FromBody] ExportExcelDto<BiQueryVisitNoSatisfiedDetailDto> dto)
        {
            if (!dto.QueryDto.StartTime.HasValue || !dto.QueryDto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var query = _orderReportApplication.BiQueryVisitNoSatisfiedDetail(dto.QueryDto);
            List<OrderVisitDetail> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<OrderVisitDetailDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVisitDetailDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderVisitDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门不满意统计明细");
        }

        /// <summary>
        /// 部门延期统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order-delay-data-list")]
        public async Task<IReadOnlyList<BiOrderDelayDataDto>> QueryOrderDelayDataList([FromQuery] QueryOrderDelayDataListRequest dto)
        {
            return await _orderReportApplication.QueryOrderDelayDataList(dto).ToListAsync();

        }

        /// <summary>
        /// 部门延期统计---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order-delay-data-list-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryOrderDelayDataList([FromBody] ExportExcelDto<QueryOrderDelayDataListRequest> dto)
        {
            var query = _orderReportApplication.QueryOrderDelayDataList(dto.QueryDto);
            List<BiOrderDelayDataDto> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }

            list.Add(new BiOrderDelayDataDto()
            {
                OrgName = "合计",
                OrgCode = "",
                //AllTotal = list.Sum(p => p.AllTotal),
                PassTotal = list.Sum(p => p.PassTotal),
                NoPassTotal = list.Sum(p => p.NoPassTotal),
                ExaminingTotal = list.Sum(p => p.ExaminingTotal),
                WithdrawTotal = list.Sum(p => p.WithdrawTotal)
            });

            var orderDtos = _mapper.Map<ICollection<BiOrderDelayDataDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<BiOrderDelayDataDto>(dto.ColumnInfos);
            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(BiOrderDelayDataDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "部门延期统计数据");
        }

        /// <summary>
        /// 部门延期统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order-delay-data-detail")]
        public async Task<PagedDto<OrderDelayDto>> QueryOrderDelayDataDetail([FromQuery] QueryOrderDelayDataDetailRequest dto)
        {
            var (total, items) = await _orderReportApplication.QueryOrderDelayDataDetail(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<OrderDelayDto>(total, _mapper.Map<IReadOnlyList<OrderDelayDto>>(items));
        }

        /// <summary>
        /// 部门延期统计明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order-delay-data-detail-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryOrderDelayDataDetail([FromBody] ExportExcelDto<QueryOrderDelayDataDetailRequest> dto)
        {
            var query = _orderReportApplication.QueryOrderDelayDataDetail(dto.QueryDto);
            List<OrderDelay> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }


            var orderDtos = _mapper.Map<ICollection<OrderDelayDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDelayDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDelayDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "部门延期统计明细数据");
        }


        /// <summary>
        /// 部门延期统计明细-单独菜单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_delay_detail")]
        public async Task<PagedDto<OrderDelayDto>> QueryOrderDelayDataDetailAsync([FromQuery] QueryOrderDelayDataDetailRequest dto)
        {
            var query = _orderDelayRepository.Queryable()
                 .Includes(x => x.Order)
                 .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
                 .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
                .WhereIF(dto.TypeId != null && dto.TypeId == 1, x => x.Order.IdentityType == EIdentityType.Citizen)
                .WhereIF(dto.TypeId != null && dto.TypeId == 2, x => x.Order.IdentityType == EIdentityType.Enterprise)
                 .WhereIF(dto.Type is 1, x => x.DelayState == EDelayState.Pass)
                 .WhereIF(dto.Type is 2, x => x.DelayState == EDelayState.NoPass)
                 .WhereIF(dto.Type is 3, x => x.DelayState == EDelayState.Examining)
                 .WhereIF(dto.Type is 4, x => x.DelayState < EDelayState.Withdraw)
             .MergeTable();

            if (_sessionContext.OrgIsCenter == false)
                query = query.Where(x => x.ApplyOrgCode.StartsWith(_sessionContext.OrgId));

            var (total, items) = await query.ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderDelayDto>(total, _mapper.Map<IReadOnlyList<OrderDelayDto>>(items));
        }

        /// <summary>
        /// 部门延期统计明细-单独菜单 导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order-delay-detail/exprot")]
        public async Task<FileStreamResult> ExportQueryOrderDelayDataDetailAsync([FromBody] ExportExcelDto<QueryOrderDelayDataDetailRequest> dto)
        {
            var query = _orderDelayRepository.Queryable()
                 .Includes(x => x.Order)
                 .WhereIF(dto.QueryDto.StartTime.HasValue, x => x.CreationTime >= dto.QueryDto.StartTime)
                 .WhereIF(dto.QueryDto.EndTime.HasValue, x => x.CreationTime <= dto.QueryDto.EndTime)
                .WhereIF(dto.QueryDto.TypeId != null && dto.QueryDto.TypeId == 1, x => x.Order.IdentityType == EIdentityType.Citizen)
                .WhereIF(dto.QueryDto.TypeId != null && dto.QueryDto.TypeId == 2, x => x.Order.IdentityType == EIdentityType.Enterprise)
                 .WhereIF(dto.QueryDto.Type is 1, x => x.DelayState == EDelayState.Pass)
                 .WhereIF(dto.QueryDto.Type is 2, x => x.DelayState == EDelayState.NoPass)
                 .WhereIF(dto.QueryDto.Type is 3, x => x.DelayState == EDelayState.Examining)
                 .WhereIF(dto.QueryDto.Type is 4, x => x.DelayState < EDelayState.Withdraw)
             .MergeTable();

            if (_sessionContext.OrgIsCenter == false)
                query = query.Where(x => x.ApplyOrgCode.StartsWith(_sessionContext.OrgId));

            List<OrderDelay> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }


            var orderDtos = _mapper.Map<ICollection<OrderDelayDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDelayDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDelayDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "部门延期统计明细数据");

        }

        /// <summary>
        /// 特提统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("special_data_list")]
        public async Task<PagedDto<OrderBiSpecialListVo>> SpecialDataList([FromQuery] ReportPagedRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var IsCenter = _sessionContext.OrgIsCenter;

            var query = _orderSpecialRepository.Queryable()
                .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
                .WhereIF(IsCenter == false, x => x.OrgId.StartsWith(_sessionContext.RequiredOrgId))
                .GroupBy(x => new { x.Cause })
                .Select(x => new OrderBiSpecialListVo
                {
                    Cause = x.Cause,
                    OrderNum = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),
                    MaxSpecialTime = SqlFunc.AggregateMax(x.CreationTime),
                })
                .MergeTable();
            switch (dto.SortField)
            {
                case "cause":
                    query = dto.SortRule is 0 ? query.OrderBy(x => x.Cause) : query.OrderByDescending(x => x.Cause);
                    break;
                case "orderNum":
                    query = dto.SortRule is 0 ? query.OrderBy(x => x.OrderNum) : query.OrderByDescending(x => x.OrderNum);
                    break;
                case "maxSpecialTime":
                    query = dto.SortRule is 0 ? query.OrderBy(x => x.MaxSpecialTime) : query.OrderByDescending(x => x.MaxSpecialTime);
                    break;
            }
            var (total, items) = await query.ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<OrderBiSpecialListVo>(total, items);
        }

        /// <summary>
        /// 特提统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("special_data_list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SpecialDataListExport([FromBody] ExportExcelDto<ReportPagedRequest> dto)
        {
            if (!dto.QueryDto.StartTime.HasValue || !dto.QueryDto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var IsCenter = _sessionContext.OrgIsCenter;

            var query = _orderSpecialRepository.Queryable()
                .WhereIF(dto.QueryDto.StartTime.HasValue, x => x.CreationTime >= dto.QueryDto.StartTime)
                .WhereIF(dto.QueryDto.EndTime.HasValue, x => x.CreationTime <= dto.QueryDto.EndTime)
                .WhereIF(IsCenter == false, x => x.OrgId.StartsWith(_sessionContext.RequiredOrgId))
                .GroupBy(x => new { x.Cause })
                .Select(x => new OrderBiSpecialListVo
                {
                    Cause = x.Cause,
                    OrderNum = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),
                    MaxSpecialTime = SqlFunc.AggregateMax(x.CreationTime),
                })
                .MergeTable();
            switch (dto.QueryDto.SortField)
            {
                case "cause":
                    query = dto.QueryDto.SortRule is 0 ? query.OrderBy(x => x.Cause) : query.OrderByDescending(x => x.Cause);
                    break;
                case "orderNum":
                    query = dto.QueryDto.SortRule is 0 ? query.OrderBy(x => x.OrderNum) : query.OrderByDescending(x => x.OrderNum);
                    break;
                case "maxSpecialTime":
                    query = dto.QueryDto.SortRule is 0 ? query.OrderBy(x => x.MaxSpecialTime) : query.OrderByDescending(x => x.MaxSpecialTime);
                    break;
            }

            var total = 0;
            var items = new List<OrderBiSpecialListVo>();
            if (dto.IsExportAll)
            {
                items = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                (total, items) = await query.ToPagedListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, HttpContext.RequestAborted);
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderBiSpecialListVo>(dto.ColumnInfos);

            var dtos = _mapper.Map<ICollection<OrderBiSpecialListVo>>(items)
                              .Select(stu => _mapper.Map(stu, typeof(OrderBiSpecialListVo), dynamicClass))
                              .Cast<object>()
                              .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "特提统计");
        }

        /// <summary>
        /// 获取工单特提信息列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("special_data_list/list")]
        public async Task<PagedDto<OrderSpecialDto>> List([FromQuery] OrderSpecialListDto dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");

            var IsCenter = _sessionContext.OrgIsCenter;
            var (total, items) = await _orderSpecialRepository.Queryable()
                .Includes(x => x.Order)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword),
                    x => x.Order.No.Contains(dto.Keyword!) || x.Order.Title.Contains(dto.Keyword!))
                .WhereIF(!string.IsNullOrEmpty(dto.Cause),
                    x => x.Cause != null && x.Cause.Equals(dto.Cause))
                .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
                .WhereIF(dto.State.HasValue, x => x.State == dto.State)
                .WhereIF(IsCenter == false, x => x.OrgId.StartsWith(_sessionContext.OrgId))
                .OrderByDescending(x => x.CreationTime)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderSpecialDto>(total, _mapper.Map<IReadOnlyList<OrderSpecialDto>>(items));
        }


        /// <summary>
        /// 受理类型前十
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("accept_type_top10_list")]
        public async Task<object> AcceptTypeTop10List([FromQuery] ReportPagedRequest dto)
        {
            var (areaList, returnList, data) = await _orderApplication.AcceptTypeTop10List(dto, false);

            return new { List = areaList, Data = returnList };
        }

        /// <summary>
        /// 受理类型前十导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("accept_type_top10_list-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> AcceptTypeTop10ListExport([FromBody] ExportExcelDto<ReportPagedRequest> dto)
        {
            var (areaList, returnList, data) = await _orderApplication.AcceptTypeTop10List(dto.QueryDto, true);
            var stream = ExcelHelper.CreateStream(data);
            return ExcelStreamResult(stream, "受理类型前十统计");
        }


        /// <summary>
        /// 热点类型部门统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotport-org-statistics")]
        public async Task<object> HotPortJoinOrgStatistics([FromQuery] HotPortJoinOrgStatisticsRequest dto)
        {
            var IsCenter = _sessionContext.OrgIsCenter;
            var (hotSpot, data) = await _orderRepository.HotPortJoinOrgStatistics(dto.StartTime, dto.EndTime, IsCenter, _sessionContext.OrgId);
            return new { hotSpot, data };
        }


        /// <summary>
        /// 热点类型部门统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotport-org-statistics/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportHotPortJoinOrgStatistics([FromBody] ExportHotPortJoinOrgStatisticsRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue) throw UserFriendlyException.SameMessage("请选择时间!");
            if (dto.AddColumnName is null || dto.AddColumnName.Count == 0) throw UserFriendlyException.SameMessage("导出字段不能为空");
            if (dto.AddColumnName.FirstOrDefault() != "部门名称") throw UserFriendlyException.SameMessage("导出字段第一个必须是'部门名称'");
            var IsCenter = _sessionContext.OrgIsCenter;

            var (hotSpot, list) = await _orderRepository.HotPortJoinOrgStatistics(dto.StartTime.Value, dto.EndTime.Value, IsCenter, _sessionContext.OrgId);
            var dataTable = await _orderReportApplication.ExportHotPortJoinOrgStatisticsAsync(hotSpot, list, dto.AddColumnName);

            return ExcelStreamResult(ExcelHelper.CreateStream(dataTable), "热点类型部门统计");
        }

        /// <summary>
        /// 热点类型部门统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotport-org-statistics/detail")]
        public async Task<PagedDto<OrderDto>> HotPortJoinOrgStatisticsDetail([FromQuery] HotPortJoinOrgStatisticsRequestDetail dto)
        {
            var (total, items) = await _orderRepository.HotPortJoinOrgStatisticsDetail(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 热点类型部门统计明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotport-org-statistics/detail/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotPortJoinOrgStatisticsDetailExport([FromBody] ExportExcelDto<HotPortJoinOrgStatisticsRequestDetail> dto)
        {
            var query = _orderRepository.HotPortJoinOrgStatisticsDetail(dto.QueryDto);
            List<Order> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }
            var orderDtos = _mapper.Map<IReadOnlyList<OrderDto>>(data);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "热点类型部门统计明细");
        }

        /// <summary>
        /// 回访量统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-measure-statistics-export")]
        [LogFilterAlpha("导出日志")]
        [AllowAnonymous]
        public async Task<FileStreamResult> VisitMeasureStatisticsExport([FromBody] ExportExcelDto<VisitMeasureStatisticsRequest> dto)
        {
            var query = _orderVisitRepository.Queryable()
                .Includes(x => x.Employee)
                 .Where(x => x.VisitTime >= dto.QueryDto.StartTime && x.VisitTime <= dto.QueryDto.EndTime && x.VisitState == EVisitState.Visited)
                 .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.VisitName), x => x.Employee.Name.Contains(dto.QueryDto.VisitName))
                 .GroupBy(x => new { x.EmployeeId, x.Employee.Name })
                 .Select(x => new VisitMeasureStatisticsModelDto()
                 {
                     VisitName = x.Employee.Name,
                     CallVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitType == EVisitType.CallVisit, 1, 0)),
                     ArtificialVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitType != EVisitType.CallVisit, 1, 0)),
                     SumCount = SqlFunc.AggregateCount(x.EmployeeId)
                 });
            var list = await query.ToListAsync();
            //合计
            var SumModel = new VisitMeasureStatisticsModelDto()
            {
                VisitName = "合计",
                CallVisitCount = list.Sum(x => x.CallVisitCount),
                ArtificialVisitCount = list.Sum(x => x.ArtificialVisitCount),
                SumCount = list.Sum(x => x.SumCount)
            };
            list.Add(SumModel);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<VisitMeasureStatisticsModelDto>(dto.ColumnInfos);
            var dtos = list
             .Select(stu => _mapper.Map(stu, typeof(VisitMeasureStatisticsModelDto), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "回访量统计");
        }


        /// <summary>
        /// 回访量统计
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="VisitName"></param>
        /// <returns></returns>
        [HttpGet("visit-measure-statistics")]
        public async Task<VisitMeasureStatisticsDto> VisitMeasureStatistics([FromQuery] VisitMeasureStatisticsRequest dto)
        {
            var query = _orderVisitRepository.Queryable()
                .Includes(x => x.Employee)
                 .Where(x => x.VisitTime >= dto.StartTime && x.VisitTime <= dto.EndTime && x.VisitState == EVisitState.Visited && x.EmployeeId != "" && x.EmployeeId != null)
                 .WhereIF(!string.IsNullOrEmpty(dto.VisitName), x => x.Employee.Name.Contains(dto.VisitName))
                 .GroupBy(x => new { x.EmployeeId, x.Employee.Name })
                 .Select(x => new VisitMeasureStatisticsModelDto()
                 {
                     VisitName = x.Employee.Name,
                     CallVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitType == EVisitType.CallVisit, 1, 0)),
                     ArtificialVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitType != EVisitType.CallVisit, 1, 0)),
                     SumCount = SqlFunc.AggregateCount(x.EmployeeId)
                 });
            var list = await query.ToListAsync();
            var returnModel = new VisitMeasureStatisticsDto();
            returnModel.VisitMeasureStatisticsModelList = list;

            //查询AIVisit
            returnModel.AiVisitCount = await _aiOrderVisitDetailRepository.Queryable()
                .Where(x => x.AiVisitTime >= dto.StartTime && x.AiVisitTime <= dto.EndTime && x.IsSuccess != null).CountAsync();

            returnModel.AiVisitSatisfiedCount = await _aiOrderVisitDetailRepository.Queryable()
                //.Includes(x => x.OrderVisit)
                .Where(x => x.AiVisitTime >= dto.StartTime && x.AiVisitTime <= dto.EndTime && x.IsSuccess == true && SqlFunc.JsonField(x.AiOrgProcessingResults, "Key") == "4").CountAsync();

            returnModel.AiVisitNoSatisfiedCount = await _aiOrderVisitDetailRepository.Queryable()
                //.Includes(x => x.OrderVisit)
                .Where(x => x.AiVisitTime >= dto.StartTime && x.AiVisitTime <= dto.EndTime && x.IsSuccess == true && SqlFunc.JsonField(x.AiOrgProcessingResults, "Key") == "2").CountAsync();

            returnModel.AIVisitFailCount = await _aiOrderVisitDetailRepository.Queryable()
                .Where(x => x.AiVisitTime >= dto.StartTime && x.AiVisitTime <= dto.EndTime && x.IsSuccess == false).CountAsync();


            return returnModel;
        }

        /// <summary>
        /// 智能回访不满意明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("aivisit-nosatisfied-paeglist")]
        public async Task<PagedDto<AiVisitNoSatisfiedPageListRep>> AiVisitNoSatisfiedPageList([FromQuery] AiVisitNoSatisfiedPageListRequest dto)
        {
            var (total, items) = await _aiOrderVisitDetailRepository.Queryable()
                .Includes(x => x.OrderVisit)
                .Includes(x => x.OrderVisit.Order)
                .Includes(x => x.OrderVisit.OrderVisitDetails)
                .Includes(x => x.OrderVisit.Employee)
                .Where(x => x.AiVisitTime >= dto.StartTime && x.AiVisitTime <= dto.EndTime && x.IsSuccess == true && SqlFunc.JsonField(x.AiOrgProcessingResults, "Key") == "2")
                .WhereIF(!string.IsNullOrEmpty(dto.VisitName), x => x.OrderVisit.Employee.Name.Contains(dto.VisitName))
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<AiVisitNoSatisfiedPageListRep>(total, _mapper.Map<IReadOnlyList<AiVisitNoSatisfiedPageListRep>>(items));
        }

        /// <summary>
        /// 热点类型小类统计
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="TypeId">0：全部 ，1：市民，2：企业</param>
        /// <returns></returns>
        [HttpGet("hotspot-statistics")]
        public async Task<object> HotspotStatistics([FromQuery] HotspotStatisticsRep dto)
        {
            var IsCenter = _sessionContext.OrgIsCenter;

            if (string.IsNullOrEmpty(dto.HotspotCode))
            {
                var list = await _hotspotTypeRepository.Queryable()
                .LeftJoin<Order>((it, o) => it.Id == o.HotspotId)
                .Where((it, o) => o.CreationTime >= dto.StartTime && o.CreationTime <= dto.EndTime && o.Id != null)
                .WhereIF(dto.TypeId == 1, (it, o) => o.IdentityType == EIdentityType.Citizen)
                .WhereIF(dto.TypeId == 2, (it, o) => o.IdentityType == EIdentityType.Enterprise)
                .WhereIF(IsCenter == false, (it, o) => o.ActualHandleOrgCode.StartsWith(_sessionContext.RequiredOrgId))
                .GroupBy((it, o) => new { Id = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("2")) })
                .Select((it, o) => new
                {
                    HotspotCode = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("2")),
                    SumCount = SqlFunc.AggregateCount(it.HotSpotName)
                })
                .MergeTable()
                .LeftJoin<Hotspot>((x, q) => x.HotspotCode == q.Id)
                .Select((x, q) => new
                {
                    HotspotCode = x.HotspotCode,
                    SumCount = x.SumCount,
                    HotspotName = q.HotSpotName,
                    HasChild = SqlFunc.Subqueryable<Hotspot>().Where(d => d.ParentId == x.HotspotCode).Any()
                })
                .ToListAsync();

                return list;
            }
            else
            {
                string count = (dto.HotspotCode.Length + 2).ToString();
                string countx = dto.HotspotCode.Length.ToString();
                var list = await _hotspotTypeRepository.Queryable()
                .LeftJoin<Order>((it, o) => it.Id == o.HotspotId)
                .Where((it, o) => o.CreationTime >= dto.StartTime && o.CreationTime <= dto.EndTime && it.ParentId.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(countx)) == dto.HotspotCode)
                .WhereIF(dto.TypeId == 1, (it, o) => o.IdentityType == EIdentityType.Citizen)
                .WhereIF(dto.TypeId == 2, (it, o) => o.IdentityType == EIdentityType.Enterprise)
                .WhereIF(IsCenter == false, (it, o) => o.ActualHandleOrgCode.StartsWith(_sessionContext.RequiredOrgId))
                .GroupBy((it, o) => new { Id = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)) })
                .Select((it, o) => new
                {
                    HotspotCode = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)),
                    SumCount = SqlFunc.AggregateCount(it.HotSpotName)
                })
                .MergeTable()
                .LeftJoin<Hotspot>((x, q) => x.HotspotCode == q.Id)
                .Select((x, q) => new
                {
                    HotspotCode = x.HotspotCode,
                    SumCount = x.SumCount,
                    HotspotName = q.HotSpotName,
                    HasChild = SqlFunc.Subqueryable<Hotspot>().Where(d => d.ParentId == x.HotspotCode).Any()
                })
                .ToListAsync();
                return list;

            }
        }

        /// <summary>
        /// 热点类型小类统计导出
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="TypeId">0：全部 ，1：市民，2：企业</param>
        /// <returns></returns>
        [HttpPost("hotspot-statistics/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotStatisticsExprot([FromBody] ExportExcelDto<HotspotStatisticsRep> dto)
        {
            DataTable data = new DataTable();


            if (_appOptions.Value.IsLuZhou)
            {
                data = await _orderReportApplication.HotspotStatisticsExprot_LZ(dto);
            }
            else
            {
                var IsCenter = _sessionContext.OrgIsCenter;
                if (string.IsNullOrEmpty(dto.QueryDto.HotspotCode))
                {
                    data = await _hotspotTypeRepository.Queryable()
                    .LeftJoin<Order>((it, o) => it.Id == o.HotspotId)
                    .Where((it, o) => o.CreationTime >= dto.QueryDto.StartTime && o.CreationTime <= dto.QueryDto.EndTime && o.Id != null)
                    .WhereIF(dto.QueryDto.TypeId == 1, (it, o) => o.IdentityType == EIdentityType.Citizen)
                    .WhereIF(dto.QueryDto.TypeId == 2, (it, o) => o.IdentityType == EIdentityType.Enterprise)
                    .WhereIF(IsCenter == false, (it, o) => o.ActualHandleOrgCode.StartsWith(_sessionContext.RequiredOrgId))
                    .GroupBy((it, o) => new { Id = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("2")) })
                    .Select((it, o) => new
                    {
                        HotspotCode = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("2")),
                        SumCount = SqlFunc.AggregateCount(it.HotSpotName)
                    })
                    .MergeTable()
                    .LeftJoin<Hotspot>((x, q) => x.HotspotCode == q.Id)
                    .Select((x, q) => new
                    {
                        SumCount = x.SumCount,
                        HotspotName = q.HotSpotName
                    })
                    .ToDataTableAsync();
                }
                else
                {
                    string count = (dto.QueryDto.HotspotCode.Length + 2).ToString();
                    string countx = dto.QueryDto.HotspotCode.Length.ToString();
                    data = await _hotspotTypeRepository.Queryable()
                   .LeftJoin<Order>((it, o) => it.Id == o.HotspotId)
                   .Where((it, o) => o.CreationTime >= dto.QueryDto.StartTime && o.CreationTime <= dto.QueryDto.EndTime && it.ParentId.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(countx)) == dto.QueryDto.HotspotCode)
                   .WhereIF(dto.QueryDto.TypeId == 1, (it, o) => o.IdentityType == EIdentityType.Citizen)
                   .WhereIF(dto.QueryDto.TypeId == 2, (it, o) => o.IdentityType == EIdentityType.Enterprise)
                   .WhereIF(IsCenter == false, (it, o) => o.ActualHandleOrgCode.StartsWith(_sessionContext.RequiredOrgId))
                   .GroupBy((it, o) => new { Id = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)) })
                   .Select((it, o) => new
                   {
                       HotspotCode = it.Id.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)),
                       SumCount = SqlFunc.AggregateCount(it.HotSpotName)
                   })
                   .MergeTable()
                   .LeftJoin<Hotspot>((x, q) => x.HotspotCode == q.Id)
                   .Select((x, q) => new
                   {
                       SumCount = x.SumCount,
                       HotspotName = q.HotSpotName,
                   })
                   .ToDataTableAsync();

                }
                data.Columns["HotspotName"].SetOrdinal(0);
                data.Columns["SumCount"].ColumnName = "分类统计";
                data.Columns["HotspotName"].ColumnName = "热点名称";
                //合计
                DataRow sumRow = data.NewRow();
                sumRow["热点名称"] = "合计";
                decimal totalAmount = 0;
                foreach (DataRow row in data.Rows)
                {
                    totalAmount += Convert.ToDecimal(row["分类统计"]);
                }
                sumRow["分类统计"] = totalAmount;
                data.Rows.Add(sumRow);
            }

            var stream = ExcelHelper.CreateStream(data);
            return ExcelStreamResult(stream, "热点类型小类统计");
        }

        /// <summary>
        /// 热点类型小类统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot-statistics-detail")]
        public async Task<PagedDto<OrderDto>> HotspotStatisticsDetail([FromQuery] HotspotStatisticsRep dto)
        {
            var (total, items) = await _orderApplication.HotspotStatisticsDetail(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 热点类型小类统计明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotspot-statistics-detail/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotStatisticsDetailExport([FromBody] ExportExcelDto<HotspotStatisticsRep> dto)
        {
            var query = _orderApplication.HotspotStatisticsDetail(dto.QueryDto);
            List<Order> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }
            var orderDtos = _mapper.Map<IReadOnlyList<OrderDto>>(data);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "热点类型小类统计明细");
        }

        /// <summary>
        /// 部门满意度统计表基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("visit-org-satisfaction-statisticsBaseData")]
        public async Task<object> VisitAndOrgSatisfactionStatisticsBaseData()
        {
            return new
            {
                VisitType = EnumExts.GetDescriptions<EVisitType>(),
            };
        }

        /// <summary>
        /// 坐席总体满意度分析
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("seat-satisfaction-statistics")]
        public async Task<List<SeatSatisfactionStatisticsDto>> SeatSatisfactionStatistics([FromQuery] PagedKeywordRequest dto)
        {
            return await _orderApplication.SeatSatisfactionStatistics(dto).ToListAsync();
        }

        /// <summary>
        /// 坐席总体满意度分析导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("seat-satisfaction-statistics/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SeatSatisfactionStatisticsExport([FromBody] ExportExcelDto<PagedKeywordRequest> dto)
        {
            var query = _orderApplication.SeatSatisfactionStatistics(dto.QueryDto);
            List<SeatSatisfactionStatisticsDto> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SeatSatisfactionStatisticsDto>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(SeatSatisfactionStatisticsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "坐席总体满意度分析");
        }

        /// <summary>
        /// 坐席总体满意率分析
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("seat-satisfaction-statistics-rate")]
        public async Task<SeatSatisfactionStatisticsEvaluateDto> SeatSatisfactionStatisticsRate([FromQuery] PagedKeywordRequest dto)
        {
            var data = await _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"
                )
                 .Select((od, ov, o) => new SeatSatisfactionStatisticsEvaluateDto
                 {
                     Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate != ESeatEvaluate.NoSatisfied && od.SeatEvaluate != ESeatEvaluate.VeryNoSatisfied, 1, 0)),
                     NoSatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(od.SeatEvaluate == ESeatEvaluate.NoSatisfied || od.SeatEvaluate == ESeatEvaluate.VeryNoSatisfied, 1, 0))
                 })
                 .FirstAsync();
            return data;

        }

        /// <summary>
        /// 坐席满意度明细表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("seat-satisfaction-statistics-list-detail")]
        public async Task<object> SeatSatisfactionStatisticsListDetail([FromQuery] PagedKeywordRequest dto)
        {
            var list = await _orderApplication.SeatSatisfactionStatisticsListDetail(dto).ToListAsync();

            var sumModel = new SeatSatisfactionStatisticsListDetailDto()
            {
                UserName = "合计",
                UserId = "",
                DefaultSatisfied = list.Sum(x => x.DefaultSatisfied),
                VeryNoSatisfied = list.Sum(x => x.VeryNoSatisfied),
                NoSatisfied = list.Sum(x => x.NoSatisfied),
                Normal = list.Sum(x => x.Normal),
                Satisfied = list.Sum(x => x.Satisfied),
                VerySatisfied = list.Sum(x => x.VerySatisfied),
                NoConnect = list.Sum(x => x.NoConnect),
                NoEvaluate = list.Sum(x => x.NoEvaluate),
            };
            return new { List = list, Total = sumModel };
        }

        /// <summary>
        /// 坐席总体满意度分析导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("seat-satisfaction-statistics-list-detail/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SeatSatisfactionStatisticsListDetailExport([FromBody] ExportExcelDto<PagedKeywordRequest> dto)
        {
            var query = _orderApplication.SeatSatisfactionStatisticsListDetail(dto.QueryDto);
            List<SeatSatisfactionStatisticsListDetailDto> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }
            var sumModel = new SeatSatisfactionStatisticsListDetailDto()
            {
                UserName = "合计",
                UserId = "",
                DefaultSatisfied = data.Sum(x => x.DefaultSatisfied),
                VeryNoSatisfied = data.Sum(x => x.VeryNoSatisfied),
                NoSatisfied = data.Sum(x => x.NoSatisfied),
                Normal = data.Sum(x => x.Normal),
                Satisfied = data.Sum(x => x.Satisfied),
                VerySatisfied = data.Sum(x => x.VerySatisfied),
                NoConnect = data.Sum(x => x.NoConnect),
                NoEvaluate = data.Sum(x => x.NoEvaluate),
            };
            data.Add(sumModel);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SeatSatisfactionStatisticsListDetailDto>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(SeatSatisfactionStatisticsListDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "坐席满意度明细表");
        }

        /// <summary>
        /// 坐席满意度工单明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("query-seat-satisfaction-order-visit-list")]
        public async Task<PagedDto<OrderVisitDetailDto>> QuerySeatSatisfactionOrderVisitList([FromQuery] SeatSatisfactionOrderVisitRequest dto)
        {
            var (total, items) = await _orderApplication.QuerySeatSatisfactionOrderVisitList(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<OrderVisitDetailDto>(total, _mapper.Map<IReadOnlyList<OrderVisitDetailDto>>(items));
        }

        /// <summary>
        /// 坐席满意度工单明细表基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("query-seat-satisfaction-base-data")]
        public async Task<object> QuerySeatSatisfactionBaseData()
        {
            var seatEvaluate = EnumExts.GetDescriptions<ESeatEvaluate>();
            if (_appOptions.Value.IsZiGong == true)
            {
                seatEvaluate = EnumExtensions.GetEnumKeyValueList<ESeatEvaluate>();
            }
            if (_appOptions.Value.IsZiGong == false)
            {
                seatEvaluate = seatEvaluate.Where(m => new int[] { 1, 3 }.Contains(m.Key) == false).ToList();
            }
            return new
            {
                SeatEvaluate = seatEvaluate
            };
        }

        /// <summary>
        /// 坐席满意度工单明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("query-seat-satisfaction-order-visit-list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQuerySeatSatisfactionOrderVisitList([FromBody] ExportExcelDto<SeatSatisfactionOrderVisitRequest> dto)
        {
            var query = _orderApplication.QuerySeatSatisfactionOrderVisitList(dto.QueryDto);
            List<OrderVisitDetail> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }

            var orderDtos = _mapper.Map<ICollection<OrderVisitDetailDto>>(orders);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVisitDetailDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderVisitDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "坐席满意度工单明细");
        }


        /// <summary>
        /// 部门满意度统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-org-satisfaction-statistics")]
        public async Task<VisitAndOrgSatisfactionStatisticsResultDto> VisitAndOrgSatisfactionStatistics([FromQuery] PagedKeywordSonRequest dto)
        {
            var data = await _orderApplication.VisitAndOrgSatisfactionStatistics(dto);

            var countySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "区县合计",
                TotalSumCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoPutThroughCount),
                NormalCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VeryNoSatisfiedCount),
            };

            var citySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "市直合计",
                TotalSumCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NoPutThroughCount),
                NormalCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.VeryNoSatisfiedCount),
            };

            var sumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "总计",
                TotalSumCount = data.Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Sum(x => x.NoPutThroughCount),
                NormalCount = data.Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = data.Sum(x => x.VeryNoSatisfiedCount),
            };


            return new VisitAndOrgSatisfactionStatisticsResultDto { DataList = data, CountySumModel = countySumModel, CitySumModel = citySumModel, SumModel = sumModel };
        }

        /// <summary>
        /// 部门满意度统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-org-satisfaction-statistics/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> VisitAndOrgSatisfactionStatisticsExport([FromBody] ExportExcelDto<PagedKeywordSonRequest> dto)
        {
            List<VisitAndOrgSatisfactionStatisticsDto> data = await _orderApplication.VisitAndOrgSatisfactionStatistics(dto.QueryDto);
            var countySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "区县合计",
                TotalSumCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoPutThroughCount),
                NormalCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VeryNoSatisfiedCount),
            };
            var citySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "市直合计",
                TotalSumCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NoPutThroughCount),
                NormalCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = data.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(x => x.VeryNoSatisfiedCount),
            };
            var sumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "总计",
                TotalSumCount = data.Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Sum(x => x.NoPutThroughCount),
                NormalCount = data.Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = data.Sum(x => x.VeryNoSatisfiedCount),
            };
            data.Add(countySumModel);
            data.Add(citySumModel);
            data.Add(sumModel);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<VisitAndOrgSatisfactionStatisticsDto>(dto.ColumnInfos);
            var dtos = data
             .Select(stu => _mapper.Map(stu, typeof(VisitAndOrgSatisfactionStatisticsDto), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门满意度统计数据");
        }

        /// <summary>
        /// 子部门满意度明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-org-statisfaction-org-detail")]
        public async Task<VisitAndOrgSatisfactionStatisticsResultDto> VisitAndOrgStatisfactionOrgDetail([FromQuery] PagedKeywordSonRequest dto)
        {
            var list = await _orderApplication.VisitAndOrgStatisfactionOrgDetail(dto);
            var countySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "区县合计",
                TotalSumCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.TotalSumCount),
                VerySatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoPutThroughCount),
                NormalCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VeryNoSatisfiedCount),
            };

            var citySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "市直合计",
                TotalSumCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.TotalSumCount),
                VerySatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NoPutThroughCount),
                NormalCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.VeryNoSatisfiedCount),
            };

            var sumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "总计",
                TotalSumCount = list.Sum(x => x.TotalSumCount),
                VerySatisfiedCount = list.Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = list.Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = list.Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = list.Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = list.Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = list.Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = list.Sum(x => x.NoPutThroughCount),
                NormalCount = list.Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = list.Sum(x => x.VeryNoSatisfiedCount),
            };

            return new VisitAndOrgSatisfactionStatisticsResultDto { DataList = list, CountySumModel = countySumModel, CitySumModel = citySumModel, SumModel = sumModel };
        }

        /// <summary>
        /// 部门满意度统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-org-statisfaction-org-detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> VisitAndOrgStatisfactionOrgDetailExport([FromBody] ExportExcelDto<PagedKeywordSonRequest> dto)
        {
            var list = await _orderApplication.VisitAndOrgStatisfactionOrgDetail(dto.QueryDto);
            var countySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "区县合计",
                TotalSumCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.TotalSumCount),
                VerySatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NoPutThroughCount),
                NormalCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.County).Sum(x => x.VeryNoSatisfiedCount),
            };
            var citySumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "市直合计",
                TotalSumCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.TotalSumCount),
                VerySatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NoPutThroughCount),
                NormalCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = list.Where(x => x.OrgType == EOrgType.City).Sum(x => x.VeryNoSatisfiedCount),
            };
            var sumModel = new VisitAndOrgSatisfactionStatisticsDto()
            {
                OrgName = "总计",
                TotalSumCount = list.Sum(x => x.TotalSumCount),
                VerySatisfiedCount = list.Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = list.Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = list.Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = list.Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = list.Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = list.Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = list.Sum(x => x.NoPutThroughCount),
                NormalCount = list.Sum(x => x.NormalCount),
                VeryNoSatisfiedCount = list.Sum(x => x.VeryNoSatisfiedCount),
            };
            list.Add(countySumModel);
            list.Add(citySumModel);
            list.Add(sumModel);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<VisitAndOrgSatisfactionStatisticsDto>(dto.ColumnInfos);
            var dtos = list
             .Select(stu => _mapper.Map(stu, typeof(VisitAndOrgSatisfactionStatisticsDto), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门满意度统计数据");
        }

        /// <summary>
        /// 部门满意度明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-org-satisfaction-detail")]
        public async Task<PagedDto<OrgVisitDetailListResp>> VisitAndOrgSatisfactionDetail([FromQuery] VisitAndOrgSatisfactionDetailDto dto)
        {
            //var (total, items) = await _orderApplication.VisitAndOrgSatisfactionDetail(dto)
            var (total, items) = await _orderRepository.VisitAndOrgSatisfactionDetail(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrgVisitDetailListResp>(total, _mapper.Map<IReadOnlyList<OrgVisitDetailListResp>>(items));
        }

        /// <summary>
        /// 部门满意度明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-org-satisfaction-detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> VisitAndOrgSatisfactionDetailExport([FromBody] ExportExcelDto<VisitAndOrgSatisfactionDetailDto> dto)
        {
            var query = _orderRepository.VisitAndOrgSatisfactionDetail(dto.QueryDto);
            List<OrgVisitDetailListResp> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }


            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrgVisitDetailListResp>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(OrgVisitDetailListResp), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门满意度明细数据");
        }

        /// <summary>
        /// 中心报表统计--宜宾
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        [HttpGet("center_report_forms_statistics")]
        public async Task<CenterReportStatisticsDto> CenterReportFormsStatistics(DateTime StartTime, DateTime EndTime)
        {
            CenterReportStatisticsDto centerReportStatisticsDto = new();

            //信件总量
            int sourceChannelCount = await _orderRepository.Queryable().Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime).CountAsync();

            // 查询工单老数据
            DataTable listOld = null;
            // 查询类型老数据
            DataTable listPurOld = null;
            // 查询部门老数据
            DataTable listCity = null;
            DataTable listCounty = null;
            // 查询老数据详情
            DataTable listInfo = null;

            var oldRun = _systemSettingCacheManager.GetSetting(SettingConstants.IsGetOld)?.SettingValue[0];
            if (oldRun == "true")
            {
                // 查询工单老数据
                listOld = await _orderRepository.CenterReportFormsStatistics(StartTime, EndTime);
                // 查询类型老数据
                listPurOld = await _orderRepository.CenterReportPurTypeStatistics(StartTime, EndTime);
                // 查询部门老数据
                listCity = await _orderRepository.CenterReportDepartStatistics(StartTime, EndTime, "市直部门");
                listCounty = await _orderRepository.CenterReportDepartStatistics(StartTime, EndTime, "区县部门");
                // 查询老数据详情
                listInfo = await _orderRepository.CenterReportNewStatistics(StartTime, EndTime);
            }


            #region 通话记录
            //通话记录
            var callData = await _trCallRecordRepository.Queryable()
                .Where(p => p.CreatedTime >= StartTime && p.CreatedTime <= EndTime && p.Gateway != "82826886" && SqlFunc.Length(p.Gateway) != 4)
                .Select(o => new CenterReportCallDto
                {
                    EffectiveCount = SqlFunc.AggregateSum(SqlFunc.IIF(o.OnState == EOnState.On, 1, 0)),//有效
                    InTotal = SqlFunc.AggregateSum(SqlFunc.IIF(o.CallDirection == ECallDirection.In, 1, 0)),//呼入总量
                    OutTotal = SqlFunc.AggregateSum(SqlFunc.IIF(o.CallDirection == ECallDirection.Out, 1, 0)),//呼出总量
                    InConnectionQuantity = SqlFunc.AggregateSum(SqlFunc.IIF(o.CallDirection == ECallDirection.In && o.AnsweredTime != null, 1, 0)),//呼入接通量
                    OutConnectionQuantity = SqlFunc.AggregateSum(SqlFunc.IIF(o.TelNo != "0" && o.CallDirection == ECallDirection.Out && o.AnsweredTime != null, 1, 0)),//呼出接通量
                    InvalidCount = SqlFunc.AggregateSum(SqlFunc.IIF(o.OnState == EOnState.NoOn /*&& o.BeginIvrTime.HasValue && o.BeginQueueTime.HasValue && o.BeginRingTime.HasValue*/, 1, 0)), //无效(排除队列挂断和IVR挂断)
                    QueueByeCount = SqlFunc.AggregateSum(SqlFunc.IIF(o.CallDirection == ECallDirection.In && o.QueueTims > 0 && o.RingTimes == 0 && o.OnState == EOnState.NoOn, 1, 0)), //队列挂断
                    IvrByeCount = SqlFunc.AggregateSum(SqlFunc.IIF(o.CallDirection == ECallDirection.In && o.BeginIvrTime.HasValue && !o.BeginQueueTime.HasValue && !o.BeginRingTime.HasValue && o.OnState == EOnState.NoOn, 1, 0)), //IVR挂断
                })
                .FirstAsync();
            if (callData != null)
                callData.InvalidCount = callData.InvalidCount - callData.QueueByeCount - callData.IvrByeCount;

            if (listOld != null && listOld.Rows.Count > 0 && callData != null)
            {
                callData.EffectiveCount = callData.EffectiveCount + Convert.ToInt32(listOld.Rows[0]["CallInConn"]);   // 有效
                callData.InvalidCount = callData.InvalidCount + Convert.ToInt32(listOld.Rows[0]["CallInNotConn"]);    // 无效
                callData.QueueByeCount = callData.QueueByeCount + Convert.ToInt32(listOld.Rows[0]["CallInQueue"]);    // 队列挂断
                callData.IvrByeCount = callData.IvrByeCount + Convert.ToInt32(listOld.Rows[0]["CallInIVR"]);          // IVR挂断
            }

            centerReportStatisticsDto.CenterReportCall = callData;
            #endregion

            #region 语音分类
            var callTypeDto = await _trCallRecordRepository.Queryable()
            .Where(x => x.CreatedTime >= StartTime && x.CreatedTime <= EndTime && SqlFunc.Length(x.Gateway) > 4 && x.CallDirection == ECallDirection.In)
            .GroupBy(x => x.CreatedTime.ToString("yyyy-MM-dd"))
                .Select(x => new IVRCallTypeDto()
                {
                    PersonCallInCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.IvrDtmf.Substring(x.IvrDtmf.Length - 1, 1) == "1", 1, 0)),
                    EnterpriseCallInCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.IvrDtmf.Substring(x.IvrDtmf.Length - 1, 1) == "2", 1, 0)),
                    AiCallInCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Gateway == "82826886", 1, 0)),
                }).FirstAsync();
            centerReportStatisticsDto.iVRCallTypeDto = callTypeDto;
            #endregion

            #region 工单
            //工单 信件情况
            var orderData = await _orderRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.ActualHandleOrgCode == so.Id)
                .Where((x, so) => x.CreationTime >= StartTime && x.CreationTime <= EndTime)
                .Select((x, so) => new CenterReportOrderDto
                {
                    EffectiveCount = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),
                    InvalidCount = 0,
                    CompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed, 1, 0)),
                    InProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed, 1, 0)),
                    CityAccept = SqlFunc.AggregateSum(SqlFunc.IIF(so.OrgType == EOrgType.City, 1, 0)),
                    CountyAccept = SqlFunc.AggregateSum(SqlFunc.IIF(so.OrgType == EOrgType.County, 1, 0)),
                    CenterAccept = SqlFunc.AggregateSum(SqlFunc.IIF(so.IsCenter, 1, 0)),
                })
                .FirstAsync();

            if (listOld != null && listOld.Rows.Count > 0 && orderData != null)
            {
                orderData.EffectiveCount = orderData.EffectiveCount + Convert.ToInt32(listOld.Rows[0]["OrderNormalNum"]);   // 有效
                orderData.InvalidCount = orderData.InvalidCount + Convert.ToInt32(listOld.Rows[0]["OrderInvalidNum"]);      // 无效
                orderData.CompletedCount = orderData.CompletedCount + Convert.ToInt32(listOld.Rows[0]["OrderEndNum"]);      // 已办
                orderData.InProgressCount = orderData.InProgressCount + Convert.ToInt32(listOld.Rows[0]["OrderWaitNum"]);   // 在办
            }
            if (listInfo != null && listOld.Rows.Count > 0 && orderData != null)
            {
                orderData.CityAccept = orderData.CityAccept + Convert.ToInt32(listInfo.Rows[0]["OrderCityCount"]);           // 市级部门受理
                orderData.CountyAccept = orderData.CountyAccept + Convert.ToInt32(listInfo.Rows[0]["OrderCountyCount"]);     // 县（区）受理
                orderData.CenterAccept = orderData.CenterAccept + Convert.ToInt32(listInfo.Rows[0]["OrderCenterCount"]);     // 12345中心受理
            }

            centerReportStatisticsDto.CenterReportOrder = orderData;


            //工单按时办结情况
            var orderCompletedData = await _orderRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.FileUserOrgId == so.Id)
                .Where((x, so) => x.CreationTime >= StartTime && x.CreationTime <= EndTime && x.Status >= EOrderStatus.Filed)
                .Select((x, so) => new OrderCompletedDto
                {
                    CompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed, 1, 0)),
                    ExpiredTimeCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.ActualHandleTime, 1, 0)),//超期已办
                    CityExpiredTimeCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.ActualHandleTime && so.OrgType == EOrgType.City, 1, 0)),//市级超期已办
                    CountyExpiredTimeCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.ActualHandleTime && so.OrgType == EOrgType.County, 1, 0)),//区县超期已办
                    CenterExpiredTimeCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ExpiredTime < x.ActualHandleTime && so.IsCenter, 1, 0)),//中心超期已办
                    CityCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && so.OrgType == EOrgType.City, 1, 0)),
                    CountyCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && so.OrgType == EOrgType.County, 1, 0)),
                    CenterCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && so.IsCenter, 1, 0)),
                })
                .FirstAsync();

            if (listInfo != null && listInfo.Rows.Count > 0 && orderCompletedData != null)
            {
                orderCompletedData.ExpiredTimeCompletedCount = orderCompletedData.ExpiredTimeCompletedCount + Convert.ToInt32(listInfo.Rows[0]["OrderAlready"]) - Convert.ToInt32(listInfo.Rows[0]["CompleteOnTime"]);
                orderCompletedData.CityExpiredTimeCompletedCount = orderCompletedData.CityExpiredTimeCompletedCount + Convert.ToInt32(listInfo.Rows[0]["CityAlready"]) - Convert.ToInt32(listInfo.Rows[0]["CityCompleteOnTime"]);
                orderCompletedData.CountyExpiredTimeCompletedCount = orderCompletedData.CountyExpiredTimeCompletedCount + Convert.ToInt32(listInfo.Rows[0]["CountyAlready"]) - Convert.ToInt32(listInfo.Rows[0]["CountyCompleteOnTime"]);
                orderCompletedData.CenterExpiredTimeCompletedCount = orderCompletedData.CenterExpiredTimeCompletedCount + Convert.ToInt32(listInfo.Rows[0]["CenterAlready"]) - Convert.ToInt32(listInfo.Rows[0]["CenterCompleteOnTime"]);
                orderCompletedData.CityCompletedCount = orderCompletedData.CityCompletedCount + Convert.ToInt32(listInfo.Rows[0]["CityAlready"]);
                orderCompletedData.CountyCompletedCount = orderCompletedData.CountyCompletedCount + Convert.ToInt32(listInfo.Rows[0]["CountyAlready"]);
                orderCompletedData.CenterCompletedCount = orderCompletedData.CenterCompletedCount + Convert.ToInt32(listInfo.Rows[0]["CenterAlready"]);
            }

            centerReportStatisticsDto.OrderCompletedDto = orderCompletedData;

            //工单办理时效
            var orderAgingData = await _orderRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.FileUserOrgId == so.Id)
                .Where((x, so) => x.CreationTime >= StartTime && x.CreationTime <= EndTime && x.Status >= EOrderStatus.Filed)
                .Select((x, so) => new
                {
                    FileOrgIsCenter = x.FileOrgIsCenter.Value,
                    CreationTimeHandleDurationWorkday = x.CreationTimeHandleDurationWorkday.HasValue ? x.CreationTimeHandleDurationWorkday : 0,
                    CenterToOrgHandleDurationWorkday = x.CenterToOrgHandleDurationWorkday.HasValue ? x.CenterToOrgHandleDurationWorkday : 0,
                    OrgType = so.OrgType
                })
                .MergeTable()
                .Select(temp => new OrderAgingDto
                {
                    OrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),
                    CompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter, temp.CreationTimeHandleDurationWorkday, temp.CenterToOrgHandleDurationWorkday)),
                    CityOrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.City, 1, 0)),//市级
                    CityCompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.City, temp.CenterToOrgHandleDurationWorkday, 0)),
                    CountyOrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.County, 1, 0)),//区县
                    CountyCompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.County, temp.CenterToOrgHandleDurationWorkday, 0)),
                    CenterOrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter, 1, 0)),//中心
                    CenterCompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter, temp.CreationTimeHandleDurationWorkday, 0)),
                })
                .FirstAsync();

            if (listInfo != null && listInfo.Rows.Count > 0 && orderAgingData != null)
            {
                orderAgingData.OrderCount = orderAgingData.OrderCount + Convert.ToInt32(listInfo.Rows[0]["AllCount"]);
                orderAgingData.CompletedAging = orderAgingData.CompletedAging + Convert.ToInt32(listInfo.Rows[0]["OrderWorkTime"]);
                orderAgingData.CityOrderCount = orderAgingData.CityOrderCount + Convert.ToInt32(listInfo.Rows[0]["OrderCityCount"]);
                orderAgingData.CityCompletedAging = orderAgingData.CityCompletedAging + Convert.ToInt32(listInfo.Rows[0]["CityWorkTime"]);
                orderAgingData.CountyOrderCount = orderAgingData.CountyOrderCount + Convert.ToInt32(listInfo.Rows[0]["OrderCountyCount"]);
                orderAgingData.CountyCompletedAging = orderAgingData.CountyCompletedAging + Convert.ToInt32(listInfo.Rows[0]["CountyWorkTime"]);
                orderAgingData.CenterOrderCount = orderAgingData.CenterOrderCount + Convert.ToInt32(listInfo.Rows[0]["OrderCenterCount"]);
                orderAgingData.CenterCompletedAging = orderAgingData.CenterCompletedAging + Convert.ToInt32(listInfo.Rows[0]["CenterWorkTime"]);
            }

            centerReportStatisticsDto.OrderAgingDto = orderAgingData;
            #endregion

            #region 信件来源
            //信件来源
            var sourceChannelData = await _orderRepository.Queryable()
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(it => new
                {
                    SourceChannelCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.SourceChannelCode), "QT", it.SourceChannelCode)
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(it => new { it.SourceChannelCode })//对新表进行分组
                 .Select(it => new CenterReportOrderSourceChannelDto
                 {
                     Code = it.SourceChannelCode,
                     CountNum = SqlFunc.AggregateCount(it.SourceChannelCode)
                 })
                 .ToListAsync();
            List<CenterReportOrderSourceChannelDto> sourceChannel = new()
            {
                new CenterReportOrderSourceChannelDto
                {
                    AllCountNum = sourceChannelCount,
                    Name = "来源总量",
                    Code = "All",
                    CountNum = sourceChannelCount
                }
            };
            var sourceChannelDic = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.SourceChannel);
            foreach (var item in sourceChannelDic)
            {
                sourceChannel.Add(new CenterReportOrderSourceChannelDto
                {
                    AllCountNum = sourceChannelCount,
                    Name = item.DicDataName,
                    Code = item.DicTypeCode,
                    CountNum = sourceChannelData.Find(p => p.Code == item.DicDataValue)?.CountNum ?? 0
                });
            }

            if (listOld != null && listOld.Rows.Count > 0 && sourceChannel != null)
            {
                foreach (var item in sourceChannel)
                {
                    if (item.Code == "All")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromAllNum"]);            //总量
                    else if (item.Code == "YTW")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromInternet"]);          // 英特网
                    else if (item.Code == "RGDH")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPhone"]);             // 电话
                    else if (item.Code == "YBS")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformYBS"]);       // 宜办事
                    else if (item.Code == "QT")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromOther"]);             // 其他
                    else if (item.Code == "ZJ")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromSelfBuild"]);         // 自建
                    else if (item.Code == "WX")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromWeChat"]);            // 微信
                    else if (item.Code == "WB")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromWeibo"]);             // 微博
                    else if (item.Code == "AP")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromApp"]);               // APP
                    else if (item.Code == "ZHYB")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromSmartYibin"]);        // 智慧宜宾
                    else if (item.Code == "ZZPT")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformZZ"]);        // 综治平台
                    else if (item.Code == "S12328")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatform12328"]);     // 省12328平台
                    else if (item.Code == "SZYSM")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromMayorNetizen"]);      // 市长与市民
                    else if (item.Code == "YBRMT")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformRMT"]);       // 宜宾融媒体
                    else if (item.Code == "S12345")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformProvince"]);  // 省12345平台
                    else if (item.Code == "SZMHD")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformZMHD"]);      // 省政民互动
                    else if (item.Code == "SZHZ")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformSZHZ"]);      // 市州互转
                    else if (item.Code == "YB110")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatform110"]);       // 宜宾110平台
                    else if (item.Code == "SMZXBNCS")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformBBCS"]);      // 市民中心办不成事窗口
                    else if (item.Code == "IYB")
                        item.CountNum = item.CountNum + Convert.ToInt32(listOld.Rows[0]["FromPlatformIYB"]);       // i宜宾
                }
            }

            centerReportStatisticsDto.CenterReportOrderSourceChannels = sourceChannel;
            #endregion

            #region 信件分类
            //信件来源
            var acceptTypeData = await _orderRepository.Queryable(false, false, false)
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(it => new
                {
                    AcceptTypeCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.AcceptTypeCode), "40", it.AcceptTypeCode),
                    FileOrgIsCenter = it.FileOrgIsCenter.HasValue ? it.FileOrgIsCenter : true,
                    CreationTimeHandleDurationWorkday = it.CreationTimeHandleDurationWorkday.HasValue ? it.CenterToOrgHandleDurationWorkday : 0,
                    CenterToOrgHandleDurationWorkday = it.CenterToOrgHandleDurationWorkday.HasValue ? it.CenterToOrgHandleDurationWorkday : 0,
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(temp => new { temp.AcceptTypeCode })//对新表进行分组
                 .Select(temp => new CenterReportOrderSourceChannelDto
                 {
                     Code = temp.AcceptTypeCode,
                     CountNum = SqlFunc.AggregateCount(temp.AcceptTypeCode),
                     CompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == true, temp.CreationTimeHandleDurationWorkday, temp.CenterToOrgHandleDurationWorkday))
                 })
                 .ToListAsync();
            List<CenterReportOrderSourceChannelDto> acceptType = new();
            var acceptTypeDic = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.AcceptType);
            foreach (var item in acceptTypeDic)
            {
                acceptType.Add(new CenterReportOrderSourceChannelDto
                {
                    AllCountNum = sourceChannelCount,
                    Name = item.DicDataName,
                    Code = item.DicTypeCode,
                    CountNum = acceptTypeData.Find(p => p.Code == item.DicDataValue)?.CountNum ?? 0,
                    CompletedAging = acceptTypeData.Find(p => p.Code == item.DicDataValue)?.CompletedAging ?? 0
                });
            }

            if (listPurOld != null && listPurOld.Rows.Count > 0 && acceptType != null)
            {
                foreach (var item in acceptType)
                {
                    if (item.Code == "10")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Consult"]);            // 咨询
                    else if (item.Code == "15")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Suggest"]);            // 建议
                    else if (item.Code == "20")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["SeekHelp"]);           // 求助
                    else if (item.Code == "25")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Praise"]);             // 表扬
                    else if (item.Code == "30")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Report"]);             // 举报
                    else if (item.Code == "35")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Complaint"]);          // 投诉
                }
            }

            centerReportStatisticsDto.CenterReportOrderAcceptTypes = acceptType;
            #endregion

            #region 信件回访量
            //信件回访量
            CenterReportVisitdDto centerReportVisitd = new()
            {
                Visitd = await _orderVisitRepository.Queryable()
              .Where(x => x.VisitTime >= StartTime && x.VisitTime <= EndTime && x.VisitState == EVisitState.Visited).CountAsync(),
                WaitVisitd = await _orderVisitRepository.Queryable()
             .Where(x => x.CreationTime >= StartTime && x.CreationTime <= EndTime && x.VisitState != EVisitState.None && x.VisitState != EVisitState.Visited).CountAsync()
            };
            //
            var query = _orderVisitDetailRepository.Queryable()
                .LeftJoin<OrderVisit>((it, o) => it.VisitId == o.Id)
                .LeftJoin<SystemOrganize>((it, o, so) => it.VisitOrgCode == so.Id)
                .Where((it, o, so) => it.VisitTarget == EVisitTarget.Org && o.VisitTime >= StartTime && o.VisitTime <= EndTime && o.VisitState == EVisitState.Visited)
                 .Select((it, o, so) => new
                 {
                     Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2", 1, 0)),
                     Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2", 0, 1)),
                     CityDissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF((SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.City, 1, 0)),
                     CitySatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.City, 1, 0)),
                     CountyDissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF((SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.County, 1, 0)),
                     CountySatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.County, 1, 0)),
                     CenterDissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF((SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.IsCenter, 1, 0)),
                     CenterSatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.IsCenter, 1, 0)),
                     OrgDissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF((SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && !so.IsCenter, 1, 0)),
                     OrgSatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && !so.IsCenter, 1, 0)),
                 });
            Console.Write(query.ToSqlString());
            var data = await query.FirstAsync();
            if (data.Satisfied > 0)
            {
                var count = data.Satisfied + data.Dissatisfied;
                centerReportVisitd.AllRate = Math.Round((data.Satisfied / (double)count) * 100, 2);
            }
            if (data.OrgSatisfied > 0)
            {
                var count = data.OrgSatisfied + data.OrgDissatisfied;
                centerReportVisitd.OrgRate = Math.Round((data.OrgSatisfied / (double)count) * 100, 2);
            }

            if (data.CitySatisfied > 0)
            {
                var count = data.CitySatisfied + data.CityDissatisfied;
                centerReportVisitd.CityRate = Math.Round((data.CitySatisfied / (double)count) * 100, 2);
            }

            if (data.CountySatisfied > 0)
            {
                var count = data.CountySatisfied + data.CountyDissatisfied;
                centerReportVisitd.CountyRate = Math.Round((data.CountySatisfied / (double)count) * 100, 2);
            }

            if (data.CenterSatisfied > 0)
            {
                var count = data.CenterSatisfied + data.CenterDissatisfied;
                centerReportVisitd.CenterRate = Math.Round((data.CenterSatisfied / (double)count) * 100, 2);
            }
            centerReportVisitd.Dissatisfied = data.Dissatisfied;
            centerReportVisitd.CityDissatisfied = data.CityDissatisfied;
            centerReportVisitd.CountyDissatisfied = data.CountyDissatisfied;

            if (listOld != null && listOld.Rows.Count > 0 && centerReportVisitd != null)
            {
                centerReportVisitd.Visitd = centerReportVisitd.Visitd + Convert.ToInt32(listOld.Rows[0]["VisitAlreadyNum"]);                    // 已回访
                centerReportVisitd.WaitVisitd = centerReportVisitd.WaitVisitd + Convert.ToInt32(listOld.Rows[0]["VisitWaitNum"]);               // 待回访
                centerReportVisitd.SeatsRate = Math.Round((centerReportVisitd.SeatsRate + Convert.ToDouble(listOld.Rows[0]["SatisfactionSeat"])) / 2, 2);      // 坐席满意度
                centerReportVisitd.OrgRate = Math.Round((centerReportVisitd.OrgRate + Convert.ToDouble(listOld.Rows[0]["SatisfactionDepartment"])) / 2, 2);   // 部门满意度
            }

            if (listInfo != null && listInfo.Rows.Count > 0 && centerReportVisitd != null)
            {
                //总体满意率
                centerReportVisitd.AllRate = Math.Round(centerReportVisitd.AllRate + Convert.ToDouble(listInfo.Rows[0]["SatisfactionRate"]) / 2, 2);
                //市级部门满意率
                centerReportVisitd.CityRate = Math.Round(centerReportVisitd.CityRate + Convert.ToDouble(listInfo.Rows[0]["CitySatisfactionRate"]) / 2, 2);
                //县（区）满意率
                centerReportVisitd.CountyRate = Math.Round(centerReportVisitd.CountyRate + Convert.ToDouble(listInfo.Rows[0]["CountySatisfactionRate"]) / 2, 2);
                //不满意件
                centerReportVisitd.Dissatisfied = centerReportVisitd.Dissatisfied + Convert.ToInt32(listInfo.Rows[0]["SatisfactionCount"]);
                //市级部门不满意件
                centerReportVisitd.CityDissatisfied = centerReportVisitd.CityDissatisfied + Convert.ToInt32(listInfo.Rows[0]["CenterSatisfactionCount"]);
                //县（区）不满意件
                centerReportVisitd.CountyDissatisfied = centerReportVisitd.CountyDissatisfied + Convert.ToInt32(listInfo.Rows[0]["CountySatisfactionCount"]);
            }

            //部门
            //var listOrg = await _orderVisitDetailRepository.Queryable()
            //    .LeftJoin<OrderVisit>((it, o) => it.VisitId == o.Id)
            //    .Where((it, o) => it.VisitTarget == EVisitTarget.Org && o.VisitTime >= StartTime && o.VisitTime <= EndTime && o.VisitState == EVisitState.Visited)
            //     .Select((it, o) => new Satisfaction
            //     {
            //         Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonListObjectAny(it.OrgProcessingResults, "key", "1") || SqlFunc.JsonListObjectAny(it.OrgProcessingResults, "key", "2"), 1, 0)),
            //         Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonListObjectAny(it.OrgProcessingResults, "key", "1") || SqlFunc.JsonListObjectAny(it.OrgProcessingResults, "key", "2"), 0, 1)),
            //     })
            //    .ToListAsync();

            //if (listOrg != null && listOrg.Count > 0)
            //{
            //    var SatisfiedCount = listOrg[0].Satisfied + listOrg[0].Satisfied;
            //    if (SatisfiedCount > 0 && listOrg[0].Satisfied > 0)
            //        centerReportVisitd.OrgRate = Math.Round((listOrg[0].Satisfied / (double)SatisfiedCount) * 100, 2);
            //}

            ////if (centerReportVisitd.Visitd > 0 && listOrg != null && listOrg.Count > 0 && listOrg[0].Satisfied > 0)
            ////centerReportVisitd.OrgRate = Math.Round((listOrg[0].Satisfied / (double)centerReportVisitd.Visitd) * 100, 2);

            ////坐席
            //var listSet = await _orderVisitDetailRepository.Queryable()
            //    .LeftJoin<OrderVisit>((it, o) => it.VisitId == o.Id)
            //    .Where((it, o) => it.VisitTarget == EVisitTarget.Seat && o.VisitTime >= StartTime && o.VisitTime <= EndTime && o.VisitState == EVisitState.Visited)
            //    .Select((it, o) => new Satisfaction
            //    {
            //        Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(it.SeatEvaluate == ESeatEvaluate.NoSatisfied, 1, 0)),
            //        Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(it.SeatEvaluate != ESeatEvaluate.NoSatisfied, 1, 0)),
            //    }).ToListAsync();

            //if (listSet != null && listSet.Count > 0)
            //{
            //    var SatisfiedCount = listSet[0].Satisfied + listSet[0].Satisfied;
            //    if (SatisfiedCount > 0 && listSet[0].Satisfied > 0)
            //        centerReportVisitd.OrgRate = Math.Round((listSet[0].Satisfied / (double)SatisfiedCount) * 100, 2);
            //}

            //if (centerReportVisitd.Visitd > 0 && listSet != null && listSet.Count > 0 && listSet[0].Satisfied > 0)
            //    centerReportVisitd.SeatsRate = Math.Round((listSet[0].Satisfied / (double)centerReportVisitd.Visitd) * 100, 2);

            centerReportStatisticsDto.CenterReportVisitd = centerReportVisitd;
            #endregion

            #region 信件分布情况
            //市直部门

            var listOrgStatisticsCityAll = await _orderRepository.Queryable()
                .Where(o => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .Select(o => new
                {
                    OrgCode = o.ActualHandleOrgCode == null || o.ActualHandleOrgCode == "" ? "001" : o.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((o, s) => o.OrgCode == s.Id)
                 .Where((o, s) => s.OrgType == EOrgType.City || s.OrgType == EOrgType.Province)
                .GroupBy((o, s) => new
                {
                    o.OrgCode,
                    s.Name
                })
                .Select((o, s) => new OrgStatistics
                {
                    CountNum = SqlFunc.AggregateCount(o.OrgCode),

                    OrgName = s.Name
                }).ToListAsync();

            if (listCity != null && listOrgStatisticsCityAll != null)
            {
                var arrOrgCode = "";
                foreach (var item in listOrgStatisticsCityAll)
                {
                    for (int i = 0; i < listCity.Rows.Count; i++)
                    {
                        var orgCode1 = item.OrgCode;
                        var orgCode2 = listCity.Rows[i]["OrgCode"].ToString();
                        if (orgCode1 == orgCode2)
                        {
                            arrOrgCode += "'" + orgCode1 + "',";
                            item.CountNum = item.CountNum + Convert.ToInt32(listCity.Rows[i]["OrderAllNum"]);
                        }
                    }
                }
                for (int i = 0; i < listCity.Rows.Count; i++)
                {
                    var orgCode = listCity.Rows[i]["OrgCode"].ToString();
                    if (arrOrgCode.IndexOf("'" + orgCode + "'") == -1)
                    {
                        listOrgStatisticsCityAll.Add(
                        new OrgStatistics
                        {
                            OrgCode = listCity.Rows[i]["OrgCode"].ToString(),
                            OrgName = listCity.Rows[i]["Name"].ToString(),
                            CountNum = Convert.ToInt32(listCity.Rows[i]["OrderAllNum"])
                        });
                    }
                }
            }


            centerReportStatisticsDto.OrgStatisticsCityAll = new OrgStatisticsAll
            {
                OrgStatistics = listOrgStatisticsCityAll
            };

            //区县部门
            var listOrgStatisticsAreaAll = await _orderRepository.Queryable()
                .Where(o => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .Select(o => new
                {
                    OrgCode = o.ActualHandleOrgCode == null || o.ActualHandleOrgCode == "" ? "001" : o.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((o, s) => o.OrgCode == s.Id)
                 .Where((o, s) => s.OrgType == EOrgType.County)
                .GroupBy((o, s) => new
                {
                    o.OrgCode,
                    s.Name
                })
                .Select((o, s) => new OrgStatistics
                {
                    CountNum = SqlFunc.AggregateCount(o.OrgCode),

                    OrgName = s.Name
                }).ToListAsync();


            if (listCounty != null && listOrgStatisticsAreaAll != null)
            {
                var arrOrgCode = "";
                foreach (var item in listOrgStatisticsAreaAll)
                {
                    for (int i = 0; i < listCounty.Rows.Count; i++)
                    {
                        var orgCode1 = item.OrgCode;
                        var orgCode2 = listCounty.Rows[i]["OrgCode"].ToString();
                        if (orgCode1 == orgCode2)
                        {
                            arrOrgCode += "'" + orgCode1 + "',";
                            item.CountNum = item.CountNum + Convert.ToInt32(listCounty.Rows[i]["OrderAllNum"]);
                        }
                    }
                }
                for (int i = 0; i < listCounty.Rows.Count; i++)
                {
                    var orgCode = listCounty.Rows[i]["OrgCode"].ToString();
                    if (arrOrgCode.IndexOf("'" + orgCode + "'") == -1)
                    {
                        listOrgStatisticsAreaAll.Add(
                        new OrgStatistics
                        {
                            OrgCode = listCounty.Rows[i]["OrgCode"].ToString(),
                            OrgName = listCounty.Rows[i]["Name"].ToString(),
                            CountNum = Convert.ToInt32(listCounty.Rows[i]["OrderAllNum"])
                        });
                    }
                }
            }

            centerReportStatisticsDto.OrgStatisticsAreaAll = new OrgStatisticsAll
            {
                OrgStatistics = listOrgStatisticsAreaAll
            };
            #endregion

            #region 企业服务办件情况

            //工单 信件情况
            var enterpriseOrderData = await _orderRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.ActualHandleOrgCode == so.Id)
                .Where((x, so) => x.CreationTime >= StartTime && x.CreationTime <= EndTime && x.IdentityType == EIdentityType.Enterprise)
                .Select((x, so) => new EnterpriseOrderDto
                {
                    InProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed, 1, 0)),
                    CompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed, 1, 0)),
                    CenterCount = SqlFunc.AggregateSum(SqlFunc.IIF(so.IsCenter, 1, 0)),
                    CityCount = SqlFunc.AggregateSum(SqlFunc.IIF(so.OrgType == EOrgType.City, 1, 0)),
                    CountyCount = SqlFunc.AggregateSum(SqlFunc.IIF(so.OrgType == EOrgType.County, 1, 0)),
                })
                .FirstAsync();

            var enterpriseOrderDto = await _orderRepository.Queryable()
                .LeftJoin<SystemOrganize>((x, so) => x.ActualHandleOrgCode == so.Id)
                .Where((x, so) => x.CreationTime >= StartTime && x.CreationTime <= EndTime && x.IdentityType == EIdentityType.Enterprise)
                .Select((x, so) => new
                {
                    FileOrgIsCenter = x.FileOrgIsCenter.Value,
                    CreationTimeHandleDurationWorkday = x.CreationTimeHandleDurationWorkday.HasValue ? x.CreationTimeHandleDurationWorkday : 0,
                    CenterToOrgHandleDurationWorkday = x.CenterToOrgHandleDurationWorkday.HasValue ? x.CenterToOrgHandleDurationWorkday : 0,
                    OrgType = so.OrgType
                })
                .MergeTable()
                .Select(temp => new EnterpriseOrderDto
                {
                    OrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),
                    CompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter, temp.CreationTimeHandleDurationWorkday, temp.CenterToOrgHandleDurationWorkday)),
                    CityOrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.City, 1, 0)),//市级
                    CityCompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.City, temp.CenterToOrgHandleDurationWorkday, 0)),
                    CountyOrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.County, 1, 0)),//区县
                    CountyCompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == false && temp.OrgType == EOrgType.County, temp.CenterToOrgHandleDurationWorkday, 0)),
                    CenterOrderCount = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter, 1, 0)),//中心
                    CenterCompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter, temp.CreationTimeHandleDurationWorkday, 0)),
                })
                .FirstAsync();

            enterpriseOrderDto.InProgressCount = enterpriseOrderData.InProgressCount;
            enterpriseOrderDto.CompletedCount = enterpriseOrderData.CompletedCount;
            enterpriseOrderDto.CenterCount = enterpriseOrderData.CenterCount;
            enterpriseOrderDto.CityCount = enterpriseOrderData.CityCount;
            enterpriseOrderDto.CountyCount = enterpriseOrderData.CountyCount;
            centerReportStatisticsDto.EnterpriseOrderDto = enterpriseOrderDto;
            var enterpriseOrderDto2 = await _orderVisitDetailRepository.Queryable()
                .Includes(it => it.OrderVisit, ov => ov.Order)
                .LeftJoin<SystemOrganize>((it, so) => it.VisitOrgCode == so.Id)
                .Where((it, so) => it.VisitTarget == EVisitTarget.Org && it.OrderVisit.VisitTime >= StartTime && it.OrderVisit.VisitTime <= EndTime && it.OrderVisit.VisitState == EVisitState.Visited && it.OrderVisit.Order.IdentityType == EIdentityType.Enterprise)
                .GroupBy((it, so) => it.Id)
                .Select((it, so) => new EnterpriseOrderDto
                {
                    VisitdCount = SqlFunc.AggregateCount(1),
                    Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2", 1, 0)),
                    Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2"), 1, 0)),
                    CityDissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF((SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.City, 1, 0)),
                    CitySatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.City, 1, 0)),
                    CountyDissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF((SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.County, 1, 0)),
                    CountySatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(!(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1") && !(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2") && so.OrgType == EOrgType.County, 1, 0)),
                })
                .ToListAsync();

            if (enterpriseOrderDto2.Any())
            {
                centerReportStatisticsDto.EnterpriseOrderDto.VisitdCount = enterpriseOrderDto2.Sum(x => x.VisitdCount);
                centerReportStatisticsDto.EnterpriseOrderDto.Dissatisfied = enterpriseOrderDto2.Sum(x => x.Dissatisfied);
                centerReportStatisticsDto.EnterpriseOrderDto.CityDissatisfied = enterpriseOrderDto2.Sum(x => x.CityDissatisfied);
                centerReportStatisticsDto.EnterpriseOrderDto.CountyDissatisfied = enterpriseOrderDto2.Sum(x => x.CountyDissatisfied);
                centerReportStatisticsDto.EnterpriseOrderDto.Satisfied = enterpriseOrderDto2.Sum(x => x.Satisfied);
                centerReportStatisticsDto.EnterpriseOrderDto.CitySatisfied = enterpriseOrderDto2.Sum(x => x.CitySatisfied);
                centerReportStatisticsDto.EnterpriseOrderDto.CountySatisfied = enterpriseOrderDto2.Sum(x => x.CountySatisfied);
            }

            if (listInfo != null && listInfo.Rows.Count > 0 && centerReportStatisticsDto.EnterpriseOrderDto != null)
            {
                // 企业办件
                centerReportStatisticsDto.EnterpriseOrderDto.OrderCount = centerReportStatisticsDto.EnterpriseOrderDto.OrderCount + Convert.ToInt32(listInfo.Rows[0]["EnterpriseAllCount"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CompletedAging = centerReportStatisticsDto.EnterpriseOrderDto.CompletedAging + Convert.ToInt32(listInfo.Rows[0]["EnterpriseWorkTime"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CityOrderCount = centerReportStatisticsDto.EnterpriseOrderDto.CityOrderCount + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCity"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CityCompletedAging = centerReportStatisticsDto.EnterpriseOrderDto.CityCompletedAging + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCityWorkTime"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CountyOrderCount = centerReportStatisticsDto.EnterpriseOrderDto.CountyOrderCount + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCounty"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CountyCompletedAging = centerReportStatisticsDto.EnterpriseOrderDto.CountyCompletedAging + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCountyWorkTime"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CenterOrderCount = centerReportStatisticsDto.EnterpriseOrderDto.CenterOrderCount + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCenter"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CenterCompletedAging = centerReportStatisticsDto.EnterpriseOrderDto.CenterCompletedAging + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCenterWorkTime"]);
                // 企业满意度
                centerReportStatisticsDto.EnterpriseOrderDto.VisitdCount = centerReportStatisticsDto.EnterpriseOrderDto.VisitdCount + Convert.ToInt32(listInfo.Rows[0]["EnterpriseVisit"]);
                centerReportStatisticsDto.EnterpriseOrderDto.Dissatisfied = centerReportStatisticsDto.EnterpriseOrderDto.Dissatisfied + Convert.ToInt32(listInfo.Rows[0]["EnterpriseDisSatisfaction"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CityDissatisfied = centerReportStatisticsDto.EnterpriseOrderDto.CityDissatisfied + Convert.ToInt32(listInfo.Rows[0]["CityCount"]) - Convert.ToInt32(listInfo.Rows[0]["CitySatisfactionCount"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CountyDissatisfied = centerReportStatisticsDto.EnterpriseOrderDto.CountyDissatisfied + Convert.ToInt32(listInfo.Rows[0]["CountyCount"]) - Convert.ToInt32(listInfo.Rows[0]["CountySatisfactionCount"]);
                centerReportStatisticsDto.EnterpriseOrderDto.Satisfied = centerReportStatisticsDto.EnterpriseOrderDto.Satisfied + Convert.ToInt32(listInfo.Rows[0]["AllCount"]) - Convert.ToInt32(listInfo.Rows[0]["SatisfactionCount"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CitySatisfied = centerReportStatisticsDto.EnterpriseOrderDto.CitySatisfied + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCitySatisfaction"]);
                centerReportStatisticsDto.EnterpriseOrderDto.CountySatisfied = centerReportStatisticsDto.EnterpriseOrderDto.CountySatisfied + Convert.ToInt32(listInfo.Rows[0]["EnterpriseCountySatisfaction"]);
            }

            #endregion

            #region 企业信件分类
            //信件来源
            var enterpriseAcceptTypeData = await _orderRepository.Queryable(false, false, false)
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime && p.IdentityType == EIdentityType.Enterprise)
                .Select(it => new
                {
                    AcceptTypeCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.AcceptTypeCode), "40", it.AcceptTypeCode),
                    FileOrgIsCenter = it.FileOrgIsCenter.HasValue ? it.FileOrgIsCenter : true,
                    CreationTimeHandleDurationWorkday = it.CreationTimeHandleDurationWorkday.HasValue ? it.CenterToOrgHandleDurationWorkday : 0,
                    CenterToOrgHandleDurationWorkday = it.CenterToOrgHandleDurationWorkday.HasValue ? it.CenterToOrgHandleDurationWorkday : 0,
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(temp => new { temp.AcceptTypeCode })//对新表进行分组
                 .Select(temp => new CenterReportOrderSourceChannelDto
                 {
                     Code = temp.AcceptTypeCode,
                     CountNum = SqlFunc.AggregateCount(temp.AcceptTypeCode),
                     CompletedAging = SqlFunc.AggregateSum(SqlFunc.IIF(temp.FileOrgIsCenter == true, temp.CreationTimeHandleDurationWorkday, temp.CenterToOrgHandleDurationWorkday))
                 })
                 .ToListAsync();
            List<CenterReportOrderSourceChannelDto> enterpriseAcceptType = new();
            var enterpriseAcceptTypeDic = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.AcceptType);
            foreach (var item in enterpriseAcceptTypeDic)
            {
                enterpriseAcceptType.Add(new CenterReportOrderSourceChannelDto
                {
                    AllCountNum = sourceChannelCount,
                    Name = item.DicDataName,
                    Code = item.DicTypeCode,
                    CountNum = enterpriseAcceptTypeData.Find(p => p.Code == item.DicDataValue)?.CountNum ?? 0,
                    CompletedAging = enterpriseAcceptTypeData.Find(p => p.Code == item.DicDataValue)?.CompletedAging ?? 0
                });
            }

            if (listPurOld != null && listPurOld.Rows.Count > 0 && enterpriseAcceptType != null)
            {
                foreach (var item in enterpriseAcceptType)
                {
                    if (item.Code == "10")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Consult"]);            // 咨询
                    else if (item.Code == "15")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Suggest"]);            // 建议
                    else if (item.Code == "20")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["SeekHelp"]);           // 求助
                    else if (item.Code == "25")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Praise"]);             // 表扬
                    else if (item.Code == "30")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Report"]);             // 举报
                    else if (item.Code == "35")
                        item.CountNum = item.CountNum + Convert.ToInt32(listPurOld.Rows[0]["Complaint"]);          // 投诉
                }
            }

            centerReportStatisticsDto.EnterpriseCenterReportOrderAcceptTypes = enterpriseAcceptType;
            #endregion

            return centerReportStatisticsDto;
        }


        /// <summary>
        /// 中心报表统计--自贡
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        [HttpGet("center_report_forms_statistics_zg")]
        public async Task<CenterReportStatisticsDto> ZgCenterReportFormsStatistics(DateTime StartTime, DateTime EndTime)
        {
            CenterReportStatisticsDto centerReportStatisticsDto = new();

            //信件总量
            int sourceChannelCount = await _orderRepository.Queryable().Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime).CountAsync();

            #region 1、通话记录
            //通话记录
            var callData = await _callNativeRepository.Queryable()
               .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
               // .Where(p => p.Gateway != "82826886" && SqlFunc.Length(p.Gateway) != 4)
               .Select(p => new CenterReportCallInfoDto
               {
                   AllCallCount = SqlFunc.AggregateSum(1),//话务总量
                   InTotal = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In, 1, 0)),//呼入总量
                   InConnectionQuantity = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.AnsweredTime != null, 1, 0)),//呼入接通量
                   InHanguped = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.AnsweredTime == null, 1, 0)),//呼入未接通
                   QueueByeCount = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.WaitDuration > 0 && p.RingDuration == 0 && p.AnsweredTime == null, 1, 0)), //队列挂断
                   IvrByeCount = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.BeginIvrTime.HasValue && !p.BeginQueueTime.HasValue && !p.BeginRingTime.HasValue && p.AnsweredTime == null, 1, 0)), //IVR挂断
                   OutTotal = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.Out, 1, 0)),//呼出总量
                   OutConnectionQuantity = SqlFunc.AggregateSum(SqlFunc.IIF(p.TelNo != "0" && p.Direction == ECallDirection.Out && p.AnsweredTime != null, 1, 0)),//呼出接通量
                   OutHanguped = SqlFunc.AggregateSum(SqlFunc.IIF(p.TelNo != "0" && p.Direction == ECallDirection.Out && p.AnsweredTime == null, 1, 0)),//呼出未接通

               })
               .FirstAsync();
            centerReportStatisticsDto.CenterReportCallInfoDto = callData;

            #endregion

            #region 2、信件回访量
            //信件回访量
            var centerReportVisitd = await _orderVisitRepository.Queryable()
              .Where(x => x.VisitTime >= StartTime && x.VisitTime <= EndTime)
              .Select(x => new CenterReportVisitdDto
              {
                  Visitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited, 1, 0)),//已回访
                  CallVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited && x.VisitType == EVisitType.CallVisit, 1, 0)),// 已回访--电话
                  SmsVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited && x.VisitType == EVisitType.SmsVisit, 1, 0)),//已回访--短信
                  OtherVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited && x.VisitType != EVisitType.CallVisit && x.VisitType != EVisitType.SmsVisit, 1, 0)),//其他回访
                  //WaitVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState != EVisitState.None && x.VisitState != EVisitState.Visited, 1, 0)),//待回访
              }).FirstAsync();

            var waitVisitd = await _orderVisitRepository.Queryable()
             .Where(x => x.CreationTime >= StartTime && x.CreationTime <= EndTime).Select(x =>
                   SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState != EVisitState.None && x.VisitState != EVisitState.Visited, 1, 0)) //待回访
              ).FirstAsync();
            centerReportVisitd.WaitVisitd = waitVisitd;

            //部门
            var listOrg = await _orderVisitDetailRepository.Queryable()
                .LeftJoin<OrderVisit>((it, o) => it.VisitId == o.Id)
                .Where((it, o) => it.VisitTarget == EVisitTarget.Org && o.VisitTime >= StartTime && o.VisitTime <= EndTime && o.VisitState == EVisitState.Visited)
                 .Select((it, o) => new Satisfaction
                 {
                     Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(it.OrgProcessingResults, "Key") == "2", 1, 0)),
                     Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(it.OrgProcessingResults, "Key") != "1" && SqlFunc.JsonField(it.OrgProcessingResults, "Key") != "2", 1, 0)),
                 })
                .FirstAsync();
            //计算部门满意度
            if (listOrg != null)
            {
                var satisfiedCount = listOrg.Satisfied + listOrg.Dissatisfied;
                if (satisfiedCount > 0 && listOrg.Satisfied > 0)
                    centerReportVisitd.OrgRate = Math.Round((listOrg.Satisfied / (double)satisfiedCount) * 100, 2);
            }

            //坐席
            var listSet = await _orderVisitDetailRepository.Queryable()
                .LeftJoin<OrderVisit>((it, o) => it.VisitId == o.Id)
                .Where((it, o) => it.VisitTarget == EVisitTarget.Seat && o.VisitTime >= StartTime && o.VisitTime <= EndTime && o.VisitState == EVisitState.Visited)
                .Select((it, o) => new Satisfaction
                {
                    Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(it.SeatEvaluate == ESeatEvaluate.NoSatisfied, 1, 0)),
                    Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(it.SeatEvaluate != ESeatEvaluate.NoSatisfied, 1, 0)),
                })
                .FirstAsync();
            //计算坐席满意度
            if (listSet != null)
            {
                var satisfiedCount = listSet.Satisfied + listSet.Dissatisfied;
                if (satisfiedCount > 0 && listSet.Satisfied > 0)
                    centerReportVisitd.SeatsRate = Math.Round((listSet.Satisfied / (double)satisfiedCount) * 100, 2);
            }

            centerReportStatisticsDto.CenterReportVisitd = centerReportVisitd;
            #endregion

            #region 3、工单
            //工单
            var orderData = await _orderRepository.Queryable()
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(x => new CenterReportOrderDto
                {
                    EffectiveCount = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),//有效
                    InvalidCount = 0,//无效
                    CompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed, 1, 0)),//已办结
                    OnTimeCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ExpiredTime > x.ActualHandleTime, 1, 0)),//按时办结
                    CenterCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ProcessType == EProcessType.Zhiban, 1, 0)),//中心办结
                    OrgCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ProcessType == EProcessType.Jiaoban, 1, 0)),//部门办结
                    InProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed, 1, 0)),//在办
                    CenterInProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed && x.ProcessType == EProcessType.Zhiban, 1, 0)),//中心在办
                    OrgInProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed && x.ProcessType == EProcessType.Jiaoban, 1, 0))//部门在办
                })
                .FirstAsync();
            centerReportStatisticsDto.CenterReportOrder = orderData;
            #endregion

            #region 4、信件来源

            //信件来源
            var sourceChannelData = _orderRepository.Queryable()
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(it => new
                {
                    SourceChannelCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.SourceChannelCode), "QT", it.SourceChannelCode)
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(it => new { it.SourceChannelCode })//对新表进行分组
                 .Select(it => new CenterReportOrderSourceChannelDto
                 {
                     Code = it.SourceChannelCode,
                     CountNum = SqlFunc.AggregateCount(it.SourceChannelCode)
                 });

            var sourceData = await _systemDicDataRepository.Queryable()
               .LeftJoin(sourceChannelData, (s, p) => s.DicDataValue == p.Code)
              .Where((s, p) => s.DicTypeCode == "SourceChannel" && s.IsShow == true)
              .Select((s, p) => new CenterReportOrderSourceChannelDto
              {
                  Code = s.DicDataValue,
                  Name = s.DicDataName,
                  CountNum = p.CountNum
              })

              .ToListAsync();

            centerReportStatisticsDto.CenterReportOrderSourceChannels = sourceData;
            #endregion

            #region 5、信件分类
            //信件来源 AcceptType

            var acceptTypeData = _orderRepository.Queryable(false, false, false)
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(it => new
                {
                    AcceptTypeCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.AcceptTypeCode), "40", it.AcceptTypeCode)
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(it => new { it.AcceptTypeCode })//对新表进行分组
                 .Select(it => new CenterReportOrderSourceChannelDto
                 {
                     Code = it.AcceptTypeCode,
                     CountNum = SqlFunc.AggregateCount(it.AcceptTypeCode)
                 });

            var acceptType = await _systemDicDataRepository.Queryable()
              .LeftJoin(acceptTypeData, (s, p) => s.DicDataValue == p.Code)
             .Where((s, p) => s.DicTypeCode == "AcceptType" && s.IsShow == true)
             .Select((s, p) => new CenterReportOrderSourceChannelDto
             {
                 AllCountNum = sourceChannelCount,
                 Code = s.DicDataValue,
                 Name = s.DicDataName,
                 CountNum = p.CountNum
             })
             .ToListAsync();

            centerReportStatisticsDto.CenterReportOrderAcceptTypes = acceptType;
            #endregion

            #region 信件分布情况
            //市直部门

            var listOrgStatisticsCityAll = await _orderRepository.Queryable()
                .Where(o => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .Select(o => new
                {
                    OrgCode = o.ActualHandleOrgCode == null || o.ActualHandleOrgCode == "" ? "001" : o.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((o, s) => o.OrgCode == s.Id)
                 .Where((o, s) => s.OrgType == EOrgType.City || s.OrgType == EOrgType.Province)
                .GroupBy((o, s) => new
                {
                    o.OrgCode,
                    s.Name
                })
                .Select((o, s) => new OrgStatistics
                {
                    CountNum = SqlFunc.AggregateCount(o.OrgCode),
                    OrgName = s.Name
                }).ToListAsync();

            centerReportStatisticsDto.OrgStatisticsCityAll = new OrgStatisticsAll
            {
                OrgStatistics = listOrgStatisticsCityAll
            };

            //区县部门
            var listOrgStatisticsAreaAll = await _orderRepository.Queryable()
                .Where(o => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .Select(o => new
                {
                    OrgCode = o.ActualHandleOrgCode == null || o.ActualHandleOrgCode == "" ? "001" : o.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((o, s) => o.OrgCode == s.Id)
                 .Where((o, s) => s.OrgType == EOrgType.County)
                .GroupBy((o, s) => new
                {
                    o.OrgCode,
                    s.Name
                })
                .Select((o, s) => new OrgStatistics
                {
                    CountNum = SqlFunc.AggregateCount(o.OrgCode),

                    OrgName = s.Name
                }).ToListAsync();

            centerReportStatisticsDto.OrgStatisticsAreaAll = new OrgStatisticsAll
            {
                OrgStatistics = listOrgStatisticsAreaAll
            };
            #endregion

            return centerReportStatisticsDto;
        }


        /// <summary>
        /// 中心报表统计--泸州
        /// </summary>
        /// <param name="StartTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <param name="IdentityType">来电主体</param>
        /// <returns></returns>
        [HttpGet("center_report_forms_statistics_lz")]
        public async Task<CenterReportStatisticsDto> LzCenterReportFormsStatistics(DateTime StartTime, DateTime EndTime, EIdentityType? IdentityType)
        {
            CenterReportStatisticsDto centerReportStatisticsDto = new();

            //信件总量
            int sourceChannelCount = await _orderRepository.Queryable().Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime).CountAsync();

            #region 1、通话记录
            //通话记录
            var callData = await _callNativeRepository.Queryable()
               .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
               // .Where(p => p.Gateway != "82826886" && SqlFunc.Length(p.Gateway) != 4)
               .Select(p => new CenterReportCallInfoDto
               {
                   AllCallCount = SqlFunc.AggregateSum(1),//话务总量
                   InTotal = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In, 1, 0)),//呼入总量
                   InConnectionQuantity = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.AnsweredTime != null, 1, 0)),//呼入接通量
                   InHanguped = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.AnsweredTime == null, 1, 0)),//呼入未接通
                   QueueByeCount = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.WaitDuration > 0 && p.RingDuration == 0 && p.AnsweredTime == null, 1, 0)), //队列挂断
                   IvrByeCount = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.In && p.BeginIvrTime.HasValue && !p.BeginQueueTime.HasValue && !p.BeginRingTime.HasValue && p.AnsweredTime == null, 1, 0)), //IVR挂断
                   OutTotal = SqlFunc.AggregateSum(SqlFunc.IIF(p.Direction == ECallDirection.Out, 1, 0)),//呼出总量
                   OutConnectionQuantity = SqlFunc.AggregateSum(SqlFunc.IIF(p.TelNo != "0" && p.Direction == ECallDirection.Out && p.AnsweredTime != null, 1, 0)),//呼出接通量
                   OutHanguped = SqlFunc.AggregateSum(SqlFunc.IIF(p.TelNo != "0" && p.Direction == ECallDirection.Out && p.AnsweredTime == null, 1, 0)),//呼出未接通

               })
               .FirstAsync();
            centerReportStatisticsDto.CenterReportCallInfoDto = callData;

            #endregion

            #region 2、信件回访量
            //信件回访量
            var centerReportVisitd = await _orderVisitRepository.Queryable()
              .LeftJoin<Order>((x, o) => x.OrderId == o.Id)
              .WhereIF(IdentityType.HasValue, (x, o) => o.IdentityType == IdentityType)
              .Where((x, o) => x.VisitTime >= StartTime && x.VisitTime <= EndTime)
              .Select((x, o) => new CenterReportVisitdDto
              {
                  Visitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited, 1, 0)),//已回访
                  CallVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited && x.VisitType == EVisitType.CallVisit, 1, 0)),// 已回访--电话
                  SmsVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited && x.VisitType == EVisitType.SmsVisit, 1, 0)),//已回访--短信
                  OtherVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState == EVisitState.Visited && x.VisitType != EVisitType.CallVisit && x.VisitType != EVisitType.SmsVisit, 1, 0)),//其他回访
                  //WaitVisitd = SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState != EVisitState.None && x.VisitState != EVisitState.Visited, 1, 0)),//待回访
              }).FirstAsync();

            var waitVisitd = await _orderVisitRepository.Queryable()
              .LeftJoin<Order>((x, o) => x.OrderId == o.Id)
              .WhereIF(IdentityType.HasValue, (x, o) => o.IdentityType == IdentityType)
              .Where((x, o) => x.CreationTime >= StartTime && x.CreationTime <= EndTime).Select((x, o) =>
                    SqlFunc.AggregateSum(SqlFunc.IIF(x.VisitState != EVisitState.None && x.VisitState != EVisitState.Visited, 1, 0)) //待回访
               ).FirstAsync();
            centerReportVisitd.WaitVisitd = waitVisitd;

            //部门
            var listOrg = await _orderVisitDetailRepository.Queryable()
                .LeftJoin<OrderVisit>((x, ov) => x.VisitId == ov.Id)
                .LeftJoin<Order>((x, ov, o) => ov.OrderId == o.Id)
                .WhereIF(IdentityType.HasValue, (x, ov, o) => o.IdentityType == IdentityType)
                .Where((x, ov, o) => x.VisitTarget == EVisitTarget.Org && ov.VisitTime >= StartTime && ov.VisitTime <= EndTime && ov.VisitState == EVisitState.Visited)
                 .Select((x, ov, o) => new Satisfaction
                 {
                     Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "1" || SqlFunc.JsonField(x.OrgProcessingResults, "Key") == "2", 1, 0)),
                     Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(SqlFunc.JsonField(x.OrgProcessingResults, "Key") != "1" && SqlFunc.JsonField(x.OrgProcessingResults, "Key") != "2", 1, 0)),
                 })
                .FirstAsync();
            //计算部门满意度
            if (listOrg != null)
            {
                centerReportVisitd.Dissatisfied = listOrg.Dissatisfied;
                centerReportVisitd.Satisfied = listOrg.Satisfied;
                var satisfiedCount = listOrg.Satisfied + listOrg.Dissatisfied;
                if (satisfiedCount > 0 && listOrg.Satisfied > 0)
                    centerReportVisitd.OrgRate = Math.Round((listOrg.Satisfied / (double)satisfiedCount) * 100, 2);
            }

            //坐席
            var listSet = await _orderVisitDetailRepository.Queryable()
                .LeftJoin<OrderVisit>((x, ov) => x.VisitId == ov.Id)
                .LeftJoin<Order>((x, ov, o) => ov.OrderId == o.Id)
                .WhereIF(IdentityType.HasValue, (x, ov, o) => o.IdentityType == IdentityType)
                .Where((x, ov, o) => x.VisitTarget == EVisitTarget.Seat && ov.VisitTime >= StartTime && ov.VisitTime <= EndTime && ov.VisitState == EVisitState.Visited)
                .Select((x, ov, o) => new Satisfaction
                {
                    Dissatisfied = SqlFunc.AggregateSum(SqlFunc.IIF(x.SeatEvaluate == ESeatEvaluate.NoSatisfied, 1, 0)),
                    Satisfied = SqlFunc.AggregateSum(SqlFunc.IIF(x.SeatEvaluate != ESeatEvaluate.NoSatisfied, 1, 0)),
                })
                .FirstAsync();
            //计算坐席满意度
            if (listSet != null)
            {
                var satisfiedCount = listSet.Satisfied + listSet.Dissatisfied;
                if (satisfiedCount > 0 && listSet.Satisfied > 0)
                    centerReportVisitd.SeatsRate = Math.Round((listSet.Satisfied / (double)satisfiedCount) * 100, 2);
            }

            centerReportStatisticsDto.CenterReportVisitd = centerReportVisitd;
            #endregion

            #region 3、工单
            //工单
            var orderData = await _orderRepository.Queryable()
                .WhereIF(IdentityType.HasValue, p => p.IdentityType == IdentityType)
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(x => new CenterReportOrderDto
                {
                    EffectiveCount = SqlFunc.AggregateSum(SqlFunc.IIF(true, 1, 0)),//有效
                    InvalidCount = 0,//无效
                    CompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed, 1, 0)),//已办结
                    OnTimeCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.ExpiredTime > x.ActualHandleTime, 1, 0)),//按时办结
                    CenterCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.FileUserOrgId == OrgSeedData.CenterId, 1, 0)),//中心办结
                    OrgCompletedCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status >= EOrderStatus.Filed && x.FileUserOrgId != OrgSeedData.CenterId, 1, 0)),//部门办结
                    InProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed, 1, 0)),//在办
                    CenterInProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed && (x.ActualHandleOrgCode == OrgSeedData.CenterId || x.ActualHandleOrgCode == null), 1, 0)),//中心在办
                    OrgInProgressCount = SqlFunc.AggregateSum(SqlFunc.IIF(x.Status < EOrderStatus.Filed && x.ActualHandleOrgCode != OrgSeedData.CenterId && x.ActualHandleOrgCode != null, 1, 0))//部门在办
                })
                .FirstAsync();
            //催办
            var orderUrge = await _orderUrgeRepository.Queryable()
                .LeftJoin<Order>((p, o) => p.OrderId == o.Id)
                .Where((p, o) => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .WhereIF(IdentityType.HasValue, (p, o) => o.IdentityType == IdentityType).Select((p, o) => p.OrderId).Distinct().CountAsync();
            orderData.orderUrge = orderUrge;
            centerReportStatisticsDto.CenterReportOrder = orderData;
            #endregion

            #region 4、信件来源

            //信件来源
            var sourceChannelData = _orderRepository.Queryable()
                .WhereIF(IdentityType.HasValue, p => p.IdentityType == IdentityType)
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(it => new
                {
                    SourceChannelCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.SourceChannelCode), "QT", it.SourceChannelCode)
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(it => new { it.SourceChannelCode })//对新表进行分组
                 .Select(it => new CenterReportOrderSourceChannelDto
                 {
                     Code = it.SourceChannelCode,
                     CountNum = SqlFunc.AggregateCount(it.SourceChannelCode)
                 });

            var sourceData = await _systemDicDataRepository.Queryable()
               .LeftJoin(sourceChannelData, (s, p) => s.DicDataValue == p.Code)
              .Where((s, p) => s.DicTypeCode == "SourceChannel" && s.IsShow == true)
              .Select((s, p) => new CenterReportOrderSourceChannelDto
              {
                  AllCountNum = sourceChannelCount,
                  Code = s.DicDataValue,
                  Name = s.DicDataName,
                  CountNum = p.CountNum
              })

              .ToListAsync();

            centerReportStatisticsDto.CenterReportOrderSourceChannels = sourceData;
            #endregion

            #region 5、信件分类
            //信件来源 AcceptType

            var acceptTypeData = _orderRepository.Queryable(false, false, false)
                .WhereIF(IdentityType.HasValue, p => p.IdentityType == IdentityType)
                .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                .Select(it => new
                {
                    AcceptTypeCode = SqlFunc.IIF(SqlFunc.IsNullOrEmpty(it.AcceptTypeCode), "40", it.AcceptTypeCode)
                })
                .MergeTable()//将查询出来的结果合并成一个新表
                 .GroupBy(it => new { it.AcceptTypeCode })//对新表进行分组
                 .Select(it => new CenterReportOrderSourceChannelDto
                 {
                     Code = it.AcceptTypeCode,
                     CountNum = SqlFunc.AggregateCount(it.AcceptTypeCode)
                 });

            var acceptType = await _systemDicDataRepository.Queryable()
              .LeftJoin(acceptTypeData, (s, p) => s.DicDataValue == p.Code)
             .Where((s, p) => s.DicTypeCode == "AcceptType" && s.IsShow == true)
             .Select((s, p) => new CenterReportOrderSourceChannelDto
             {
                 AllCountNum = sourceChannelCount,
                 Code = s.DicDataValue,
                 Name = s.DicDataName,
                 CountNum = p.CountNum
             })
             .ToListAsync();

            centerReportStatisticsDto.CenterReportOrderAcceptTypes = acceptType;
            #endregion

            #region 信件分布情况
            //市直部门

            var listOrgStatisticsCityAll = await _orderRepository.Queryable()
                .WhereIF(IdentityType.HasValue, p => p.IdentityType == IdentityType)
                .Where(o => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .Select(o => new
                {
                    OrgCode = o.ActualHandleOrgCode == null || o.ActualHandleOrgCode == "" ? "001" : o.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((o, s) => o.OrgCode == s.Id)
                 .Where((o, s) => s.OrgType == EOrgType.City || s.OrgType == EOrgType.Province)
                .GroupBy((o, s) => new
                {
                    o.OrgCode,
                    s.Name
                })
                .Select((o, s) => new OrgStatistics
                {
                    CountNum = SqlFunc.AggregateCount(o.OrgCode),
                    OrgName = s.Name
                }).ToListAsync();

            centerReportStatisticsDto.OrgStatisticsCityAll = new OrgStatisticsAll
            {
                OrgStatistics = listOrgStatisticsCityAll
            };

            //区县部门
            var listOrgStatisticsAreaAll = await _orderRepository.Queryable()
                .Where(o => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .Select(o => new
                {
                    OrgCode = o.ActualHandleOrgCode == null || o.ActualHandleOrgCode == "" ? "001" : o.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                })
                .MergeTable()
                .LeftJoin<SystemOrganize>((o, s) => o.OrgCode == s.Id)
                 .Where((o, s) => s.OrgType == EOrgType.County)
                .GroupBy((o, s) => new
                {
                    o.OrgCode,
                    s.Name
                })
                .Select((o, s) => new OrgStatistics
                {
                    CountNum = SqlFunc.AggregateCount(o.OrgCode),

                    OrgName = s.Name
                }).ToListAsync();

            centerReportStatisticsDto.OrgStatisticsAreaAll = new OrgStatisticsAll
            {
                OrgStatistics = listOrgStatisticsAreaAll
            };
            #endregion

            return centerReportStatisticsDto;
        }


        /// <summary>
        /// 部门受理类型统计周期
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("department_acceptance_type_statistics")]
        public async Task<object> DepartmentAcceptanceTypeStatistics([FromQuery] DepartmentKeyWordRequest dto)
        {
            var items = await _orderReportApplication.DepartmentAcceptanceTypeStatistics(dto).ToListAsync();

            foreach (var item in items)
            {
                item.ZxAllTimes = Math.Round(((double)item.ZxAllTimes / 3600 / 8), 2);
                item.JyAllTimes = Math.Round(((double)item.JyAllTimes / 3600 / 8), 2);
                item.QzAllTimes = Math.Round(((double)item.QzAllTimes / 3600 / 8), 2);
                item.ByAllTimes = Math.Round(((double)item.ByAllTimes / 3600 / 8), 2);
                item.JbAllTimes = Math.Round(((double)item.JbAllTimes / 3600 / 8), 2);
                item.TsAllTimes = Math.Round(((double)item.TsAllTimes / 3600 / 8), 2);
                item.QtAllTimes = Math.Round(((double)item.QtAllTimes / 3600 / 8), 2);
                item.YjAllTimes = Math.Round(((double)item.YjAllTimes / 3600 / 8), 2);
            }


            var total = new DepartmentAcceptanceTypeStatisticsDto
            {
                OrgName = "合计",
                OrgCode = "",
                OrgType = "",
                ZxAllCount = items.Sum(p => p.ZxAllCount),
                ZxAllTimes = Math.Round(items.Sum(p => p.ZxAllTimes).Value, 2),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = items.Sum(p => p.JyAllCount),
                JyAllTimes = Math.Round(items.Sum(p => p.JyAllTimes).Value, 2),
                JyAcceptanceTypeCode = "15",

                QzAllCount = items.Sum(p => p.QzAllCount),
                QzAllTimes = Math.Round(items.Sum(p => p.QzAllTimes).Value, 2),
                QzAcceptanceTypeCode = "20",

                ByAllCount = items.Sum(p => p.ByAllCount),
                ByAllTimes = Math.Round(items.Sum(p => p.ByAllTimes).Value, 2),
                ByAcceptanceTypeCode = "25",

                JbAllCount = items.Sum(p => p.JbAllCount),
                JbAllTimes = Math.Round(items.Sum(p => p.JbAllTimes).Value, 2),
                JbAcceptanceTypeCode = "30",

                TsAllCount = items.Sum(p => p.TsAllCount),
                TsAllTimes = Math.Round(items.Sum(p => p.TsAllTimes).Value, 2),
                TsAcceptanceTypeCode = "35",

                QtAllCount = items.Sum(p => p.QtAllCount),
                QtAllTimes = Math.Round(items.Sum(p => p.QtAllTimes).Value, 2),
                QtAcceptanceTypeCode = "40",

                YjAllCount = items.Sum(p => p.YjAllCount),
                YjAllTimes = Math.Round(items.Sum(p => p.YjAllTimes).Value, 2),
                YjAcceptanceTypeCode = "1"
            };

            return new { List = items, Total = total };
        }

        /// <summary>
        /// 部门受理类型统计周期---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("department_acceptance_type_statistics_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentAcceptanceTypeStatistics([FromBody] ExportExcelDto<DepartmentKeyWordRequest> dto)
        {
            var query = _orderReportApplication.DepartmentAcceptanceTypeStatistics(dto.QueryDto);
            List<DepartmentAcceptanceTypeStatisticsDto> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }
            foreach (var item in list)
            {
                item.ZxAllTimes = Math.Round(((double)item.ZxAllTimes / 3600 / 8), 2);
                item.JyAllTimes = Math.Round(((double)item.JyAllTimes / 3600 / 8), 2);
                item.QzAllTimes = Math.Round(((double)item.QzAllTimes / 3600 / 8), 2);
                item.ByAllTimes = Math.Round(((double)item.ByAllTimes / 3600 / 8), 2);
                item.JbAllTimes = Math.Round(((double)item.JbAllTimes / 3600 / 8), 2);
                item.TsAllTimes = Math.Round(((double)item.TsAllTimes / 3600 / 8), 2);
                item.QtAllTimes = Math.Round(((double)item.QtAllTimes / 3600 / 8), 2);
                item.YjAllTimes = Math.Round(((double)item.YjAllTimes / 3600 / 8), 2);
            }
            //增加合计
            list.Add(new DepartmentAcceptanceTypeStatisticsDto
            {
                OrgName = "合计",
                OrgCode = "",
                OrgType = "",
                ZxAllCount = list.Sum(p => p.ZxAllCount),
                ZxAllTimes = list.Sum(p => p.ZxAllTimes),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = list.Sum(p => p.JyAllCount),
                JyAllTimes = list.Sum(p => p.JyAllTimes),
                JyAcceptanceTypeCode = "15",

                QzAllCount = list.Sum(p => p.QzAllCount),
                QzAllTimes = list.Sum(p => p.QzAllTimes),
                QzAcceptanceTypeCode = "20",

                ByAllCount = list.Sum(p => p.ByAllCount),
                ByAllTimes = list.Sum(p => p.ByAllTimes),
                ByAcceptanceTypeCode = "25",

                JbAllCount = list.Sum(p => p.JbAllCount),
                JbAllTimes = list.Sum(p => p.JbAllTimes),
                JbAcceptanceTypeCode = "30",

                TsAllCount = list.Sum(p => p.TsAllCount),
                TsAllTimes = list.Sum(p => p.TsAllTimes),
                TsAcceptanceTypeCode = "35",

                QtAllCount = list.Sum(p => p.QtAllCount),
                QtAllTimes = list.Sum(p => p.QtAllTimes),
                QtAcceptanceTypeCode = "40",

                YjAllCount = list.Sum(p => p.YjAllCount),
                YjAllTimes = list.Sum(p => p.YjAllTimes),
                YjAcceptanceTypeCode = "1"
            });

            var orderDtos = _mapper.Map<ICollection<DepartmentAcceptanceTypeStatisticsDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<DepartmentAcceptanceTypeStatisticsDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(DepartmentAcceptanceTypeStatisticsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门受理类型统计周期数据");
        }

        /// <summary>
        /// 部门受理类型统计周期--明细列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("department_acceptance_type_order_list")]
        public async Task<PagedDto<OrderDto>> DepartmentAcceptanceTypeOrderList([FromQuery] DepartmentKeyWordRequest dto)
        {
            var (total, items) = await _orderReportApplication.DepartmentAcceptanceTypeOrderList(dto)
                .ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 部门受理类型统计周期--明细列表---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("department_acceptance_type_order_list_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentAcceptanceTypeOrderList([FromBody] ExportExcelDto<DepartmentKeyWordRequest> dto)
        {
            var query = _orderReportApplication.DepartmentAcceptanceTypeOrderList(dto.QueryDto);
            List<Order> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }

            var orderDtos = _mapper.Map<ICollection<OrderDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门受理类型统计周期数据");
        }


        /// <summary>
        /// 部门受理类型统计（宜宾功能）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("department_acceptance_type_statistics_v1")]
        public async Task<object> DepartmentAcceptanceTypeStatisticsV1([FromQuery] DepartmentKeyWordRequest dto)
        {
            var items = await _orderReportApplication.DepartmentAcceptanceTypeStatisticsV1(dto).ToListAsync();

            var countySumModel = new DepartmentAcceptanceTypeStatisticsV1Dto()
            {
                OrgName = "区县合计",
                OrgCode = "",
                OrgTypeText = "",
                ZxAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.ZxAllCount),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.JyAllCount),
                JyAcceptanceTypeCode = "15",

                QzAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.QzAllCount),
                QzAcceptanceTypeCode = "20",

                ByAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.ByAllCount),
                ByAcceptanceTypeCode = "25",

                JbAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.JbAllCount),
                JbAcceptanceTypeCode = "30",

                TsAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.TsAllCount),
                TsAcceptanceTypeCode = "35",

                QtAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.QtAllCount),
                QtAcceptanceTypeCode = "40",

                YjAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.YjAllCount),
                YjAcceptanceTypeCode = "1",

                HmAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.HmAllCount),
                HmAcceptanceTypeCode = "2",

                DqAllCount = items.Where(x => x.OrgType == EOrgType.County).Sum(p => p.DqAllCount),
                DqAcceptanceTypeCode = "3"
            };

            var citySumModel = new DepartmentAcceptanceTypeStatisticsV1Dto()
            {
                OrgName = "市直合计",
                OrgCode = "",
                OrgTypeText = "",
                ZxAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.ZxAllCount),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.JyAllCount),
                JyAcceptanceTypeCode = "15",

                QzAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.QzAllCount),
                QzAcceptanceTypeCode = "20",

                ByAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.ByAllCount),
                ByAcceptanceTypeCode = "25",

                JbAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.JbAllCount),
                JbAcceptanceTypeCode = "30",

                TsAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.TsAllCount),
                TsAcceptanceTypeCode = "35",

                QtAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.QtAllCount),
                QtAcceptanceTypeCode = "40",

                YjAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.YjAllCount),
                YjAcceptanceTypeCode = "1",

                HmAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.HmAllCount),
                HmAcceptanceTypeCode = "2",

                DqAllCount = items.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.DqAllCount),
                DqAcceptanceTypeCode = "3"
            };

            var sumModel = new DepartmentAcceptanceTypeStatisticsV1Dto()
            {
                OrgName = "总计",
                OrgCode = "",
                OrgTypeText = "",
                ZxAllCount = items.Sum(p => p.ZxAllCount),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = items.Sum(p => p.JyAllCount),
                JyAcceptanceTypeCode = "15",

                QzAllCount = items.Sum(p => p.QzAllCount),
                QzAcceptanceTypeCode = "20",

                ByAllCount = items.Sum(p => p.ByAllCount),
                ByAcceptanceTypeCode = "25",

                JbAllCount = items.Sum(p => p.JbAllCount),
                JbAcceptanceTypeCode = "30",

                TsAllCount = items.Sum(p => p.TsAllCount),
                TsAcceptanceTypeCode = "35",

                QtAllCount = items.Sum(p => p.QtAllCount),
                QtAcceptanceTypeCode = "40",

                YjAllCount = items.Sum(p => p.YjAllCount),
                YjAcceptanceTypeCode = "1",

                HmAllCount = items.Sum(p => p.HmAllCount),
                HmAcceptanceTypeCode = "2",

                DqAllCount = items.Sum(p => p.DqAllCount),
                DqAcceptanceTypeCode = "3"
            };

            return new { DataList = items, CountySumModel = countySumModel, CitySumModel = citySumModel, SumModel = sumModel };
        }

        /// <summary>
        /// 部门受理类型统计（宜宾功能）---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("department_acceptance_type_statistics_export_v1")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentAcceptanceTypeStatisticsV1([FromBody] ExportExcelDto<DepartmentKeyWordRequest> dto)
        {
            var query = _orderReportApplication.DepartmentAcceptanceTypeStatisticsV1(dto.QueryDto);
            List<DepartmentAcceptanceTypeStatisticsV1Dto> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }

            list.Add(new DepartmentAcceptanceTypeStatisticsV1Dto
            {
                OrgName = "区县合计",
                OrgCode = "",
                OrgTypeText = "",
                ZxAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.ZxAllCount),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.JyAllCount),
                JyAcceptanceTypeCode = "15",

                QzAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.QzAllCount),
                QzAcceptanceTypeCode = "20",

                ByAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.ByAllCount),
                ByAcceptanceTypeCode = "25",

                JbAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.JbAllCount),
                JbAcceptanceTypeCode = "30",

                TsAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.TsAllCount),
                TsAcceptanceTypeCode = "35",

                QtAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.QtAllCount),
                QtAcceptanceTypeCode = "40",

                YjAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.YjAllCount),
                YjAcceptanceTypeCode = "1",

                HmAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.HmAllCount),
                HmAcceptanceTypeCode = "2",

                DqAllCount = list.Where(x => x.OrgType == EOrgType.County).Sum(p => p.DqAllCount),
                DqAcceptanceTypeCode = "3"
            });

            list.Add(new DepartmentAcceptanceTypeStatisticsV1Dto
            {
                OrgName = "市直合计",
                OrgCode = "",
                OrgTypeText = "",
                ZxAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.ZxAllCount),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.JyAllCount),
                JyAcceptanceTypeCode = "15",

                QzAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.QzAllCount),
                QzAcceptanceTypeCode = "20",

                ByAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.ByAllCount),
                ByAcceptanceTypeCode = "25",

                JbAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.JbAllCount),
                JbAcceptanceTypeCode = "30",

                TsAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.TsAllCount),
                TsAcceptanceTypeCode = "35",

                QtAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.QtAllCount),
                QtAcceptanceTypeCode = "40",

                YjAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.YjAllCount),
                YjAcceptanceTypeCode = "1",

                HmAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.HmAllCount),
                HmAcceptanceTypeCode = "2",

                DqAllCount = list.Where(x => x.OrgType == EOrgType.City && x.OrgCode != "001").Sum(p => p.DqAllCount),
                DqAcceptanceTypeCode = "3"
            });

            list.Add(new DepartmentAcceptanceTypeStatisticsV1Dto
            {
                OrgName = "总计",
                OrgCode = "",
                OrgTypeText = "",
                ZxAllCount = list.Sum(p => p.ZxAllCount),
                ZxAcceptanceTypeCode = "10",

                JyAllCount = list.Sum(p => p.JyAllCount),
                JyAcceptanceTypeCode = "15",

                QzAllCount = list.Sum(p => p.QzAllCount),
                QzAcceptanceTypeCode = "20",

                ByAllCount = list.Sum(p => p.ByAllCount),
                ByAcceptanceTypeCode = "25",

                JbAllCount = list.Sum(p => p.JbAllCount),
                JbAcceptanceTypeCode = "30",

                TsAllCount = list.Sum(p => p.TsAllCount),
                TsAcceptanceTypeCode = "35",

                QtAllCount = list.Sum(p => p.QtAllCount),
                QtAcceptanceTypeCode = "40",

                YjAllCount = list.Sum(p => p.YjAllCount),
                YjAcceptanceTypeCode = "1",

                HmAllCount = list.Sum(p => p.HmAllCount),
                HmAcceptanceTypeCode = "2",

                DqAllCount = list.Sum(p => p.DqAllCount),
                DqAcceptanceTypeCode = "3"
            });

            var orderDtos = _mapper.Map<ICollection<DepartmentAcceptanceTypeStatisticsV1Dto>>(list);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<DepartmentAcceptanceTypeStatisticsV1Dto>(dto.ColumnInfos);
            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(DepartmentAcceptanceTypeStatisticsV1Dto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门受理类型统计数据");
        }

        /// <summary>
        /// 部门受理类型统计（宜宾功能）--明细列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("department_acceptance_type_order_list_v1")]
        public async Task<PagedDto<OrderDto>> DepartmentAcceptanceTypeOrderListV1([FromQuery] DepartmentKeyWordRequest dto)
        {
            var (total, items) = await _orderReportApplication.DepartmentAcceptanceTypeOrderListV1(dto)
                .ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 部门受理类型统计（宜宾功能）--明细列表---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("department_acceptance_type_order_list_export_v1")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentAcceptanceTypeOrderListV1([FromBody] ExportExcelDto<DepartmentKeyWordRequest> dto)
        {
            var query = _orderReportApplication.DepartmentAcceptanceTypeOrderListV1(dto.QueryDto);
            List<Order> list;
            if (dto.IsExportAll)
            {
                list = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                list = items;
            }

            var orderDtos = _mapper.Map<ICollection<OrderDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门受理类型统计数据");
        }

        /// <summary>
        /// 部门办件统计表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("departmental_processing_statistics")]
        public async Task<object> DepartmentalProcessingStatistics([FromQuery] DepartmentalProcessingStatisticsRequest dto)
        {
            //联合查询
            //var items = await _orderReportApplication.DepartmentalProcessingStatistics(dto)
            //    .ToListAsync();

            var items = new List<DepartmentalProcessingStatisticsDataDto>();
            if (_appOptions.Value.IsLuZhou == true)
                items = await _orderReportApplication.LZDepartmentalProcessingStatisticsNew(dto);
            else
                items = await _orderReportApplication.DepartmentalProcessingStatisticsNew(dto);

            var total = new DepartmentalProcessingStatisticsDataDto
            {
                OrgCode = "",
                OrgName = "合计",
                OrgType = EOrgType.City,
                // OrderCountNum = items.Sum(p => p.OrderCountNum),
                YbOrderCountNum = items.Sum(p => p.YbOrderCountNum),
                ZbOrderCountNum = items.Sum(p => p.ZbOrderCountNum),
                Archived = items.Sum(p => p.Archived),
                ToBeArchived = items.Sum(p => p.ToBeArchived),
                WaitPublished = items.Sum(p => p.WaitPublished),
                PublishedOpen = items.Sum(p => p.PublishedOpen),
                PublishedNoOpen = items.Sum(p => p.PublishedNoOpen),
                YbOverdue = items.Sum(p => p.YbOverdue),
                ZbOverdue = items.Sum(p => p.ZbOverdue),
                CompleteOnTime = items.Sum(p => p.CompleteOnTime),
                HqybOverdue = items.Sum(p => p.HqybOverdue),
                HqzbOverdue = items.Sum(p => p.HqzbOverdue),
                DelayEnd = items.Sum(p => p.DelayEnd),
                DelayWait = items.Sum(p => p.DelayWait),
                OrderDelayCount = items.Sum(p => p.OrderDelayCount),
                ScreenCount = items.Sum(p => p.ScreenCount),
                ScreenApproval = items.Sum(p => p.ScreenApproval),
                ScreenPass = items.Sum(p => p.ScreenPass),
                ScreenNotPass = items.Sum(p => p.ScreenNotPass),
                SatisfactionCount = items.Sum(p => p.SatisfactionCount),
                NotSatisfactionCount = items.Sum(p => p.NotSatisfactionCount)
            };
            return new { List = items, Total = total };
        }

        /// <summary>
        /// 部门办件统计表--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("departmental_processing_statistics_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentalProcessingStatistics([FromBody] ExportExcelDto<DepartmentalProcessingStatisticsRequest> dto)
        {
            var list = new List<DepartmentalProcessingStatisticsDataDto>();
            if (_appOptions.Value.IsLuZhou == true)
                list = await _orderReportApplication.LZDepartmentalProcessingStatisticsNew(dto.QueryDto);
            else
                list = await _orderReportApplication.DepartmentalProcessingStatisticsNew(dto.QueryDto);

            //增加合计
            list.Add(new DepartmentalProcessingStatisticsDataDto
            {
                OrgCode = "",
                OrgName = "合计",
                OrgType = EOrgType.City,
                // OrderCountNum = items.Sum(p => p.OrderCountNum),
                YbOrderCountNum = list.Sum(p => p.YbOrderCountNum),
                ZbOrderCountNum = list.Sum(p => p.ZbOrderCountNum),
                Archived = list.Sum(p => p.Archived),
                ToBeArchived = list.Sum(p => p.ToBeArchived),
                WaitPublished = list.Sum(p => p.WaitPublished),
                PublishedOpen = list.Sum(p => p.PublishedOpen),
                PublishedNoOpen = list.Sum(p => p.PublishedNoOpen),
                YbOverdue = list.Sum(p => p.YbOverdue),
                ZbOverdue = list.Sum(p => p.ZbOverdue),
                CompleteOnTime = list.Sum(p => p.CompleteOnTime),
                HqybOverdue = list.Sum(p => p.HqybOverdue),
                HqzbOverdue = list.Sum(p => p.HqzbOverdue),
                DelayEnd = list.Sum(p => p.DelayEnd),
                DelayWait = list.Sum(p => p.DelayWait),
                OrderDelayCount = list.Sum(p => p.OrderDelayCount),
                ScreenCount = list.Sum(p => p.ScreenCount),
                ScreenApproval = list.Sum(p => p.ScreenApproval),
                ScreenPass = list.Sum(p => p.ScreenPass),
                ScreenNotPass = list.Sum(p => p.ScreenNotPass),
                SatisfactionCount = list.Sum(p => p.SatisfactionCount),
                NotSatisfactionCount = list.Sum(p => p.NotSatisfactionCount)
            });

            var orderDtos = _mapper.Map<ICollection<DepartmentalProcessingStatisticsDataDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<DepartmentalProcessingStatisticsDataDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(DepartmentalProcessingStatisticsDataDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门办件统计表数据");
        }

        /// <summary>
        /// 部门办件统计表--子级
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("departmental_processing_child_statistics")]
        public async Task<object> DepartmentalProcessingChildStatistics([FromQuery] DepartmentalProcessingStatisticsRequest dto)
        {
            var items = new List<DepartmentalProcessingStatisticsDataDto>();
            if (_appOptions.Value.IsLuZhou == true)
                items = await _orderReportApplication.LZDepartmentalProcessingChildStatisticsNew(dto);
            else
                items = await _orderReportApplication.DepartmentalProcessingChildStatisticsNew(dto);

            //计算合计
            var total = new DepartmentalProcessingStatisticsDataDto
            {
                OrgCode = "",
                OrgName = "合计",
                OrgType = EOrgType.City,
                // OrderCountNum = items.Sum(p => p.OrderCountNum),
                YbOrderCountNum = items.Sum(p => p.YbOrderCountNum),
                ZbOrderCountNum = items.Sum(p => p.ZbOrderCountNum),
                Archived = items.Sum(p => p.Archived),
                ToBeArchived = items.Sum(p => p.ToBeArchived),
                WaitPublished = items.Sum(p => p.WaitPublished),
                PublishedOpen = items.Sum(p => p.PublishedOpen),
                PublishedNoOpen = items.Sum(p => p.PublishedNoOpen),
                YbOverdue = items.Sum(p => p.YbOverdue),
                ZbOverdue = items.Sum(p => p.ZbOverdue),
                CompleteOnTime = items.Sum(p => p.CompleteOnTime),
                HqybOverdue = items.Sum(p => p.HqybOverdue),
                HqzbOverdue = items.Sum(p => p.HqzbOverdue),
                DelayEnd = items.Sum(p => p.DelayEnd),
                DelayWait = items.Sum(p => p.DelayWait),
                OrderDelayCount = items.Sum(p => p.OrderDelayCount),
                ScreenCount = items.Sum(p => p.ScreenCount),
                ScreenApproval = items.Sum(p => p.ScreenApproval),
                ScreenPass = items.Sum(p => p.ScreenPass),
                ScreenNotPass = items.Sum(p => p.ScreenNotPass),
                SatisfactionCount = items.Sum(p => p.SatisfactionCount),
                NotSatisfactionCount = items.Sum(p => p.NotSatisfactionCount)
            };
            return new { List = items, Total = total };
        }

        /// <summary>
        /// 部门办件统计表--子级--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("departmental_processing_child_statistics_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentalProcessingChildStatistics([FromBody] ExportExcelDto<DepartmentalProcessingStatisticsRequest> dto)
        {
            var list = new List<DepartmentalProcessingStatisticsDataDto>();
            if (_appOptions.Value.IsLuZhou == true)
                list = await _orderReportApplication.LZDepartmentalProcessingChildStatisticsNew(dto.QueryDto);
            else
                list = await _orderReportApplication.DepartmentalProcessingChildStatisticsNew(dto.QueryDto);

            //增加合计
            list.Add(new DepartmentalProcessingStatisticsDataDto
            {
                OrgCode = "",
                OrgName = "合计",
                OrgType = EOrgType.City,
                // OrderCountNum = items.Sum(p => p.OrderCountNum),
                YbOrderCountNum = list.Sum(p => p.YbOrderCountNum),
                ZbOrderCountNum = list.Sum(p => p.ZbOrderCountNum),
                Archived = list.Sum(p => p.Archived),
                ToBeArchived = list.Sum(p => p.ToBeArchived),
                WaitPublished = list.Sum(p => p.WaitPublished),
                PublishedOpen = list.Sum(p => p.PublishedOpen),
                PublishedNoOpen = list.Sum(p => p.PublishedNoOpen),
                YbOverdue = list.Sum(p => p.YbOverdue),
                ZbOverdue = list.Sum(p => p.ZbOverdue),
                CompleteOnTime = list.Sum(p => p.CompleteOnTime),
                HqybOverdue = list.Sum(p => p.HqybOverdue),
                HqzbOverdue = list.Sum(p => p.HqzbOverdue),
                DelayEnd = list.Sum(p => p.DelayEnd),
                DelayWait = list.Sum(p => p.DelayWait),
                OrderDelayCount = list.Sum(p => p.OrderDelayCount),
                ScreenCount = list.Sum(p => p.ScreenCount),
                ScreenApproval = list.Sum(p => p.ScreenApproval),
                ScreenPass = list.Sum(p => p.ScreenPass),
                ScreenNotPass = list.Sum(p => p.ScreenNotPass),
                SatisfactionCount = list.Sum(p => p.SatisfactionCount),
                NotSatisfactionCount = list.Sum(p => p.NotSatisfactionCount)
            });

            var orderDtos = _mapper.Map<ICollection<DepartmentalProcessingStatisticsDataDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<DepartmentalProcessingStatisticsDataDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(DepartmentalProcessingStatisticsDataDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门办件统计表数据");
        }

        /// <summary>
        /// 部门办件统计表--明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("departmental_processing_statistics_list")]
        public async Task<PagedDto<OrderDto>> GetDepartmentalProcessingStatisticsList([FromQuery] DepartmentalProcessingStatisticsRequest dto)
        {
            RefAsync<int> total = 0;

            ISugarQueryable<SelectOrderId> query;
            if (_appOptions.Value.IsLuZhou == true)
                query = _orderReportApplication.LZGetDepartmentalProcessingStatisticsListNew(dto, HttpContext.RequestAborted);
            else
                query = _orderReportApplication.GetDepartmentalProcessingStatisticsListNew(dto, HttpContext.RequestAborted);

            var queryData = await query
                        .LeftJoin<Order>((x, o) => x.Id == o.Id)
                        .OrderByIF(string.IsNullOrEmpty(dto.SortField), (x, o) => o.CreationTime, OrderByType.Desc)
                        .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, (x, o) => o.StartTime, OrderByType.Asc) //受理时间升序
                        .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, (x, o) => o.StartTime, OrderByType.Desc) //受理时间降序
                        .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, (x, o) => o.ExpiredTime, OrderByType.Asc) //工单期满时间升序
                        .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, (x, o) => o.ExpiredTime, OrderByType.Desc) //工单期满时间降序
                        .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, (x, o) => o.FiledTime, OrderByType.Asc)// 办结时间升序
                        .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, (x, o) => o.FiledTime, OrderByType.Desc) //办结时间降序
                         .Select((x, o) => new { o })
                        .ToPageListAsync(dto.PageIndex, dto.PageSize, total, HttpContext.RequestAborted);

            var dtos = queryData.Select(d =>
            {
                var dto = _mapper.Map<OrderDto>(d.o);
                return dto;
            }).ToList();
            return new PagedDto<OrderDto>(total, dtos);
        }

        /// <summary>
        /// 部门办件统计表--明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("departmental_processing_statistics_list_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportGetDepartmentalProcessingStatisticsList([FromBody] ExportExcelDto<DepartmentalProcessingStatisticsRequest> dto)
        {
            ISugarQueryable<SelectOrderId> queryDa;
            if (_appOptions.Value.IsLuZhou == true)
                queryDa = _orderReportApplication.LZGetDepartmentalProcessingStatisticsListNew(dto.QueryDto, HttpContext.RequestAborted);
            else
                queryDa = _orderReportApplication.GetDepartmentalProcessingStatisticsListNew(dto.QueryDto, HttpContext.RequestAborted);

            var query = queryDa
                 .LeftJoin<Order>((x, o) => x.Id == o.Id)
                .OrderByIF(string.IsNullOrEmpty(dto.QueryDto.SortField), (x, o) => o.CreationTime, OrderByType.Desc)
                .OrderByIF(dto.QueryDto is { SortField: "startTime", SortRule: 0 }, (x, o) => o.StartTime, OrderByType.Asc) //受理时间升序
                .OrderByIF(dto.QueryDto is { SortField: "startTime", SortRule: 1 }, (x, o) => o.StartTime, OrderByType.Desc) //受理时间降序
                .OrderByIF(dto.QueryDto is { SortField: "expiredTime", SortRule: 0 }, (x, o) => o.ExpiredTime, OrderByType.Asc) //工单期满时间升序
                .OrderByIF(dto.QueryDto is { SortField: "expiredTime", SortRule: 1 }, (x, o) => o.ExpiredTime, OrderByType.Desc) //工单期满时间降序
                .OrderByIF(dto.QueryDto is { SortField: "filedTime", SortRule: 0 }, (x, o) => o.FiledTime, OrderByType.Asc)// 办结时间升序
                .OrderByIF(dto.QueryDto is { SortField: "filedTime", SortRule: 1 }, (x, o) => o.FiledTime, OrderByType.Desc) //办结时间降序
                 .Select((x, o) => new { o });
            List<OrderDto> list = new List<OrderDto>();
            if (dto.IsExportAll)
            {
                var listData = await query.ToListAsync(HttpContext.RequestAborted);
                list = listData.Select(d =>
                {
                    var dto = _mapper.Map<OrderDto>(d.o);
                    return dto;
                }).ToList();
            }
            else
            {
                RefAsync<int> total = 0;
                var listData = await query.ToPageListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, total, HttpContext.RequestAborted);
                list = listData.Select(d =>
                {
                    var dto = _mapper.Map<OrderDto>(d.o);
                    return dto;
                }).ToList();
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门办件统计明细数据");
        }

        /// <summary>
        /// 部门办件统计明细表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("departmental_processing_statistics_details_list")]
        public async Task<PagedDto<OrderDto>> DepartmentalProcessingStatisticsDetailsList([FromQuery] DepartmentalProcessingStatisticsRequest dto)
        {
            RefAsync<int> total = 0;

            ISugarQueryable<SelectOrderId> query;
            if (_appOptions.Value.IsLuZhou == true)
                query = _orderReportApplication.LZDepartmentalProcessingStatisticsDetailsList(dto);
            else
                query = _orderReportApplication.DepartmentalProcessingStatisticsDetailsList(dto);

            var queryData = await query.LeftJoin<Order>((x, o) => x.Id == o.Id)
                        .OrderByIF(string.IsNullOrEmpty(dto.SortField), (x, o) => o.CreationTime, OrderByType.Desc)
                        .OrderByIF(dto is { SortField: "startTime", SortRule: 0 }, (x, o) => o.StartTime, OrderByType.Asc) //受理时间升序
                        .OrderByIF(dto is { SortField: "startTime", SortRule: 1 }, (x, o) => o.StartTime, OrderByType.Desc) //受理时间降序
                        .OrderByIF(dto is { SortField: "expiredTime", SortRule: 0 }, (x, o) => o.ExpiredTime, OrderByType.Asc) //工单期满时间升序
                        .OrderByIF(dto is { SortField: "expiredTime", SortRule: 1 }, (x, o) => o.ExpiredTime, OrderByType.Desc) //工单期满时间降序
                        .OrderByIF(dto is { SortField: "filedTime", SortRule: 0 }, (x, o) => o.FiledTime, OrderByType.Asc)// 办结时间升序
                        .OrderByIF(dto is { SortField: "filedTime", SortRule: 1 }, (x, o) => o.FiledTime, OrderByType.Desc) //办结时间降序
                        .Select((x, o) => new { o })

                        .ToPageListAsync(dto.PageIndex, dto.PageSize, total, HttpContext.RequestAborted);

            var dtos = queryData.Select(d =>
            {
                var dto = _mapper.Map<OrderDto>(d.o);
                return dto;
            }).ToList();
            return new PagedDto<OrderDto>(total, dtos);
        }

        /// <summary>
        /// 部门办件统计明细表--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("departmental_processing_statistics_details_list_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportDepartmentalProcessingStatisticsDetailsList([FromBody] ExportExcelDto<DepartmentalProcessingStatisticsRequest> dto)
        {
            ISugarQueryable<SelectOrderId> queryDa;
            if (_appOptions.Value.IsLuZhou == true)
                queryDa = _orderReportApplication.LZDepartmentalProcessingStatisticsDetailsList(dto.QueryDto);
            else
                queryDa = _orderReportApplication.DepartmentalProcessingStatisticsDetailsList(dto.QueryDto);


            var query = queryDa.LeftJoin<Order>((x, o) => x.Id == o.Id)
                  .OrderByIF(string.IsNullOrEmpty(dto.QueryDto.SortField), (x, o) => o.CreationTime, OrderByType.Desc)
                        .OrderByIF(dto.QueryDto is { SortField: "startTime", SortRule: 0 }, (x, o) => o.StartTime, OrderByType.Asc) //受理时间升序
                        .OrderByIF(dto.QueryDto is { SortField: "startTime", SortRule: 1 }, (x, o) => o.StartTime, OrderByType.Desc) //受理时间降序
                        .OrderByIF(dto.QueryDto is { SortField: "expiredTime", SortRule: 0 }, (x, o) => o.ExpiredTime, OrderByType.Asc) //工单期满时间升序
                        .OrderByIF(dto.QueryDto is { SortField: "expiredTime", SortRule: 1 }, (x, o) => o.ExpiredTime, OrderByType.Desc) //工单期满时间降序
                        .OrderByIF(dto.QueryDto is { SortField: "filedTime", SortRule: 0 }, (x, o) => o.FiledTime, OrderByType.Asc)// 办结时间升序
                        .OrderByIF(dto.QueryDto is { SortField: "filedTime", SortRule: 1 }, (x, o) => o.FiledTime, OrderByType.Desc) //办结时间降序
                  .Select((x, o) => new { o });
            var list = new List<OrderDto>();
            if (dto.IsExportAll)
            {
                var listData = await query.ToListAsync(HttpContext.RequestAborted);
                list = listData.Select(d =>
                {
                    var dto = _mapper.Map<OrderDto>(d.o);
                    return dto;
                }).ToList();
            }
            else
            {
                RefAsync<int> total = 0;
                var listData = await query.ToPageListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, total, HttpContext.RequestAborted);
                list = listData.Select(d =>
                {
                    var dto = _mapper.Map<OrderDto>(d.o);
                    return dto;
                }).ToList();
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门办件统计明细表数据");
        }

        /// <summary>
        /// 高频来电统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("high_frequency_call_statistics")]
        public async Task<PagedDto<HighFrequencyCallStatisticsDto>> HighFrequencyCallStatistics([FromQuery] HighFrequencyCallStatisticsRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");

            int CallCount = 2;
            var HighFrequencyCallStatistics = _systemSettingCacheManager.GetSetting(SettingConstants.HighFrequencyCallStatistics)?.SettingValue[0];
            if (HighFrequencyCallStatistics != null)
                CallCount = int.Parse(HighFrequencyCallStatistics);

            var (total, items) = await _trCallRecordRepository.Queryable()
                     .LeftJoin<Order>((p, o) => p.ExternalId == o.Id)
                   .Where((p, o) => p.OverTime >= dto.StartTime && p.OverTime <= dto.EndTime)
                   .Where((p, o) => p.CallOrderType == ECallOrderType.Order)
                   .Where((p, o) => p.ExternalId != null && o.Id != null)
                   .Where((p, o) => p.CallDirection == ECallDirection.In)
                    .WhereIF(!string.IsNullOrEmpty(dto.PhoneNum), (p, o) => p.CPN == dto.PhoneNum)
                   .Select((p, o) => new
                   {
                       p.CPN,
                       p.ExternalId
                   })
                   .MergeTable()
                   .GroupBy(p => p.CPN)
                   .Select(p => new HighFrequencyCallStatisticsDto
                   {
                       Callnum = p.CPN,
                       OrderCountNum = SqlFunc.AggregateCount(p.CPN),//总量
                   })
                  .MergeTable()
                 .Where(p => p.OrderCountNum >= CallCount)
                 .OrderByDescending(p => p.OrderCountNum)
                 .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<HighFrequencyCallStatisticsDto>(total, _mapper.Map<IReadOnlyList<HighFrequencyCallStatisticsDto>>(items));
        }

        /// <summary>
        /// 高频来电统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("high_frequency_call_statistics/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HighFrequencyCallStatisticsExport([FromBody] ExportExcelDto<HighFrequencyCallStatisticsRequest> dto)
        {
            if (!dto.QueryDto.StartTime.HasValue || !dto.QueryDto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");

            int CallCount = 2;
            var HighFrequencyCallStatistics = _systemSettingCacheManager.GetSetting(SettingConstants.HighFrequencyCallStatistics)?.SettingValue[0];
            if (HighFrequencyCallStatistics != null)
                CallCount = int.Parse(HighFrequencyCallStatistics);

            var query = _trCallRecordRepository.Queryable()
                     .LeftJoin<Order>((p, o) => p.ExternalId == o.Id)
                   .Where((p, o) => p.OverTime >= dto.QueryDto.StartTime && p.OverTime <= dto.QueryDto.EndTime)
                   .Where((p, o) => p.CallOrderType == ECallOrderType.Order)
                   .Where((p, o) => p.ExternalId != null && o.Id != null)
                   .Where((p, o) => p.CallDirection == ECallDirection.In)
                    .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.PhoneNum), (p, o) => p.CPN == dto.QueryDto.PhoneNum)
                   .Select((p, o) => new
                   {
                       p.CPN,
                       p.ExternalId
                   })
                   .MergeTable()
                   .GroupBy(p => p.CPN)
                   .Select(p => new HighFrequencyCallStatisticsDto
                   {
                       Callnum = p.CPN,
                       OrderCountNum = SqlFunc.AggregateCount(p.CPN),//总量
                   })
                  .MergeTable()
                 .Where(p => p.OrderCountNum >= CallCount)
                 .OrderByDescending(p => p.OrderCountNum);

            var total = 0;
            var items = new List<HighFrequencyCallStatisticsDto>();
            if (dto.IsExportAll)
            {
                items = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                (total, items) = await query.ToPagedListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, HttpContext.RequestAborted);
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<HighFrequencyCallStatisticsDto>(dto.ColumnInfos);
            var dtos = _mapper.Map<ICollection<HighFrequencyCallStatisticsDto>>(items)
                              .Select(stu => _mapper.Map(stu, typeof(HighFrequencyCallStatisticsDto), dynamicClass))
                              .Cast<object>()
                              .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "高频来电统计");
        }

        /// <summary>
        /// 高频来电统计列表详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("high_frequency_call_statistics_order_list")]
        public async Task<PagedDto<OrderDto>> HighFrequencyCallStatisticsOrderList([FromQuery] HighFrequencyCallStatisticsListRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");
            if (string.IsNullOrEmpty(dto.FromPhone))
                throw UserFriendlyException.SameMessage("号码不能为空!");

            var data = await _trCallRecordRepository.Queryable()
                    .LeftJoin<Order>((p, o) => p.ExternalId == o.Id)
                   .Where((p, o) => p.OverTime >= dto.StartTime && p.OverTime <= dto.EndTime)
                   .Where((p, o) => p.CallOrderType == ECallOrderType.Order)
                   .Where((p, o) => p.ExternalId != null && o.Id != null)
                    .Where((p, o) => p.CPN == dto.FromPhone)
                   .Where((p, o) => p.CallDirection == ECallDirection.In)
                   .Select((p, o) =>
                       p.ExternalId
                   )
                  .ToListAsync();


            var (total, items) = await _orderRepository.Queryable()
           .Includes(x => x.OrderScreens)
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Title.StartsWith(dto.Keyword!)) //标题
            .WhereIF(!string.IsNullOrEmpty(dto.ProvinceNo), d => d.ProvinceNo == dto.ProvinceNo) //省本地编号
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No == 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.OrgId), d => d.CurrentHandleOrgId == dto.OrgId)//接办部门
            .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.EmergencyLevels.Any(), d => dto.EmergencyLevels.Contains(d.EmergencyLevel))  //紧急程度
            .WhereIF(!string.IsNullOrEmpty(dto.FromPhone), d => d.FromPhone == dto.FromPhone) //来电号码
            .WhereIF(!string.IsNullOrEmpty(dto.PhoneNo), d => d.Contact == dto.PhoneNo!) //联系电话
            //.WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), d => d.PushTypeCode == dto.PushTypeCode) //推送分类
            .WhereIF(!string.IsNullOrEmpty(dto.PushTypeCode), d => d.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.ActualHandleStepCode == dto.CurrentStepCode) //当前办理节点
            .WhereIF(dto.ActualHandleTimeStart.HasValue, d => d.ActualHandleTime >= dto.ActualHandleTimeStart) //办结时间开始
            .WhereIF(dto.ActualHandleTimeEnd.HasValue, d => d.ActualHandleTime <= dto.ActualHandleTimeEnd) //办结时间结束
            .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(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(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == true, x => x.IsProvince == true)
            .WhereIF(dto.IsProvinceOrder.HasValue && dto.IsProvinceOrder == false, x => x.IsProvince == false)
           .OrderByDescending(d => d.CreationTime)
           .ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));

        }

        /// <summary>
        /// 高频事项预警
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("highmatter-warning")]
        public async Task<PagedDto<HighMatterWarningDto>> HighMatterWarning([FromQuery] HighMatterWarningRequest dto)
        {
            var filterTitle = _systemSettingCacheManager.GetSetting(SettingConstants.HighMatterWarningFilterTitle).SettingValue;

            var (total, items) = await _orderRepository.Queryable()
                .Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
                .Where(x => filterTitle.Any(s => x.Title.Contains(s)) == false)
                .LeftJoin<SystemArea>((it, o) => it.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")) == o.Id)
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), x => x.AcceptTypeCode == dto.AcceptType)//受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), x => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.Hotspot))//热点类型
                .WhereIF(!string.IsNullOrEmpty(dto.AreaCode), x => x.AreaCode == dto.AreaCode)//区域
                .GroupBy((it, o) => new
                {
                    it.AcceptTypeCode,
                    it.AcceptType,
                    it.HotspotId,
                    it.HotspotName,
                    AreaCode = it.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                    o.AreaName,
                })
                .Having((it, o) => SqlFunc.AggregateCount(it.HotspotName) >= 5)
                .Select((it, o) => new HighMatterWarningDto()
                {
                    AcceptTypeCode = it.AcceptTypeCode,
                    AcceptType = it.AcceptType,
                    AreaName = o.AreaName,
                    HotspotName = it.HotspotName,
                    HotspotId = it.HotspotId,
                    SumCount = SqlFunc.AggregateCount(it.HotspotName),
                    Id = SqlFunc.AggregateMin(it.Id),
                    AreaCode = it.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))
                })
                .MergeTable()
                .LeftJoin<Order>((x, d) => x.Id == d.Id)
                .Select((x, d) => new HighMatterWarningDto()
                {
                    AreaName = x.AreaName,
                    HotspotName = x.HotspotName,
                    HotspotId = x.HotspotId,
                    Title = d.Title,
                    SumCount = x.SumCount,
                    Id = d.Id,
                    AcceptTypeCode = x.AcceptTypeCode,
                    AcceptType = x.AcceptType,
                    AreaCode = x.AreaCode
                })
                .MergeTable()
                .OrderByDescending(d => d.SumCount).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<HighMatterWarningDto>(total, _mapper.Map<IReadOnlyList<HighMatterWarningDto>>(items));
        }

        /// <summary>
        /// 高频事项预警
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("highmatter-warning/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HighMatterWarningExport([FromBody] ExportExcelDto<HighMatterWarningRequest> dto)
        {
            var filterTitle = _systemSettingCacheManager.GetSetting(SettingConstants.HighMatterWarningFilterTitle).SettingValue;

            var query = _orderRepository.Queryable()
                .Where(x => x.CreationTime >= dto.QueryDto.StartTime && x.CreationTime <= dto.QueryDto.EndTime)
                .Where(x => filterTitle.Any(s => x.Title.Contains(s)) == false)
                .LeftJoin<SystemArea>((it, o) => it.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")) == o.Id)
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.AcceptType), x => x.AcceptTypeCode == dto.QueryDto.AcceptType)//受理类型
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.Hotspot), x => x.HotspotSpliceName != null && x.HotspotSpliceName.Contains(dto.QueryDto.Hotspot))//热点类型
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.AreaCode), x => x.AreaCode == dto.QueryDto.AreaCode)//区域
                .GroupBy((it, o) => new
                {
                    it.AcceptTypeCode,
                    it.AcceptType,
                    it.HotspotId,
                    it.HotspotName,
                    AreaCode = it.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                    o.AreaName,
                })
                .Having((it, o) => SqlFunc.AggregateCount(it.HotspotName) >= 5)
                .Select((it, o) => new HighMatterWarningDto()
                {
                    AcceptTypeCode = it.AcceptTypeCode,
                    AcceptType = it.AcceptType,
                    AreaName = o.AreaName,
                    HotspotName = it.HotspotName,
                    HotspotId = it.HotspotId,
                    SumCount = SqlFunc.AggregateCount(it.HotspotName),
                    Id = SqlFunc.AggregateMin(it.Id),
                    AreaCode = it.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))
                })
                .MergeTable()
                .LeftJoin<Order>((x, d) => x.Id == d.Id)
                .Select((x, d) => new HighMatterWarningDto()
                {
                    AreaName = x.AreaName,
                    HotspotName = x.HotspotName,
                    HotspotId = x.HotspotId,
                    Title = d.Title,
                    SumCount = x.SumCount,
                    Id = d.Id,
                    AcceptTypeCode = x.AcceptTypeCode,
                    AcceptType = x.AcceptType,
                    AreaCode = x.AreaCode
                })
                .MergeTable()
                .OrderByDescending(d => d.SumCount);

            var total = 0;
            var items = new List<HighMatterWarningDto>();
            if (dto.IsExportAll)
            {
                items = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                (total, items) = await query.ToPagedListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, HttpContext.RequestAborted);
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<HighMatterWarningDto>(dto.ColumnInfos);
            var dtos = _mapper.Map<ICollection<HighMatterWarningDto>>(items)
                              .Select(stu => _mapper.Map(stu, typeof(HighMatterWarningDto), dynamicClass))
                              .Cast<object>()
                              .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "高频事项预警");
        }

        /// <summary>
        /// 高频事项预警明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("highmatter-warning-detail")]
        public async Task<PagedDto<OrderDto>> HighMatterWarningDetail([FromQuery] HighMatterWarningDetailRequest dto)
        {
            var filterTitle = _systemSettingCacheManager.GetSetting(SettingConstants.HighMatterWarningFilterTitle).SettingValue;

            var (total, items) = await _orderRepository.Queryable()
            .Includes(x => x.OrderScreens)
            .Where(d => d.AcceptTypeCode == dto.AcceptTypeCode) //受理类型
            .Where(d => d.HotspotId == dto.HotspotId) //热点类型
            .Where(d => d.CreationTime >= dto.StartTime) //受理时间开始
            .Where(d => d.CreationTime <= dto.EndTime) //受理时间结束
            .Where(d => d.AreaCode == dto.AreaCode) //区域
            .Where(x => filterTitle.Any(s => x.Title.Contains(s)) == false)
            .OrderByDescending(d => d.CreationTime)
            .ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 回退错件
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("reTransact")]
        public async Task<PagedDto<OrderReTransactVo>> OrderReTransact([FromQuery] QueryOrderReTransactRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");
            var query = _orderApplication.OrderReTransact(dto);
            var (total, items) = await query
                .ToPagedListAsync(dto, HttpContext.RequestAborted);
            items.Add(new OrderReTransactVo
            {
                OrgName = "合计",
                Num = items.Select(s => s.Num).Sum(),
            });
            return new PagedDto<OrderReTransactVo>(total, _mapper.Map<IReadOnlyList<OrderReTransactVo>>(items));
        }

        /// <summary>
        /// 回退错件导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("reTransact/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderReTransactExport([FromBody] ExportExcelDto<QueryOrderReTransactRequest> dto)
        {
            var query = _orderApplication.OrderReTransact(dto.QueryDto);
            List<OrderReTransactVo> data;
            data = await query.ToListAsync(HttpContext.RequestAborted);
            data.Add(new OrderReTransactVo
            {
                OrgName = "合计",
                Num = data.Select(s => s.Num).Sum(),
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderReTransactVo>(dto.ColumnInfos);
            var dtos = data
             .Select(stu => _mapper.Map(stu, typeof(OrderReTransactVo), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "回退错件统计数据");
        }

        /// <summary>
        /// 回退错件明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("reTransact_detail")]
        public async Task<PagedDto<OrderSpecialDetailDto>> OrderReTransactDetail([FromQuery] QueryOrderReTransactDetailRequest dto)
        {
            var query = _orderApplication.QueryOrderSourceDetail(dto);
            var (total, items) = await
                query.ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<OrderSpecialDetailDto>(total, _mapper.Map<IReadOnlyList<OrderSpecialDetailDto>>(items));
        }

        /// <summary>
        /// 回退错件明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("reTransact_detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderReTransactDetailExport([FromBody] ExportExcelDto<QueryOrderReTransactDetailRequest> dto)
        {
            var query = _orderApplication.QueryOrderSourceDetail(dto.QueryDto);
            List<OrderSpecialDetail> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<OrderSpecialDetailDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderSpecialDetailDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderSpecialDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "回退错件明细列表数据");
        }

        /// <summary>
        /// 获取基本信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("reTransact_base")]
        public async Task<object> ReTransactBaseData()
        {
            var rsp = new
            {
                ReTransactErrorType = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.ReTransactErrorType),
            };
            return rsp;
        }

        /// <summary>
        /// 派单量统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("send_order_report")]
        public async Task<List<SendOrderReportOutDto>> SendOrderReport([FromQuery] QuerySendOrderRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");
            return await _orderApplication.SendOrderReportAsync(dto);
        }

        /// <summary>
        /// 派单量统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("send_order_report/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportSendOrderReport([FromBody] ExportExcelDto<QuerySendOrderRequest> dto)
        {
            if (!dto.QueryDto.StartTime.HasValue || !dto.QueryDto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");
            var list = await _orderApplication.SendOrderReportAsync(dto.QueryDto);

            if (list != null && list.Count > 0)
            {
                list.Add(new SendOrderReportOutDto()
                {
                    UserName = "合计",
                    SendOrderNum = list.Sum(p => p.SendOrderNum),
                    NoSendOrderNum = list.Sum(p => p.NoSendOrderNum),
                    ReSendOrderNum = list.Sum(p => p.ReSendOrderNum),
                });
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SendOrderReportOutDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(SendOrderReportOutDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "派单量统计");

        }


        /// <summary>
        /// 派单量统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("send_order_detail_report")]
        public async Task<PagedDto<OrderDto>> QuerySendOrderDetail([FromQuery] QuerySendOrderDetailRequest dto)
        {
            if (!dto.StartTime.HasValue || !dto.EndTime.HasValue)
                throw UserFriendlyException.SameMessage("请选择时间!");

            var (total, items) = await _orderApplication.QuerySendOrderDetail(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }


        /// <summary>
        /// 派单量统计明细
        /// </summary>
        /// <returns></returns>
        [HttpPost("send_order_detail_report/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QuerySendOrderDetailExport([FromBody] ExportExcelDto<QuerySendOrderDetailRequest> dto)
        {
            var query = _orderApplication.QuerySendOrderDetail(dto.QueryDto);
            List<Order> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var secondaryHandlingDtos = _mapper.Map<ICollection<OrderDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = secondaryHandlingDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "派单量明细数据");
        }

        /// <summary>
        /// 二次办理统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("secondary_handling_report")]
        public async Task<List<SecondaryHandlingVo>> SecondaryHandlingReport([FromQuery] QuerySecondaryHandlingRequest dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingReport(dto, HttpContext.RequestAborted);
            return await query.ToListAsync();
        }

        /// <summary>
        /// 二次办理统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("secondary_handling_report/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SecondaryHandlingReportExport([FromBody] ExportExcelDto<QuerySecondaryHandlingRequest> dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingReport(dto.QueryDto, HttpContext.RequestAborted);
            List<SecondaryHandlingVo> secondaryHandling;
            secondaryHandling = await query.ToListAsync(HttpContext.RequestAborted);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SecondaryHandlingVo>(dto.ColumnInfos);
            var dtos = secondaryHandling
                .Select(stu => _mapper.Map(stu, typeof(SecondaryHandlingVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "二次办理统计数据");
        }

        /// <summary>
        /// 二次办理明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("secondary_handling_detail_report")]
        public async Task<PagedDto<OrderSecondaryHandlingDto>> SecondaryHandlingDetailReport([FromQuery] QuerySecondaryHandlingRequest dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingDetailReport(dto, HttpContext.RequestAborted);
            var (total, items) = await query.ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderSecondaryHandlingDto>(total, _mapper.Map<IReadOnlyList<OrderSecondaryHandlingDto>>(items));
        }

        /// <summary>
        /// 二次办理明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("secondary_handling_detail_report/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SecondaryHandlingDetailReportExport([FromBody] ExportExcelDto<QuerySecondaryHandlingRequest> dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingDetailReport(dto.QueryDto, HttpContext.RequestAborted);
            List<OrderSecondaryHandling> secondaryHandling;
            if (dto.IsExportAll)
            {
                secondaryHandling = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                secondaryHandling = items;
            }

            var secondaryHandlingDtos = _mapper.Map<ICollection<OrderSecondaryHandlingDto>>(secondaryHandling);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderSecondaryHandlingDto>(dto.ColumnInfos);

            var dtos = secondaryHandlingDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderSecondaryHandlingDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "二次办理列表数据");
        }

        /// <summary>
        /// 二次办理满意度统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("secondary_handling_satisfaction_report")]
        public async Task<List<SecondaryHandlingSatisfactionVo>> SecondaryHandlingSatisfactionReport([FromQuery] QuerySecondaryHandlingRequest dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingSatisfactionReport(dto, HttpContext.RequestAborted);
            var list = await query.ToListAsync();
            //总计
            var total = new SecondaryHandlingSatisfactionVo
            {
                OrgId = "",
                OrgName = "总计",
                TotalSumCount = list.Select(x => x.TotalSumCount).Sum(),
                VerySatisfiedCount = list.Select(x => x.VerySatisfiedCount).Sum(),
                SatisfiedCount = list.Select(x => x.SatisfiedCount).Sum(),
                RegardedAsSatisfiedCount = list.Select(x => x.RegardedAsSatisfiedCount).Sum(),
                DefaultSatisfiedCount = list.Select(x => x.DefaultSatisfiedCount).Sum(),
                NoSatisfiedCount = list.Select(x => x.NoSatisfiedCount).Sum(),
                NoEvaluateCount = list.Select(x => x.NoEvaluateCount).Sum(),
                NoPutThroughCount = list.Select(x => x.NoPutThroughCount).Sum(),
                NormalCount = list.Select(x => x.NormalCount).Sum(),//未接通
                VeryNoSatisfiedCount = list.Select(x => x.NormalCount).Sum(),//非常不满意
            };
            list.Add(total);
            //区县合计
            var countyList = list.Where(x => x.OrgType == EOrgType.County).ToList();
            var countyTotal = new SecondaryHandlingSatisfactionVo
            {
                OrgId = "",
                OrgName = "区县合计",
                TotalSumCount = countyList.Select(x => x.TotalSumCount).Sum(),
                VerySatisfiedCount = countyList.Select(x => x.VerySatisfiedCount).Sum(),
                SatisfiedCount = countyList.Select(x => x.SatisfiedCount).Sum(),
                RegardedAsSatisfiedCount = countyList.Select(x => x.RegardedAsSatisfiedCount).Sum(),
                DefaultSatisfiedCount = countyList.Select(x => x.DefaultSatisfiedCount).Sum(),
                NoSatisfiedCount = countyList.Select(x => x.NoSatisfiedCount).Sum(),
                NoEvaluateCount = countyList.Select(x => x.NoEvaluateCount).Sum(),
                NoPutThroughCount = countyList.Select(x => x.NoPutThroughCount).Sum(),
                NormalCount = countyList.Select(x => x.NormalCount).Sum(),//未接通
                VeryNoSatisfiedCount = countyList.Select(x => x.NormalCount).Sum(),//非常不满意

            };
            list.Add(countyTotal);
            //市直合计
            var cityList = list.Where(x => x.OrgType == EOrgType.City).ToList();
            var cityTotal = new SecondaryHandlingSatisfactionVo
            {
                OrgId = "",
                OrgName = "市直合计",
                TotalSumCount = cityList.Select(x => x.TotalSumCount).Sum(),
                VerySatisfiedCount = cityList.Select(x => x.VerySatisfiedCount).Sum(),
                SatisfiedCount = cityList.Select(x => x.SatisfiedCount).Sum(),
                RegardedAsSatisfiedCount = cityList.Select(x => x.RegardedAsSatisfiedCount).Sum(),
                DefaultSatisfiedCount = cityList.Select(x => x.DefaultSatisfiedCount).Sum(),
                NoSatisfiedCount = cityList.Select(x => x.NoSatisfiedCount).Sum(),
                NoEvaluateCount = cityList.Select(x => x.NoEvaluateCount).Sum(),
                NoPutThroughCount = cityList.Select(x => x.NoPutThroughCount).Sum(),
                NormalCount = cityList.Select(x => x.NormalCount).Sum(),//未接通
                VeryNoSatisfiedCount = cityList.Select(x => x.NormalCount).Sum(),//非常不满意
            };
            list.Add(cityTotal);
            return list;
        }

        /// <summary>
        /// 二次办理满意度统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("secondary_handling_satisfaction_report/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SecondaryHandlingSatisfactionReportExport([FromBody] ExportExcelDto<QuerySecondaryHandlingRequest> dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingSatisfactionReport(dto.QueryDto, HttpContext.RequestAborted);
            List<SecondaryHandlingSatisfactionVo> secondaryHandling;
            secondaryHandling = await query.ToListAsync(HttpContext.RequestAborted);
            //总计
            var total = new SecondaryHandlingSatisfactionVo
            {
                OrgId = "",
                OrgName = "总计",
                TotalSumCount = secondaryHandling.Select(x => x.TotalSumCount).Sum(),
                VerySatisfiedCount = secondaryHandling.Select(x => x.VerySatisfiedCount).Sum(),
                SatisfiedCount = secondaryHandling.Select(x => x.SatisfiedCount).Sum(),
                RegardedAsSatisfiedCount = secondaryHandling.Select(x => x.RegardedAsSatisfiedCount).Sum(),
                DefaultSatisfiedCount = secondaryHandling.Select(x => x.DefaultSatisfiedCount).Sum(),
                NoSatisfiedCount = secondaryHandling.Select(x => x.NoSatisfiedCount).Sum(),
                NoEvaluateCount = secondaryHandling.Select(x => x.NoEvaluateCount).Sum(),
                NoPutThroughCount = secondaryHandling.Select(x => x.NoPutThroughCount).Sum()
            };
            secondaryHandling.Add(total);
            //区县合计
            var countyList = secondaryHandling.Where(x => x.OrgType == EOrgType.County).ToList();
            var countyTotal = new SecondaryHandlingSatisfactionVo
            {
                OrgId = "",
                OrgName = "区县合计",
                TotalSumCount = countyList.Select(x => x.TotalSumCount).Sum(),
                VerySatisfiedCount = countyList.Select(x => x.VerySatisfiedCount).Sum(),
                SatisfiedCount = countyList.Select(x => x.SatisfiedCount).Sum(),
                RegardedAsSatisfiedCount = countyList.Select(x => x.RegardedAsSatisfiedCount).Sum(),
                DefaultSatisfiedCount = countyList.Select(x => x.DefaultSatisfiedCount).Sum(),
                NoSatisfiedCount = countyList.Select(x => x.NoSatisfiedCount).Sum(),
                NoEvaluateCount = countyList.Select(x => x.NoEvaluateCount).Sum(),
                NoPutThroughCount = countyList.Select(x => x.NoPutThroughCount).Sum()
            };
            secondaryHandling.Add(countyTotal);
            //市直合计
            var cityList = secondaryHandling.Where(x => x.OrgType == EOrgType.City).ToList();
            var cityTotal = new SecondaryHandlingSatisfactionVo
            {
                OrgId = "",
                OrgName = "市直合计",
                TotalSumCount = cityList.Select(x => x.TotalSumCount).Sum(),
                VerySatisfiedCount = cityList.Select(x => x.VerySatisfiedCount).Sum(),
                SatisfiedCount = cityList.Select(x => x.SatisfiedCount).Sum(),
                RegardedAsSatisfiedCount = cityList.Select(x => x.RegardedAsSatisfiedCount).Sum(),
                DefaultSatisfiedCount = cityList.Select(x => x.DefaultSatisfiedCount).Sum(),
                NoSatisfiedCount = cityList.Select(x => x.NoSatisfiedCount).Sum(),
                NoEvaluateCount = cityList.Select(x => x.NoEvaluateCount).Sum(),
                NoPutThroughCount = cityList.Select(x => x.NoPutThroughCount).Sum()
            };
            secondaryHandling.Add(cityTotal);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SecondaryHandlingSatisfactionVo>(dto.ColumnInfos);
            var dtos = secondaryHandling
                .Select(stu => _mapper.Map(stu, typeof(SecondaryHandlingSatisfactionVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "二次办理满意度统计数据");
        }

        /// <summary>
        /// 二次办理满意度明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("secondary_handling_satisfaction_detail_report")]
        public async Task<PagedDto<OrderSecondaryHandlingDto>> SecondaryHandlingSatisfactionDetailReport([FromQuery] QuerySecondaryHandlingRequest dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingSatisfactionDetailReport(dto, HttpContext.RequestAborted);
            var (total, items) = await query.ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderSecondaryHandlingDto>(total, _mapper.Map<IReadOnlyList<OrderSecondaryHandlingDto>>(items));
        }

        /// <summary>
        /// 二次办理满意度明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("secondary_handling_satisfaction_detail_report/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SecondaryHandlingSatisfactionDetailReport([FromBody] ExportExcelDto<QuerySecondaryHandlingRequest> dto)
        {
            var query = _orderSecondaryHandlingApplication.SecondaryHandlingSatisfactionDetailReport(dto.QueryDto, HttpContext.RequestAborted);
            List<OrderSecondaryHandling> secondaryHandling;
            if (dto.IsExportAll)
            {
                secondaryHandling = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                secondaryHandling = items;
            }

            var secondaryHandlingDtos = _mapper.Map<ICollection<OrderSecondaryHandlingDto>>(secondaryHandling);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderSecondaryHandlingDto>(dto.ColumnInfos);

            var dtos = secondaryHandlingDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderSecondaryHandlingDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "二次办理满意度列表数据");
        }

        /// <summary>
        /// 未签收统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("unsigned_order_report")]
        public async Task<PagedDto<UnsignedOrderDto>> UnsignedOrderReport([FromQuery] QueryUnsignedOrdersRequest dto)
        {
            var query = _orderApplication.QueryUnsignedOrders(dto);
            var (total, items) = await query.Select((x, ws) => new UnsignedOrder { Order = x, WorkflowStep = ws }).ToPagedListAsync(dto, HttpContext.RequestAborted);
            var itemsVo = _mapper.Map<IReadOnlyList<UnsignedOrderDto>>(items);
            foreach (var item in itemsVo)
            {
                // item.UnsignedTime = _timeLimitDomainService.CalcWorkTimeToHour(item.WorkflowStep.CreationTime, item.WorkflowStep.Status != EWorkflowStepStatus.WaitForAccept && item.WorkflowStep.AcceptTime.HasValue ?  item.WorkflowStep.AcceptTime!.Value : DateTime.Now, false);
                item.UnsignedTime = await _expireTime.CalcWorkTimeToHour(item.WorkflowStep.CreationTime, item.WorkflowStep.Status != EWorkflowStepStatus.WaitForAccept && item.WorkflowStep.AcceptTime.HasValue ? item.WorkflowStep.AcceptTime!.Value : DateTime.Now, false);
            }
            return new PagedDto<UnsignedOrderDto>(total, itemsVo);
        }

        /// <summary>
        /// 未签收统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("unsigned_order_report/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> UnsignedOrdersReport([FromBody] ExportExcelDto<QueryUnsignedOrdersRequest> dto)
        {
            var query = _orderApplication.QueryUnsignedOrders(dto.QueryDto).Select((x, ws) => new UnsignedOrder { Order = x, WorkflowStep = ws });
            List<UnsignedOrder> unsignedOrders;
            if (dto.IsExportAll)
            {
                unsignedOrders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                unsignedOrders = items;
            }

            var unsignedOrderDtos = _mapper.Map<ICollection<UnsignedOrderDto>>(unsignedOrders);

            foreach (var item in unsignedOrderDtos)
            {
                // item.UnsignedTime = _timeLimitDomainService.CalcWorkTimeToHour(
                item.UnsignedTime = await _expireTime.CalcWorkTimeToHour(
                    item.WorkflowStep.CreationTime, item.WorkflowStep.Status == EWorkflowStepStatus.WaitForAccept ? DateTime.Now : item.WorkflowStep.AcceptTime!.Value, false);
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<UnsignedOrderDto>(dto.ColumnInfos);

            var dtos = unsignedOrderDtos
                .Select(stu => _mapper.Map(stu, typeof(UnsignedOrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "未签收统计列表数据");
        }

        /// <summary>
        /// 信件来源统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_source_report")]
        public async Task<IReadOnlyList<OrderSourceVo>> QueryOrderSourceReport([FromQuery] QueryOrderSourceRequest dto)
        {
            //var count = await _orderApplication.QueryOrderSource(dto).CountAsync();
            var query = _orderApplication.QueryOrderSource(dto);
            var items = await query.GroupBy(d => d.SourceChannel).Select(d => new OrderSourceVo { Source = d.SourceChannel, Num = SqlFunc.AggregateCount(d.Id) }).ToListAsync(HttpContext.RequestAborted);
            var count = items.Sum(x => x.Num);
            items.ForEach(x => x.TotalSumCount = count);
            items.Add(new OrderSourceVo { Source = "合计", Num = count, TotalSumCount = count });
            return items;
        }

        /// <summary>
        /// 信件来源统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("order_source/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QueryOrderSourceReport([FromBody] ExportExcelDto<QueryOrderSourceRequest> dto)
        {
            //var count = await _orderApplication.QueryOrderSource(dto.QueryDto).CountAsync();
            var query = _orderApplication.QueryOrderSource(dto.QueryDto).GroupBy(d => d.SourceChannel).Select(d => new OrderSourceVo { Source = d.SourceChannel, Num = SqlFunc.AggregateCount(d.Id) });
            List<OrderSourceVo> orderSources;
            if (dto.IsExportAll)
            {
                orderSources = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orderSources = items;
            }
            var count = orderSources.Sum(x => x.Num);
            orderSources.ForEach(x => x.TotalSumCount = count);
            orderSources.Add(new OrderSourceVo { Source = "合计", Num = count, TotalSumCount = count });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderSourceVo>(dto.ColumnInfos);
            var dtos = orderSources
                .Select(stu => _mapper.Map(stu, typeof(OrderSourceVo), dynamicClass))
                .Cast<object>()
                .ToList();
            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "信件来源统计数据");
        }

        /// <summary>
        /// 信件来源统计列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_source_report_list")]
        public async Task<Object> QueryOrderSourceReportList([FromQuery] QueryOrderSourceRequest dto)
        {
            var item = await _orderRepository.OrderSource(dto);

            var titleData = await _systemDicDataRepository.Queryable()
                .Where(p => p.DicTypeCode == "SourceChannel")
                .Select(p => new
                {
                    Key = p.DicDataValue,
                    Value = p.DicDataName
                }).ToListAsync();

            return new { Item = item, TitleData = titleData };
        }

        /// <summary>
        /// 信件来源统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("order_source_list/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QueryOrderSourceListExport([FromBody] QueryOrderSourceRequest dto)
        {
            var dataTable = await _orderRepository.OrderSourceExport(dto);
            var stream = ExcelHelper.CreateStream(dataTable);
            return ExcelStreamResult(stream, "信件来源统计数据");
        }

        /// <summary>
        /// 信件来源统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_source_detail_report")]
        public async Task<PagedDto<OrderDto>> QueryOrderSourceDetailReport([FromQuery] QueryOrderSourceDetailRequest dto)
        {
            var (total, items) = await _orderApplication.QueryOrderSourceDetail(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 信件来源统计明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("order_source_detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> QueryOrderSourceDetailReport([FromBody] ExportExcelDto<QueryOrderSourceDetailRequest> dto)
        {
            var query = _orderApplication.QueryOrderSourceDetail(dto.QueryDto);
            List<Order> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }
            var ordersDtos = _mapper.Map<ICollection<OrderDto>>(orders);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);
            var dtos = ordersDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();
            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "信件来源统计明细数据");
        }

        /// <summary>
        /// 区域分时统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_area_time")]
        public async Task<object> OrderAreaTime([FromQuery] TimeSharingPagedKeywordRequest dto)
        {
            var item = await _orderRepository.OrderAreaTime(dto);

            var titleData = await _systemAreaRepository.Queryable()
                .Where(p => p.Id.Length == 6 && p.Id != "510000")
                .Select(p => new
                {
                    Key = p.Id,
                    Value = p.AreaName
                }).ToListAsync();

            return new { Item = item, TitleData = titleData };
        }

        /// <summary>
        /// 区域分时统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order_area_time_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderAreaTimeExport([FromBody] TimeSharingPagedKeywordRequest dto)
        {
            var dataTable = await _orderRepository.OrderAreaTimeExport(dto);
            var stream = ExcelHelper.CreateStream(dataTable);
            return ExcelStreamResult(stream, "区域分时统计数据");
        }

        /// <summary>
        /// 热点类型分时统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_hotspot_time")]
        public async Task<object> OrderHotspotTime([FromQuery] TimeSharingPagedKeywordRequest dto)
        {
            var item = await _orderRepository.OrderHotspotTime(dto);

            var titleData = await _hotspotRepository.Queryable()
                .Where(p => p.Id.Length == 2 && (p.ParentId == null || p.ParentId == ""))
                .Select(p => new
                {
                    Key = p.Id,
                    Value = p.HotSpotName
                }).ToListAsync();

            return new { Item = item, TitleData = titleData };
        }

        /// <summary>
        /// 热点类型分时统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order_hotspot_time_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderHotspotTimeExport([FromBody] TimeSharingPagedKeywordRequest dto)
        {
            var dataTable = await _orderRepository.OrderHotspotTimeExport(dto);
            var stream = ExcelHelper.CreateStream(dataTable);
            return ExcelStreamResult(stream, "热点类型分时统计数据");
        }

        /// <summary>
        /// 受理类型分时统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_acceptance_time")]
        public async Task<object> OrderAcceptanceTime([FromQuery] TimeSharingPagedKeywordRequest dto)
        {
            var titleData = await _systemDicDataRepository.Queryable()
                .Where(p => p.DicTypeCode == "AcceptType")
                .Select(p => new Kv()
                {
                    Key = p.DicDataValue,
                    Value = p.DicDataName
                }).OrderBy(p => p.Key).ToListAsync();

            var item = await _orderRepository.OrderAcceptanceTime(dto);
            var res = new { Item = item, TitleData = titleData };
            return res;
        }

        /// <summary>
        /// 受理类型分时统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order_acceptance_time_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderAcceptanceTimeExport([FromBody] TimeSharingPagedKeywordRequest dto)
        {
            var titleData = await _systemDicDataRepository.Queryable()
                .Where(p => p.DicTypeCode == "AcceptType")
                .Select(p => new Kv()
                {
                    Key = p.DicDataValue,
                    Value = p.DicDataName
                }).OrderBy(p => p.Key).ToListAsync();
            var dataTable = await _orderRepository.OrderAcceptanceTimeExport(dto, titleData);
            var stream = ExcelHelper.CreateStream(dataTable);
            return ExcelStreamResult(stream, "受理类型分时统计数据");
        }

        /// <summary>
        /// 信件来源分时统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order_source_time")]
        public async Task<object> OrderSourceTime([FromQuery] TimeSharingPagedKeywordRequest dto)
        {
            var item = await _orderRepository.OrderSourceTime(dto);

            var titleData = await _systemDicDataRepository.Queryable()
                .Where(p => p.DicTypeCode == "SourceChannel")
                .Select(p => new
                {
                    Key = p.DicDataValue,
                    Value = p.DicDataName
                }).ToListAsync();

            return new { Item = item, TitleData = titleData };
        }

        /// <summary>
        /// 信件来源分时统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order_source_time_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderSourceTimeExport([FromBody] TimeSharingPagedKeywordRequest dto)
        {
            var dataTable = await _orderRepository.OrderSourceTimeExport(dto);
            var stream = ExcelHelper.CreateStream(dataTable);
            return ExcelStreamResult(stream, "信件来源分时统计数据");
        }

        /// <summary>
        /// 部门满意度明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("org-visitdetail-list")]
        public async Task<PagedDto<OrgVisitDetailListResp>> OrgVisitDetailList([FromQuery] OrgVisitDetailListReq dto)
        {
            //var query = _orderReportApplication.OrgVisitDetailList(dto);
            var query = _orderRepository.OrgVisitDetailList(dto);
            var (total, items) = await query.ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<OrgVisitDetailListResp>(total, _mapper.Map<IReadOnlyList<OrgVisitDetailListResp>>(items));
        }

        /// <summary>
        /// 部门满意度明细页面基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("org-visitdetail-list-basedata")]
        public async Task<Dictionary<string, dynamic>> OrgVisitDetailListBaseData()
        {
            IReadOnlyList<SystemOrganize> items;
            if (_sessionContext.OrgIsCenter)
                items = await _systemOrganizeRepository.GetOrgJson();
            else
                items = await _systemOrganizeRepository.GetOrgJsonForUser(_sessionContext.RequiredOrgId); ;

            var wfModule = await _workflowApplication.GetWorkflowModuleAsync(WorkflowModuleConsts.OrderHandle, HttpContext.RequestAborted);
            var definition = wfModule.Definition;
            var attitudeType = EnumExts.GetDescriptions<EAttitudeType>();
            if (_appOptions.Value.IsZiGong == false)
            {
                attitudeType = attitudeType.Where(m => new int[] { 2 }.Contains(m.Key) == false).ToList();
            }

            return new Dictionary<string, dynamic>
            {
                { "visitSatisfaction", _systemDicDataCacheManager.GetVisitSatisfaction() },
                { "orgsOptions", items },
                { "attitudeType", attitudeType},
                { "visitType",EnumExts.GetDescriptions<EVisitType>() },
                { "channelOptions",_sysDicDataCacheManager.GetSysDicDataCache(TimeLimitBaseDataConsts.SourceChannel) },
                { "acceptTypeOptions",_sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.AcceptType)},
                { "orderStatusOptions", EnumExts.GetDescriptions<EOrderStatus>()},
                { "currentStepOptions",definition?.Steps.Select(x => new Kv(x.Code, x.Name))},
                { "visitMananer", _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.VisitManner) },
                { "orderTags", _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.OrderTag) },
                { "dissatisfiedReason", _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.DissatisfiedReason)},
        };
        }

        /// <summary>
        /// 部门满意度明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("org-visitdetail-list-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrgVisitDetailListExport([FromBody] ExportExcelDto<OrgVisitDetailListReq> dto)
        {
            var query = _orderRepository.OrgVisitDetailList(dto.QueryDto);

            List<OrgVisitDetailListResp> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }
            //var ordersDtos = _mapper.Map<ICollection<OrgVisitDetailListResp>>(orders);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrgVisitDetailListResp>(dto.ColumnInfos);
            var dtos = orders
                .Select(stu => _mapper.Map(stu, typeof(OrgVisitDetailListResp), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "部门满意度明细");
        }

        /// <summary>
        /// 热点区域统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot-area-statistics")]
        public async Task<object> HotspotAndAreaStatistics([FromQuery] HotspotAndAreaStatisticsReq dto)
        {

            var (areaList, returnList) = await _orderApplication.HotspotAndAreaStatistics(dto);

            return new { AreaList = areaList, Data = returnList };
        }

        /// <summary>
        /// 热点区域统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotspot-area-statistics-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotAndAreaStatisticsExport([FromBody] HotspotAndAreaStatisticsReq dto)
        {
            var returnList = await _orderApplication.HotspotAndAreaStatisticsExport(dto);
            var table = _orderApplication.InitHotspotTable(returnList, dto.AddColumnName, dto.HotspotLevel);
            var stream = ExcelHelper.CreateStream(table);
            return ExcelStreamResult(stream, "热点区域统计");
        }

        /// <summary>
        /// 热点区域明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot-area-statistics-detail")]
        public async Task<PagedDto<HotspotAndAreaStatisticsDetailDto>> HotspotAndAreaStatisticsDetail([FromQuery] HotspotAndAreaStatisticsDetailReq dto)
        {
            var (total, items) = await _orderRepository.HotspotAndAreaStatisticsDetail(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<HotspotAndAreaStatisticsDetailDto>(total, items);
        }

        /// <summary>
        /// 受理类型明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("accepttype-statistics-bydate-detail")]
        public async Task<PagedDto<HotspotAndAreaStatisticsDetailDto>> AcceptTypeStatisticsByDateDetail([FromQuery] AcceptTypeStatisticsByDateDetailReq dto)
        {
            var (total, items) = await _orderRepository.AcceptTypeStatisticsByDateDetail(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<HotspotAndAreaStatisticsDetailDto>(total, items);
        }

        /// <summary>
        /// 受理类型明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("accepttype-statistics-bydate-detail-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> AcceptTypeStatisticsByDateDetailExport([FromBody] ExportExcelDto<AcceptTypeStatisticsByDateDetailReq> dto)
        {
            var query = _orderRepository.AcceptTypeStatisticsByDateDetail(dto.QueryDto);

            List<HotspotAndAreaStatisticsDetailDto> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }
            var ordersDtos = _mapper.Map<ICollection<HotspotAndAreaStatisticsDetailDto>>(orders);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<HotspotAndAreaStatisticsDetailDto>(dto.ColumnInfos);
            var dtos = ordersDtos
                .Select(stu => _mapper.Map(stu, typeof(HotspotAndAreaStatisticsDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "受理类型明细");
        }

        /// <summary>
        /// 热点区域明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotspot-area-statistics-detail-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotAndAreaStatisticsDetailExport([FromBody] ExportExcelDto<HotspotAndAreaStatisticsDetailReq> dto)
        {
            var query = _orderRepository.HotspotAndAreaStatisticsDetail(dto.QueryDto);

            List<HotspotAndAreaStatisticsDetailDto> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }
            var ordersDtos = _mapper.Map<ICollection<HotspotAndAreaStatisticsDetailDto>>(orders);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<HotspotAndAreaStatisticsDetailDto>(dto.ColumnInfos);
            var dtos = ordersDtos
                .Select(stu => _mapper.Map(stu, typeof(HotspotAndAreaStatisticsDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "热点区域明细");
        }

        /// <summary>
        /// 受理类型统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("accepttype-statistics")]
        public async Task<List<AcceptTypeStatisticsDto>> AcceptTypeStatistics([FromQuery] AcceptTypeStatisticsReq dto)
        {
            var list = await _orderReportApplication.AcceptTypeStatistics(dto).ToListAsync();
            int SumCount = list.Sum(x => x.SumCount);
            list.Add(new AcceptTypeStatisticsDto()
            {
                AcceptType = "合计",
                SumCount = SumCount,
                CompletionCount = list.Sum(x => x.CompletionCount),
                VisitCount = list.Sum(x => x.VisitCount)
            });

            list.ForEach(x =>
            {
                x.SumCountRate = SumCount > 0 ? Math.Round((double)x.SumCount / (double)SumCount * 100, digits: 3) + "%" : 0.000 + "%";
            });

            return list;
        }

        /// <summary>
        /// 受理类型统计-导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("accepttype-statistics-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> AcceptTypeStatisticsExport([FromBody] ExportExcelDto<AcceptTypeStatisticsReq> dto)
        {
            var list = await _orderReportApplication.AcceptTypeStatistics(dto.QueryDto).ToListAsync();
            int SumCount = list.Sum(x => x.SumCount);
            list.Add(new AcceptTypeStatisticsDto()
            {
                AcceptType = "合计",
                SumCount = SumCount,
                CompletionCount = list.Sum(x => x.CompletionCount),
                VisitCount = list.Sum(x => x.VisitCount)
            });

            list.ForEach(x =>
            {
                x.SumCountRate = SumCount > 0 ? Math.Round((double)x.SumCount / (double)SumCount * 100, digits: 3) + "%" : 0.000 + "%";
            });
            var orderDtos = _mapper.Map<ICollection<AcceptTypeStatisticsDto>>(list);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<AcceptTypeStatisticsDto>(dto.ColumnInfos);
            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(AcceptTypeStatisticsDto), dynamicClass))
                .Cast<object>()
                .ToList();
            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "受理类型统计表数据");
        }

        /// <summary>
        /// 根据时间查询受理类型统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("accepttype-statistics-bydate")]
        public async Task<object> AcceptTypeStatisticsByDate([FromQuery] AcceptTypeStatisticsByDateReq dto)
        {
            var (acceptList, items) = await _orderRepository.AcceptTypeStatisticsByDate(dto);

            return new { AcceptType = acceptList, Data = items };
        }

        /// <summary>
        /// 根据时间查询受理类型统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("accepttype-statistics-bydate-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> AcceptTypeStatisticsByDateExport([FromBody] AcceptTypeStatisticsByDateReq dto)
        {
            var returnList = await _orderRepository.AcceptTypeStatisticsByDateExport(dto);
            var table = _orderRepository.InitAcceptTypeTable(returnList, dto.AddColumnName);
            var stream = ExcelHelper.CreateStream(table);
            return ExcelStreamResult(stream, "受理类型时间统计");
        }

        /// <summary>
        /// 下级区域统计
        /// </summary>
        /// <param name="StartTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <param name="TypeId">0：全部 ，1：市民，2：企业</param>
        /// <param name="AreaCode">上级区域Id</param>
        /// <param name="Line">线路号</param>
        /// <returns></returns>
        [HttpGet("area_subordinate")]
        public async Task<object> AreaSubordinate(DateTime StartTime, DateTime EndTime, int? TypeId, string? AreaCode, string? Line)
        {
            string count = "6";
            if (!string.IsNullOrEmpty(AreaCode) && AreaCode != "511500")
                count = (AreaCode.Length + 2).ToString();

            if (string.IsNullOrEmpty(AreaCode))
                AreaCode = "510000";

            if (AreaCode == "510000")
            {
                var query = _orderRepository.Queryable()
                      .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                        .WhereIF(TypeId != null && TypeId == 1, p => p.IdentityType == EIdentityType.Citizen)
                      .WhereIF(TypeId != null && TypeId == 2, p => p.IdentityType == EIdentityType.Enterprise)
                      .WhereIF(!string.IsNullOrEmpty(Line), p => p.TransferPhone == Line)
                      .Select(p => new
                      {
                          AreaCode = p.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)),

                      })
                      .MergeTable()
                      .Select(p => new
                      {
                          AreaCode = SqlFunc.IIF(p.AreaCode != "519800" && p.AreaCode != "519900", "511500", p.AreaCode)
                      }
                    ).MergeTable()
                    .GroupBy(p => p.AreaCode)
                    .Select(p => new
                    {
                        AreaCode = p.AreaCode,
                        SumCount = SqlFunc.AggregateCount(p.AreaCode)
                    }
                    ).MergeTable();

                var list = await _systemAreaRepository.Queryable()
                      .LeftJoin(query, (s, o) => s.Id == o.AreaCode)
                      .Where((s, o) => s.ParentId == AreaCode)
                      .Select((s, o) => new
                      {
                          AreaCode = s.Id,
                          SumCount = o.SumCount,
                          AreaName = s.AreaName,
                          HasChild = SqlFunc.Subqueryable<SystemArea>().Where(d => d.ParentId == o.AreaCode).Any()
                      })
                    .ToListAsync();

                return list;
            }
            else
            {
                var query = _orderRepository.Queryable()
                 .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime)
                   .WhereIF(TypeId != null && TypeId == 1, p => p.IdentityType == EIdentityType.Citizen)
                 .WhereIF(TypeId != null && TypeId == 2, p => p.IdentityType == EIdentityType.Enterprise)
                 .WhereIF(!string.IsNullOrEmpty(Line), p => p.TransferPhone == Line)
                  .GroupBy(p => new { Id = p.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)) })
                 .Select(p => new
                 {
                     AreaCode = p.AreaCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>(count)),
                     SumCount = SqlFunc.AggregateCount(p.AreaCode)
                 })
                 .MergeTable();

                var list = await _systemAreaRepository.Queryable()
                      .LeftJoin(query, (s, o) => s.Id == o.AreaCode)
                      .Where((s, o) => s.ParentId == AreaCode)
                      .Select((s, o) => new
                      {
                          AreaCode = s.Id,
                          SumCount = o.SumCount,
                          AreaName = s.AreaName,
                          HasChild = SqlFunc.Subqueryable<SystemArea>().Where(d => d.ParentId == o.AreaCode).Any()
                      })
                    .ToListAsync();
                return list;
            }
        }

        /// <summary>
        /// 下级区域统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("area_subordinate/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> AreaSubordinateExport([FromBody] ExportExcelDto<AreaSubordinateRequest> dto)
        {
            var StartTime = dto.QueryDto.StartTime;
            var EndTime = dto.QueryDto.EndTime;
            var TypeId = dto.QueryDto.TypeId;
            var Line = dto.QueryDto.Line;
            DataTable data = new DataTable();

            var list = await _systemAreaRepository.Queryable()
                .LeftJoin<Order>((s, o) => o.AreaCode.StartsWith(s.Id))
                .Where((s, o) => o.CreationTime >= StartTime && o.CreationTime <= EndTime)
                .WhereIF(TypeId != null && TypeId == 1, (s, o) => o.IdentityType == EIdentityType.Citizen)
                .WhereIF(TypeId != null && TypeId == 2, (s, o) => o.IdentityType == EIdentityType.Enterprise)
                .WhereIF(!string.IsNullOrEmpty(Line), (s, o) => o.TransferPhone == Line)
                .GroupBy((s, o) => s.Id)
                .OrderBy((s, o) => new { s.Id }, OrderByType.Asc)
                .Select((s, o) => new AreaSubordinateReportRes
                {
                    AreaName = s.AreaName,
                    SumCount = SqlFunc.AggregateSum(SqlFunc.IIF(o.AreaCode.StartsWith(s.Id), 1, 0))
                })
                .ToListAsync();
            data = list.ToDataTable("areasubordinate");
            //合计
            DataRow sumRow = data.NewRow();
            sumRow["AreaName"] = "合计";
            decimal totalAmount = 0;
            foreach (DataRow row in data.Rows)
            {
                totalAmount += Convert.ToDecimal(row["SumCount"]);
            }
            sumRow["SumCount"] = totalAmount;
            data.Rows.Add(sumRow);
            data.Columns["AreaName"].ColumnName = "区域名称";
            data.Columns["SumCount"].ColumnName = "分类统计";

            var stream = ExcelHelper.CreateStream(data);
            return ExcelStreamResult(stream, "下级区域统计");
        }

        /// <summary>
        /// 热点满意度统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-hotspot-satisfaction-statistics")]
        public async Task<Object> VisitAndHotspotSatisfactionStatistics([FromQuery] VisitAndHotspotPagedKeywordRequest dto)
        {
            var data = await _orderApplication.VisitAndHotspotSatisfactionStatistics(dto);
            var sumModel = new VisitAndHotspotSatisfactionStatisticsDto()
            {
                HotspotName = "总计",
                TotalSumCount = data.Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Sum(x => x.NoPutThroughCount),
            };

            return new { DataList = data, SumModel = sumModel };
        }

        /// <summary>
        /// 热点满意度统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-hotspot-satisfaction-statistics/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> VisitAndHotspotSatisfactionStatisticsExport([FromBody] ExportExcelDto<VisitAndHotspotPagedKeywordRequest> dto)
        {
            List<VisitAndHotspotSatisfactionStatisticsDto> data = await _orderApplication.VisitAndHotspotSatisfactionStatistics(dto.QueryDto);
            var sumModel = new VisitAndHotspotSatisfactionStatisticsDto()
            {
                HotspotName = "总计",
                TotalSumCount = data.Sum(x => x.TotalSumCount),
                VerySatisfiedCount = data.Sum(x => x.VerySatisfiedCount),
                SatisfiedCount = data.Sum(x => x.SatisfiedCount),
                RegardedAsSatisfiedCount = data.Sum(x => x.RegardedAsSatisfiedCount),
                DefaultSatisfiedCount = data.Sum(x => x.DefaultSatisfiedCount),
                NoSatisfiedCount = data.Sum(x => x.NoSatisfiedCount),
                NoEvaluateCount = data.Sum(x => x.NoEvaluateCount),
                NoPutThroughCount = data.Sum(x => x.NoPutThroughCount),
            };
            data.Add(sumModel);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<VisitAndHotspotSatisfactionStatisticsDto>(dto.ColumnInfos);
            var dtos = data
             .Select(stu => _mapper.Map(stu, typeof(VisitAndHotspotSatisfactionStatisticsDto), dynamicClass))
             .Cast<object>()
             .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "热点满意度统计数据");
        }

        /// <summary>
        /// 热点满意度明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("visit-hotspot-satisfaction-detail")]
        public async Task<PagedDto<OrderVisitDetailDto>> VisitAndHotspotSatisfactionDetail([FromQuery] VisitAndHotspotPagedKeywordRequest dto)
        {
            var (total, items) = await _orderApplication.VisitAndHotspotSatisfactionDetail(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderVisitDetailDto>(total, _mapper.Map<IReadOnlyList<OrderVisitDetailDto>>(items));
        }

        /// <summary>
        /// 热点满意度明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("visit-hotspot-satisfaction-detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> VisitAndHotspotSatisfactionDetailExport([FromBody] ExportExcelDto<VisitAndHotspotPagedKeywordRequest> dto)
        {
            var query = _orderApplication.VisitAndHotspotSatisfactionDetail(dto.QueryDto);
            List<OrderVisitDetail> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<OrderVisitDetailDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVisitDetailDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderVisitDetailDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "热点满意度明细数据");
        }

        /// <summary>
        /// 热点受理类型统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot-accepttype-statistics")]
        public async Task<object> HotspotAndAcceptTypeStatistics([FromQuery] HotspotAndAcceptTypeStatisticsReq dto)
        {

            var (areaList, returnList) = await _orderApplication.HotspotAndAcceptTypeStatistics(dto);

            return new { AreaList = areaList, Data = returnList };
        }

        /// <summary>
        /// 热点受理类型统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotspot-accepttype-statistics-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotAndAcceptTypeStatisticsExport([FromBody] HotspotAndAcceptTypeStatisticsReq dto)
        {
            var returnList = await _orderApplication.HotspotAndAcceptTypeStatisticsExport(dto);
            var table = _orderApplication.InitHotspotTable(returnList, dto.AddColumnName, dto.HotspotLevel);
            var stream = ExcelHelper.CreateStream(table);
            return ExcelStreamResult(stream, "热点受理类型统计");
        }

        /// <summary>
        /// 热点受理类型明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("hotspot-accepttype-statistics-detail")]
        public async Task<PagedDto<OrderDto>> HotspotAndAcceptTypeStatisticsDetail([FromQuery] HotspotAndAcceptTypeStatisticsDetailReq dto)
        {
            var (total, items) = await _orderApplication.HotspotAndAcceptTypeStatisticsDetail(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 热点受理类型明细导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("hotspot-accepttype-statistics-detail-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> HotspotAndAcceptTypeStatisticsDetailExport([FromBody] ExportExcelDto<HotspotAndAcceptTypeStatisticsDetailReq> dto)
        {
            var query = _orderApplication.HotspotAndAcceptTypeStatisticsDetail(dto.QueryDto);

            List<Order> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }
            var ordersDtos = _mapper.Map<ICollection<OrderDto>>(orders);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);
            var dtos = ordersDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "热点受理类型明细");
        }

        /// <summary>
        /// 甄别申请统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("screen-apply")]
        public async Task<PagedDto<OrderScreenApplyVo>> OrderScreenApply([FromQuery] OrderScreenApplyPagedRequest dto)
        {
            var (total, items) = await _orderApplication.OrderScreenApply(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderScreenApplyVo>(total, items);
        }

        /// <summary>
        /// 甄别申请统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("screen-apply-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderScreenApplyExport([FromBody] ExportExcelDto<OrderScreenApplyPagedRequest> dto)
        {
            var query = _orderApplication.OrderScreenApply(dto.QueryDto);

            List<OrderScreenApplyVo> datas;
            if (dto.IsExportAll)
            {
                datas = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                datas = items;
            }
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderScreenApplyVo>(dto.ColumnInfos);
            var dtos = datas
                .Select(stu => _mapper.Map(stu, typeof(OrderScreenApplyVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "甄别申请统计");
        }

        /// <summary>
        /// 甄别审批统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("screen-audit")]
        public async Task<PagedDto<OrderScreenAuditVo>> OrderScreenAudit([FromQuery] OrderScreenAuditPagedRequest dto)
        {
            var (total, items) = await _orderApplication.OrderScreenAudit(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderScreenAuditVo>(total, items);
        }

        /// <summary>
        /// 甄别审批统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("screen-audit-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderScreenAuditExport([FromBody] ExportExcelDto<OrderScreenAuditPagedRequest> dto)
        {
            var query = _orderApplication.OrderScreenAudit(dto.QueryDto);

            List<OrderScreenAuditVo> datas;
            if (dto.IsExportAll)
            {
                datas = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                datas = items;
            }
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderScreenAuditVo>(dto.ColumnInfos);
            var dtos = datas
                .Select(stu => _mapper.Map(stu, typeof(OrderScreenAuditVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "甄别审批统计");
        }

        /// <summary>
        /// 未签收统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get_order_nosigen")]
        public async Task<object> GetOrderNoSigen([FromQuery] OrderNoSigenRequestDto dto)
        {
            var items = await _orderReportApplication.GetOrderNoSigen(dto);

            var total = new OrderNoSigenDto
            {
                OrgName = "合计",
                OrgCode = "",
                OrderNoSigen = items.Sum(p => p.OrderNoSigen),
                CounterNoSign = items.Sum(p => p.CounterNoSign)
            };

            return new { List = items, Total = total };
        }

        /// <summary>
        /// 未签收统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("get_order_nosigen_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportGetOrderNoSigen([FromBody] ExportExcelDto<OrderNoSigenRequestDto> dto)
        {
            var list = await _orderReportApplication.GetOrderNoSigen(dto.QueryDto);

            //增加合计
            list.Add(new OrderNoSigenDto
            {
                OrgName = "合计",
                OrgCode = "",
                OrderNoSigen = list.Sum(p => p.OrderNoSigen),
                CounterNoSign = list.Sum(p => p.CounterNoSign)
            });

            var orderDtos = _mapper.Map<ICollection<OrderNoSigenDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderNoSigenDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderNoSigenDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "未签收统计数据");
        }

        /// <summary>
        /// 未签收统计--明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get_order_nosigen_detail")]
        public async Task<PagedDto<OrderDto>> GetOrderNoSigenDetail([FromQuery] OrderNoSigenRequestDto dto)
        {
            RefAsync<int> total = 0;

            var queryData = await _orderReportApplication.GetOrderNoSigenDetail(dto)
                         .Select(o => new { o })
                        .ToPageListAsync(dto.PageIndex, dto.PageSize, total, HttpContext.RequestAborted);

            var dtos = queryData.Select(d =>
            {
                var dto = _mapper.Map<OrderDto>(d.o);
                return dto;
            }).ToList();
            return new PagedDto<OrderDto>(total, dtos);
        }

        /// <summary>
        /// 未签收统计--明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("get_order_nosigen_detail_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportGetOrderNoSigenDetail([FromBody] ExportExcelDto<OrderNoSigenRequestDto> dto)
        {
            var query = _orderReportApplication.GetOrderNoSigenDetail(dto.QueryDto).Select(o => new { o });

            List<OrderDto> list = new();
            if (dto.IsExportAll)
            {
                var listData = await query.ToListAsync(HttpContext.RequestAborted);
                list = listData.Select(d =>
                {
                    var dto = _mapper.Map<OrderDto>(d.o);
                    return dto;
                }).ToList();
            }
            else
            {
                RefAsync<int> total = 0;
                var listData = await query.ToPageListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, total, HttpContext.RequestAborted);
                list = listData.Select(d =>
                {
                    var dto = _mapper.Map<OrderDto>(d.o);
                    return dto;
                }).ToList();
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "未签收统计明细数据");
        }

        /// <summary>
        /// 企业专席信件统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get_enterprise_seats_report")]
        public async Task<object> GetEnterpriseSeatsReport([FromQuery] EnterpriseSeatsReportRequestDto dto)
        {
            var items = await _orderReportApplication.GetEnterpriseSeatsReport(dto);

            var total = new EnterpriseSeatsReportDto
            {
                UserName = "合计",
                UserId = "",
                UserNo = "",
                TelCallNum = items.Sum(p => p.TelCallNum),
                OrderNum = items.Sum(p => p.OrderNum),
            };

            return new { List = items, Total = total };
        }

        /// <summary>
        /// 企业专席信件统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("get_enterprise_seats_report_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportGetEnterpriseSeatsReport([FromBody] ExportExcelDto<EnterpriseSeatsReportRequestDto> dto)
        {
            var list = await _orderReportApplication.GetEnterpriseSeatsReport(dto.QueryDto);

            //增加合计
            list.Add(new EnterpriseSeatsReportDto
            {
                UserName = "合计",
                UserId = "",
                UserNo = "",
                TelCallNum = list.Sum(p => p.TelCallNum),
                OrderNum = list.Sum(p => p.OrderNum),
            });

            var orderDtos = _mapper.Map<ICollection<EnterpriseSeatsReportDto>>(list);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<EnterpriseSeatsReportDto>(dto.ColumnInfos);

            var dtos = orderDtos
                .Select(stu => _mapper.Map(stu, typeof(EnterpriseSeatsReportDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "企业专席信件统计");
        }

        /// <summary>
        /// 企业专席信件统计--明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get_enterprise_seats_report_detail")]
        public async Task<PagedDto<OrderDto>> GetEnterpriseSeatsReportDetail([FromQuery] EnterpriseSeatsReportRequestDto dto)
        {
            RefAsync<int> total = 0;
            var queryData = await _orderReportApplication.GetEnterpriseSeatsReportDetail(dto)
                        .ToPageListAsync(dto.PageIndex, dto.PageSize, total, HttpContext.RequestAborted);

            return new PagedDto<OrderDto>(total, _mapper.Map<List<OrderDto>>(queryData));
        }

        /// <summary>
        /// 企业专席信件统计--明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("get_enterprise_seats_report_detail_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportGetEnterpriseSeatsReportDetail([FromBody] ExportExcelDto<EnterpriseSeatsReportRequestDto> dto)
        {
            var query = _orderReportApplication.GetEnterpriseSeatsReportDetail(dto.QueryDto);

            List<OrderDto> list = new();
            if (dto.IsExportAll)
            {
                var listData = await query.ToListAsync(HttpContext.RequestAborted);
                list = _mapper.Map<List<OrderDto>>(listData);
            }
            else
            {
                RefAsync<int> total = 0;
                var listData = await query.ToPageListAsync(dto.QueryDto.PageIndex, dto.QueryDto.PageSize, total, HttpContext.RequestAborted);
                list = _mapper.Map<List<OrderDto>>(listData);
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "企业专席信件统计");
        }

        /// <summary>
        /// 中心受理统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("center-accept")]
        public async Task<List<OrderCenterAcceptVo>> OrderCenterAccept([FromQuery] OrderCenterAcceptPagedRequest dto)
        {
            var items = await _orderApplication.OrderCenterAccept(dto).ToListAsync(HttpContext.RequestAborted);
            items.Add(new OrderCenterAcceptVo
            {
                Time = "合计",
                AcceptNum = items.Sum(p => p.AcceptNum),
                ValidNum = items.Sum(p => p.ValidNum),
                RepetitionNum = items.Sum(p => p.RepetitionNum),
                InvalidNum = items.Sum(p => p.InvalidNum),
                HandleNum = items.Sum(p => p.HandleNum),
                NoHandleNum = items.Sum(p => p.NoHandleNum),
                BackNum = items.Sum(p => p.BackNum),
                DutyDeskNum = items.Sum(p => p.DutyDeskNum),
            });
            return items;
        }

        /// <summary>
        /// 中心受理统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("center-accept-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderCenterAcceptExport([FromBody] ExportExcelDto<OrderCenterAcceptPagedRequest> dto)
        {
            var query = _orderApplication.OrderCenterAccept(dto.QueryDto);

            List<OrderCenterAcceptVo> datas;
            if (dto.IsExportAll)
            {
                datas = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                datas = items;
            }
            datas.Add(new OrderCenterAcceptVo
            {
                Time = "合计",
                AcceptNum = datas.Sum(p => p.AcceptNum),
                ValidNum = datas.Sum(p => p.ValidNum),
                RepetitionNum = datas.Sum(p => p.RepetitionNum),
                InvalidNum = datas.Sum(p => p.InvalidNum),
                HandleNum = datas.Sum(p => p.HandleNum),
                NoHandleNum = datas.Sum(p => p.NoHandleNum),
                BackNum = datas.Sum(p => p.BackNum),
                DutyDeskNum = datas.Sum(p => p.DutyDeskNum),
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderCenterAcceptVo>(dto.ColumnInfos);
            var dtos = datas
                .Select(stu => _mapper.Map(stu, typeof(OrderCenterAcceptVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "中心受理统计");
        }

        /// <summary>
        /// 中心受理值班坐席统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("center-accept-user")]
        public async Task<PagedDto<OrderCenterAcceptUserVo>> OrderCenterAcceptUser([FromQuery] OrderCenterAcceptPagedRequest dto)
        {
            var (total, items) = await _orderApplication.OrderCenterAcceptUser(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderCenterAcceptUserVo>(total, items);
        }

        /// <summary>
        /// 中心受理值班坐席统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("center-accept-user-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderCenterAcceptUserExport([FromBody] ExportExcelDto<OrderCenterAcceptPagedRequest> dto)
        {
            var query = _orderApplication.OrderCenterAcceptUser(dto.QueryDto);

            List<OrderCenterAcceptUserVo> datas;
            if (dto.IsExportAll)
            {
                datas = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                datas = items;
            }
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderCenterAcceptUserVo>(dto.ColumnInfos);
            var dtos = datas
                .Select(stu => _mapper.Map(stu, typeof(OrderCenterAcceptUserVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "中心受理值班坐席统计");
        }

        /// <summary>
        /// 中心受理时间段统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("center-accept-hour")]
        public async Task<List<OrderCenterAcceptHourVo>> OrderCenterAcceptHour([FromQuery] OrderCenterAcceptPagedRequest dto)
        {
            var items = await _orderRepository.OrderCenterAcceptHour(dto).ToListAsync(HttpContext.RequestAborted);
            return items;
        }

        /// <summary>
        /// 中心受理时间段统计导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("center-accept-hour-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderCenterAcceptHourExport([FromBody] ExportExcelDto<OrderCenterAcceptPagedRequest> dto)
        {
            var query = _orderRepository.OrderCenterAcceptHour(dto.QueryDto);

            List<OrderCenterAcceptHourVo> datas;
            if (dto.IsExportAll)
            {
                datas = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                datas = items;
            }
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderCenterAcceptHourVo>(dto.ColumnInfos);
            var dtos = datas
                .Select(stu => _mapper.Map(stu, typeof(OrderCenterAcceptHourVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "中心受理时间段统计");
        }

        /// <summary>
        /// 数据清单基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("order-data-inventory-basedata")]
        public async Task<object> OrderDataInventoryBaseData()
        {
            var wfModule = await _workflowApplication.GetWorkflowModuleAsync(WorkflowModuleConsts.OrderHandle, HttpContext.RequestAborted);
            var definition = wfModule.Definition;
            return new
            {
                OrderStatusOptions = EnumExts.GetDescriptions<EOrderStatus>(),
                ChannelOptions = _sysDicDataCacheManager.GetSysDicDataCache(TimeLimitBaseDataConsts.SourceChannel),
                ScreenStatusOptions = EnumExts.GetDescriptions<EScreenStatus>(),
                AcceptTypeOptions = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.AcceptType),
                IdentityTypeOptions = EnumExts.GetDescriptions<EIdentityType>(),
                FromGenderOptions = EnumExts.GetDescriptions<EGender>(),
                ExpiredStatusOptions = EnumExts.GetDescriptions<EExpiredStatusEx>(),
                PushTypeOptions = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.PushType),
                CurrentStepOptions = definition?.Steps.Select(x => new Kv(x.Code, x.Name)),
                OrgsOptions = await _organizeRepository.GetOrgJson(),
                GenderOptions = EnumExts.GetDescriptions<EGender>(),
            };
        }

        /// <summary>
        /// 数据清单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("order-data-inventory")]
        public async Task<PagedDto<OrderDataInventoryRep>> OrderDataInventory([FromQuery] OrderDataInventoryReq dto)
        {
            var (total, items) = await _orderRepository.OrderDataInventory(dto).ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderDataInventoryRep>() { Total = total, Items = items };
        }

        /// <summary>
        /// 数据清单导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("order-data-inventory-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderDataInventoryExport([FromBody] ExportExcelDto<OrderDataInventoryReq> dto)
        {
            var query = _orderRepository.OrderDataInventory(dto.QueryDto);

            List<OrderDataInventoryRep> orders;
            if (dto.IsExportAll)
            {
                orders = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                orders = items;
            }
            var ordersDtos = _mapper.Map<ICollection<OrderDataInventoryRep>>(orders);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDataInventoryRep>(dto.ColumnInfos);
            var dtos = ordersDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderDataInventoryRep), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "数据清单明细");

        }

        #region 智能回访统计

        /// <summary>
        /// 智能回访数据统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("aivisit-statistics")]
        public async Task<QueryAiVisitStatisticsResp> QueryAiVisitStatistics([FromQuery] QueryAiVisitStatisticsRequest dto)
        {
            var model = await _orderRepository.QueryAiVisitStatistics(dto);
            return model;
        }

        /// <summary>
        /// 智能回访有效性分析
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("aivisit-effective-analysis")]
        public async Task<QueryAiVisitEffectiveAnalysisResp> QueryAiVisitEffectiveAnalysis([FromQuery] QueryAiVisitStatisticsRequest dto)
        {
            var model = await _orderRepository.QueryAiVisitEffectiveAnalysis(dto);
            return model;
        }
        #endregion

        /// <summary>
        /// 扭转信件统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("ordervisit-jude-statistics")]
        public async Task<List<OrderVisitJudeStatisticsRep>> OrderVisitJudeStatistics([FromQuery] OrderVisitJudeStatisticsReq dto)
        {
            var list = await _orderApplication.OrderVisitJudeStatistics(dto).ToListAsync();
            return list;
        }

        /// <summary>
        /// 扭转信件统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("ordervisit-jude-statistics-export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrderVisitJudeStatisticsExport([FromBody] ExportExcelDto<OrderVisitJudeStatisticsReq> dto)
        {
            var query = _orderApplication.OrderVisitJudeStatistics(dto.QueryDto);
            List<OrderVisitJudeStatisticsRep> exportList;
            exportList = await query.ToListAsync(HttpContext.RequestAborted);
            var ordersDtos = _mapper.Map<ICollection<OrderVisitJudeStatisticsRep>>(exportList);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderVisitJudeStatisticsRep>(dto.ColumnInfos);
            var dtos = ordersDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderVisitJudeStatisticsRep), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "扭转信件统计");
        }

        /// <summary>
        /// 工单热词分析
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("query_order_ts_details_list")]
        public async Task<PagedDto<OrderTsDetailsDto>> QueryOrderTsDetailsList([FromQuery] PagedKeywordRequest dto)
        {
            var (total, items) = await _orderApplication.QueryOrderTsDetailsList(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderTsDetailsDto>(total, _mapper.Map<IReadOnlyList<OrderTsDetailsDto>>(items));
        }

        /// <summary>
        /// 工单热词分析导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("query_order_ts_details_list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryOrderTsDetailsList([FromBody] ExportExcelDto<PagedKeywordRequest> dto)
        {
            var query = _orderApplication.QueryOrderTsDetailsList(dto.QueryDto);

            List<OrderTsDetailsDto> lists;
            if (dto.IsExportAll)
            {
                lists = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                lists = items;
            }

            var listDtos = _mapper.Map<ICollection<OrderTsDetailsDto>>(lists);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderTsDetailsDto>(dto.ColumnInfos);

            var dtos = listDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderTsDetailsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "工单热词分析数据");

        }

        /// <summary>
        /// 根据热词查询工单
        /// </summary>
        /// <param name="KeyWord"></param>
        /// <returns></returns>
        [HttpGet("get_query_order_ts_details_order_list")]
        public async Task<List<OrderTsDetails>> GetQueryOrderTsDetailslOrderList(string KeyWord)
        {
            return await _orderTsDetailsRepository.Queryable()
                .LeftJoin<Order>((ot, o) => ot.OrderId == o.Id)
                   .Where((ot, o) => ot.Terms == KeyWord)
                   .Select((ot, o) => new OrderTsDetails
                   {
                       Id = ot.Id,
                       Terms = ot.Terms,
                       OrderId = o.Id,
                       Title = o.Title,
                       No = ot.No
                   })
                   .ToListAsync(HttpContext.RequestAborted);
        }

        /// <summary>
        /// 知识库引用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("query_knowledge_quote_list")]
        public async Task<PagedDto<OrderTsDetailsDto>> QueryKnowledgeQuoteList([FromQuery] PagedKeywordRequest dto)
        {
            var (total, items) = await _orderApplication.QueryKnowledgeQuoteList(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);

            return new PagedDto<OrderTsDetailsDto>(total, _mapper.Map<IReadOnlyList<OrderTsDetailsDto>>(items));
        }

        /// <summary>
        /// 知识库引用导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("query_knowledge_quote_list/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExportQueryKnowledgeQuoteList([FromBody] ExportExcelDto<PagedKeywordRequest> dto)
        {
            var query = _orderApplication.QueryKnowledgeQuoteList(dto.QueryDto);

            List<OrderTsDetailsDto> lists;
            if (dto.IsExportAll)
            {
                lists = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                lists = items;
            }

            var listDtos = _mapper.Map<ICollection<OrderTsDetailsDto>>(lists);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderTsDetailsDto>(dto.ColumnInfos);

            var dtos = listDtos
                .Select(stu => _mapper.Map(stu, typeof(OrderTsDetailsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "知识库引用数据");

        }

        /// <summary>
        /// 根据知识库引用查询工单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get_query_knowledge_quote_order_list")]
        public async Task<List<KnowledgeQuote>> GetQueryKnowledgeQuoteOrderList([FromQuery] PagedKeywordRequest dto)
        {
            return await _knowledgeQuoteRepository.Queryable()
                   .LeftJoin<Order>((kn, o) => kn.OrderId == o.Id)
                   .Where((kn, o) => kn.KnowledgeId == dto.Keyword && kn.CreationTime >= dto.StartTime && kn.CreationTime <= dto.EndTime)
                   .Select((kn, o) => new KnowledgeQuote
                   {
                       KnowledgeId = kn.Id,
                       KnowledgeTitle = o.Title,
                       OrderId = o.Id,
                       Title = o.Title,
                       No = o.No,
                   })
                   .ToListAsync(HttpContext.RequestAborted);
        }

        /// <summary>
        /// 超期退回统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("extended_sendback_statistics")]
        public async Task<List<ExtendedSendBackVo>> ExtendedSendBackStatistics([FromQuery] PagedKeywordRequest dto)
        {
            var quer = _orderApplication.ExtendedSendBackStatistics(dto);
            var list = await quer.ToListAsync(HttpContext.RequestAborted);
            list.Add(new ExtendedSendBackVo()
            {
                OrgName = "合计",
                TotalNum = list.Sum(m => m.TotalNum),
                PassNum = list.Sum(p => p.PassNum),
                NoPassNum = list.Sum(m => m.NoPassNum),
                AuditNum = list.Sum(m => m.AuditNum)
            });

            return list;
        }

        /// <summary>
        /// 超期退回统计导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("extended_sendback_statistics/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExtendedSendBackStatisticsExport([FromBody] ExportExcelDto<PagedKeywordRequest> dto)
        {
            var query = _orderApplication.ExtendedSendBackStatistics(dto.QueryDto);
            List<ExtendedSendBackVo> data;

            data = await query.ToListAsync(HttpContext.RequestAborted);

            data.Add(new ExtendedSendBackVo()
            {
                OrgName = "合计",
                TotalNum = data.Sum(m => m.TotalNum),
                PassNum = data.Sum(p => p.PassNum),
                NoPassNum = data.Sum(m => m.NoPassNum),
                AuditNum = data.Sum(m => m.AuditNum)
            });

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<ExtendedSendBackVo>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(ExtendedSendBackVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "超期退回统计");
        }

        /// <summary>
        /// 超期退回统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("extended_sendback_detail")]
        public async Task<PagedDto<SendBackDto>> ExtendedSendBackDetail([FromQuery] ExtendedSendBackRequest dto)
        {
            var quer = _orderApplication.ExtendedSendBackDetail(dto);
            var (total, items) = await quer.ToPagedListAsync(dto.PageIndex, dto.PageSize);

            return new PagedDto<SendBackDto>(total, _mapper.Map<IReadOnlyList<SendBackDto>>(items));
        }

        /// <summary>
        /// 超期退回统计明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("extended_sendback_detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> ExtendedSendBackDetailExport([FromBody] ExportExcelDto<ExtendedSendBackRequest> dto)
        {
            var query = _orderApplication.ExtendedSendBackDetail(dto.QueryDto);
            List<OrderSendBackAudit> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<SendBackDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SendBackDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(SendBackDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "超期退回统计明细");
        }

        /// <summary>
        /// 列表页面基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("extended_sendback_detail/base-data")]
        public async Task<object> ExtendedSendBackDetailBaseData()
        {
            var rsp = new
            {
                AcceptTypeOptions = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.AcceptType),
                ChannelOptions = _sysDicDataCacheManager.GetSysDicDataCache(TimeLimitBaseDataConsts.SourceChannel),
                SendBackAuditState = EnumExts.GetDescriptions<ESendBackAuditState>()
            };
            return rsp;
        }

        /// <summary>
        /// 网上群众路线通报
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("onlinemassline-report")]
        public async Task<List<OnlineMassLineReportRes>> OnlineMassLineReport([FromQuery] OnlineMassLineReportRequest dto)
        {
            var nowList = await _orderRepository.Queryable()
                .Where(x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime).ToListAsync();


            var oldList = await _orderRepository.Queryable()
                .Where(x => x.CreationTime >= dto.ChainStartTime && x.CreationTime <= dto.ChainEndTime).ToListAsync();


            var returnList = new List<OnlineMassLineReportRes>();
            //市12345政务服务便民热线
            var Other = new OnlineMassLineReportRes();
            Other.SourceChannel = "市12345政务服务便民热线";
            Other.SumCount = nowList.Where(x => x.IsProvince == false && x.SourceChannelCode != "SZYSM").Count(); //市12345政务服务便民热线
            Other.PreviousCount = oldList.Where(x => x.IsProvince == false && x.SourceChannelCode != "SZYSM").Count(); //市12345政务服务便民热线
            returnList.Add(Other);
            //中国政府网“我向总理说句话”
            var ZGZFW = new OnlineMassLineReportRes();
            ZGZFW.SourceChannel = "中国政府网“我向总理说句话”";
            ZGZFW.SumCount = nowList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("ZGZFW")).Count(); //中国政府网“我向总理说句话”
            ZGZFW.PreviousCount = oldList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("ZGZFW")).Count(); //中国政府网“我向总理说句话”
            returnList.Add(ZGZFW);
            //国家政务服务平台“投诉与建议”
            var GJZWFWPT = new OnlineMassLineReportRes();
            GJZWFWPT.SourceChannel = "国家政务服务平台“投诉与建议”";
            GJZWFWPT.SumCount = nowList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT")).Count(); //国家政务服务平台“投诉与建议”
            GJZWFWPT.PreviousCount = oldList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT")).Count(); //国家政务服务平台“投诉与建议”
            returnList.Add(GJZWFWPT);
            //省12345政务服务便民热线
            var Province12345 = new OnlineMassLineReportRes();
            Province12345.SourceChannel = "省12345政务服务便民热线";
            Province12345.SumCount = nowList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT") == false && x.ReceiveProvinceNo.StartsWith("ZGZFW") == false).Count(); //国家政务服务平台“投诉与建议”
            Province12345.PreviousCount = oldList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT") == false && x.ReceiveProvinceNo.StartsWith("ZGZFW") == false).Count(); //国家政务服务平台“投诉与建议”
            returnList.Add(Province12345);
            //市政府网站“市长与网民”
            var SZYSM = new OnlineMassLineReportRes();
            SZYSM.SourceChannel = "市政府网站“市长与网民”";
            SZYSM.SumCount = nowList.Where(x => x.SourceChannelCode == "SZYSM").Count(); //国家政务服务平台“投诉与建议”
            SZYSM.PreviousCount = oldList.Where(x => x.SourceChannelCode == "SZYSM").Count(); //国家政务服务平台“投诉与建议”
            returnList.Add(SZYSM);
            return returnList;
        }

        /// <summary>
        /// 网上群众路线通报导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("onlinemassline-report/export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OnlineMassLineReportExport([FromBody] ExportExcelDto<OnlineMassLineReportRequest> dto)
        {
            var nowList = await _orderRepository.Queryable()
                .Where(x => x.CreationTime >= dto.QueryDto.StartTime && x.CreationTime <= dto.QueryDto.EndTime).ToListAsync();


            var oldList = await _orderRepository.Queryable()
                .Where(x => x.CreationTime >= dto.QueryDto.ChainStartTime && x.CreationTime <= dto.QueryDto.ChainEndTime).ToListAsync();


            var returnList = new List<OnlineMassLineReportRes>();
            //市12345政务服务便民热线
            var Other = new OnlineMassLineReportRes();
            Other.SourceChannel = "市12345政务服务便民热线";
            Other.SumCount = nowList.Where(x => x.IsProvince == false && x.SourceChannelCode != "SZYSM").Count(); //市12345政务服务便民热线
            Other.PreviousCount = oldList.Where(x => x.IsProvince == false && x.SourceChannelCode != "SZYSM").Count(); //市12345政务服务便民热线
            returnList.Add(Other);
            //中国政府网“我向总理说句话”
            var ZGZFW = new OnlineMassLineReportRes();
            ZGZFW.SourceChannel = "中国政府网“我向总理说句话”";
            ZGZFW.SumCount = nowList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("ZGZFW")).Count(); //中国政府网“我向总理说句话”
            ZGZFW.PreviousCount = oldList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("ZGZFW")).Count(); //中国政府网“我向总理说句话”
            returnList.Add(ZGZFW);
            //国家政务服务平台“投诉与建议”
            var GJZWFWPT = new OnlineMassLineReportRes();
            GJZWFWPT.SourceChannel = "国家政务服务平台“投诉与建议”";
            GJZWFWPT.SumCount = nowList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT")).Count(); //国家政务服务平台“投诉与建议”
            GJZWFWPT.PreviousCount = oldList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT")).Count(); //国家政务服务平台“投诉与建议”
            returnList.Add(GJZWFWPT);
            //省12345政务服务便民热线
            var Province12345 = new OnlineMassLineReportRes();
            Province12345.SourceChannel = "省12345政务服务便民热线";
            Province12345.SumCount = nowList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT") == false && x.ReceiveProvinceNo.StartsWith("ZGZFW") == false).Count(); //国家政务服务平台“投诉与建议”
            Province12345.PreviousCount = oldList.Where(x => x.IsProvince == true && x.ReceiveProvinceNo.StartsWith("GJZWFWPT") == false && x.ReceiveProvinceNo.StartsWith("ZGZFW") == false).Count(); //国家政务服务平台“投诉与建议”
            returnList.Add(Province12345);
            //市政府网站“市长与网民”
            var SZYSM = new OnlineMassLineReportRes();
            SZYSM.SourceChannel = "市政府网站“市长与网民”";
            SZYSM.SumCount = nowList.Where(x => x.SourceChannelCode == "SZYSM").Count(); //国家政务服务平台“投诉与建议”
            SZYSM.PreviousCount = oldList.Where(x => x.SourceChannelCode == "SZYSM").Count(); //国家政务服务平台“投诉与建议”
            returnList.Add(SZYSM);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OnlineMassLineReportRes>(dto.ColumnInfos);

            var dtos = _mapper.Map<ICollection<OnlineMassLineReportRes>>(returnList)
                              .Select(stu => _mapper.Map(stu, typeof(OnlineMassLineReportRes), dynamicClass))
                              .Cast<object>()
                              .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "网上群众路线统计");
        }

        /// <summary>
        /// 部门退回中心统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("org_sendback_statistics")]
        public async Task<List<OrgSendBackAuditListVo>> OrgSendBackAuditStatistics([FromQuery] OrgSendBackAuditListDto dto)
        {
            var quer = _orderApplication.OrgSendBackAuditList(dto);
            var list = await quer.ToListAsync(HttpContext.RequestAborted);
            list.Add(new OrgSendBackAuditListVo()
            {
                OrgName = "合计",
                Num = list.Sum(m => m.Num),
            });

            return list;
        }

        /// <summary>
        /// 部门退回中心统计
        /// </summary>
        /// <returns></returns>
        [HttpPost("org_sendback_statistics/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrgSendBackAuditStatisticsExport([FromBody] ExportExcelDto<OrgSendBackAuditListDto> dto)
        {
            var query = _orderApplication.OrgSendBackAuditList(dto.QueryDto);
            List<OrgSendBackAuditListVo> data;

            data = await query.ToListAsync(HttpContext.RequestAborted);

            data.Add(new OrgSendBackAuditListVo()
            {
                OrgName = "合计",
                Num = data.Sum(m => m.Num),
            });

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrgSendBackAuditListVo>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(OrgSendBackAuditListVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门退回统计");
        }

        /// <summary>
        /// 部门退回中心统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("org_sendback_detail")]
        public async Task<PagedDto<SendBackDto>> OrgSendBackDetail([FromQuery] OrgSendBackAuditListDto dto)
        {
            var quer = _orderApplication.OrgSendBackAuditDetail(dto);
            var (total, items) = await quer.ToPagedListAsync(dto.PageIndex, dto.PageSize);

            return new PagedDto<SendBackDto>(total, _mapper.Map<IReadOnlyList<SendBackDto>>(items));
        }

        /// <summary>
        /// 部门退回中心统计明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("org_sendback_detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> OrgSendBackDetailExport([FromBody] ExportExcelDto<OrgSendBackAuditListDto> dto)
        {
            var query = _orderApplication.OrgSendBackAuditDetail(dto.QueryDto);
            List<OrderSendBackAudit> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            var dataDtos = _mapper.Map<ICollection<SendBackDto>>(data);

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SendBackDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(SendBackDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "部门退回统计明细");
        }


        /// <summary>
        /// 坐席退回中心统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("seat_sendback_statistics")]
        public async Task<List<SeatSendBackStatisticsVo>> SeatSendBackStatistics([FromQuery] PagedKeywordRequest dto)
        {
            var quer = _orderApplication.SeatSendBackStatistics(dto);
            var list = await quer.ToListAsync(HttpContext.RequestAborted);
            list.Add(new SeatSendBackStatisticsVo()
            {
                UserName = "合计",
                SendOrderNum = list.Sum(m => m.SendOrderNum),
                SendOrderBackNum = list.Sum(m => m.SendOrderBackNum),
                SendOrderBackNumber = list.Sum(m => m.SendOrderBackNumber),
                CentreFileNum = list.Sum(m => m.CentreFileNum),
                CentreFileBackNum = list.Sum(m => m.CentreFileBackNum),
                CentreFileBackNumber = list.Sum(m => m.CentreFileBackNumber),
            });

            return list;
        }

        /// <summary>
        /// 坐席退回中心统计
        /// </summary>
        /// <returns></returns>
        [HttpPost("seat_sendback_statistics/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SeatSendBackStatisticsExport([FromBody] ExportExcelDto<PagedKeywordRequest> dto)
        {
            var query = _orderApplication.SeatSendBackStatistics(dto.QueryDto);
            List<SeatSendBackStatisticsVo> data;

            data = await query.ToListAsync(HttpContext.RequestAborted);

            data.Add(new SeatSendBackStatisticsVo()
            {
                UserName = "合计",
                SendOrderNum = data.Sum(m => m.SendOrderNum),
                SendOrderBackNum = data.Sum(m => m.SendOrderBackNum),
                SendOrderBackNumber = data.Sum(m => m.SendOrderBackNumber),
                CentreFileNum = data.Sum(m => m.CentreFileNum),
                CentreFileBackNum = data.Sum(m => m.CentreFileBackNum),
                CentreFileBackNumber = data.Sum(m => m.CentreFileBackNumber),
            });

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SeatSendBackStatisticsVo>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(SeatSendBackStatisticsVo), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "坐席退回统计");
        }

        /// <summary>
        /// 坐席退回统计明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("seat_sendback_detail")]
        public async Task<PagedDto<OrderDto>> SeatSendBackStatisticsDetail([FromQuery] SeatSendBackStatisticsDetail dto)
        {
            var quer = _orderApplication.SeatSendBackStatisticsDetail(dto);
            var (total, items) = await quer.ToPagedListAsync(dto.PageIndex, dto.PageSize);

            return new PagedDto<OrderDto>(total, items);
        }

        /// <summary>
        /// 坐席退回统计明细导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("seat_sendback_detail/_export")]
        [LogFilterAlpha("导出日志")]
        public async Task<FileStreamResult> SeatSendBackStatisticsDetailExport([FromBody] ExportExcelDto<SeatSendBackStatisticsDetail> dto)
        {
            var query = _orderApplication.SeatSendBackStatisticsDetail(dto.QueryDto);
            List<OrderDto> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<OrderDto>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(OrderDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "坐席退回统计明细");
        }

    }
}
