using DocumentFormat.OpenXml.Office2010.Excel;
using Hotline.Api.Filter;
using Hotline.Application.JudicialManagement;
using Hotline.Caching.Interfaces;
using Hotline.File;
using Hotline.JudicialManagement;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Settings;
using Hotline.Settings.TimeLimits;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.JudicialManagement;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.JudicialManagement;
using Hotline.Share.Requests;
using Hotline.Tools;
using JiebaNet.Segmenter.Common;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers
{
    public class JudicialManagementOrdersController : BaseController
    {
        private readonly IRepository<JudicialComplaintsEventType> _judicialComplaintsEventTypeRepository;
        private readonly IRepository<EnforcementHotspot> _enforcementHotspotRepository;
        private readonly IMapper _mapper;
        private readonly ISystemDicDataCacheManager _sysDicDataCacheManager;
        private readonly IRepository<SystemOrganize> _systemOrganizeRepository;
        private readonly ISessionContext _sessionContext;
        private readonly IRepository<SystemArea> _systemAreaRepository;
        private readonly IRepository<JudicialManagementOrders> _judicialManagementOrdersRepository;
        private readonly IFileRepository _fileRepository;
        private readonly IJudicialManagementOrdersService _judicialManagementOrdersService;
        private readonly IRepository<EnforcementOrdersHandler> _enforcementOrdersHandlerRepository;
        private readonly IEnforcementApplication _enforcementApplication;
        private readonly IRepository<Order> _orderRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="judicialComplaintsEventTypeRepository"></param>
        /// <param name="enforcementHotspotRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="sysDicDataCacheManager"></param>
        /// <param name="systemOrganizeRepository"></param>
        /// <param name="sessionContext"></param>
        /// <param name="systemAreaRepository"></param>
        /// <param name="judicialManagementOrdersRepository"></param>
        /// <param name="fileRepository"></param>
        /// <param name="judicialManagementOrdersService"></param>
        /// <param name="enforcementOrdersHandlerRepository"></param>
        /// <param name="enforcementApplication"></param>
        /// <param name="orderRepository"></param>
        public JudicialManagementOrdersController(
         IRepository<JudicialComplaintsEventType> judicialComplaintsEventTypeRepository,
         IRepository<EnforcementHotspot> enforcementHotspotRepository,
         IMapper mapper,
         ISystemDicDataCacheManager sysDicDataCacheManager,
         IRepository<SystemOrganize> systemOrganizeRepository,
         ISessionContext sessionContext,
         IRepository<SystemArea> systemAreaRepository,
         IRepository<JudicialManagementOrders> judicialManagementOrdersRepository,
         IFileRepository fileRepository,
         IJudicialManagementOrdersService judicialManagementOrdersService,
         IRepository<EnforcementOrdersHandler> enforcementOrdersHandlerRepository,
         IEnforcementApplication enforcementApplication,
         IRepository<Order> orderRepository,
         IRepository<LawEnforcementAgencies> lawEnforcementAgenciesRepository
         )
        {
            _judicialComplaintsEventTypeRepository = judicialComplaintsEventTypeRepository;
            _enforcementHotspotRepository = enforcementHotspotRepository;
            _mapper = mapper;
            _sysDicDataCacheManager = sysDicDataCacheManager;
            _systemOrganizeRepository = systemOrganizeRepository;
            _sessionContext = sessionContext;
            _systemAreaRepository = systemAreaRepository;
            _judicialManagementOrdersRepository = judicialManagementOrdersRepository;
            _fileRepository = fileRepository;
            _judicialManagementOrdersService = judicialManagementOrdersService;
            _enforcementOrdersHandlerRepository = enforcementOrdersHandlerRepository;
            _enforcementApplication = enforcementApplication;
            _orderRepository = orderRepository;
        }

        /// <summary>
        /// 新增工单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [LogFilter("新增司法工单")]
        public async Task<string> Add([FromBody] JudicialManagementAddOrderDto dto)
        {
            dto.InitAddress();
            var order = _mapper.Map<JudicialManagementOrders>(dto);
            order.InitId();
            if (dto.Files.Any())
                order.FileJson = await _fileRepository.AddFileAsync(dto.Files, order.Id, "", HttpContext.RequestAborted);
            await _judicialManagementOrdersService.AddAsync(order, true, HttpContext.RequestAborted);

            //处理执法部门
            if (dto.EnforcementOrdersHandler != null && dto.EnforcementOrdersHandler.Any())
            {
                List<EnforcementOrdersHandler> enforcementOrdersHandlers = new();
                foreach (var item in dto.EnforcementOrdersHandler)
                {
                    enforcementOrdersHandlers.Add(new EnforcementOrdersHandler
                    {
                        OrderId = order.Id,
                        OrderNo = order.No,
                        OrderSoure = EOrderSoure.Enforcement,
                        OrgCode = item.Value,
                        OrgName = item.Key
                    });
                }
                if (enforcementOrdersHandlers != null && enforcementOrdersHandlers.Any())
                    await _enforcementOrdersHandlerRepository.AddRangeAsync(enforcementOrdersHandlers, HttpContext.RequestAborted);
            }
            return order.Id;
        }

        /// <summary>
        /// 更新工单信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        [LogFilter("更新司法工单")]
        public async Task Update([FromBody] JudicialManagementUpdateOrderDto dto)
        {
            dto.InitAddress();
            var order = await _judicialManagementOrdersRepository.Queryable().FirstAsync(d => d.Id == dto.Id);
            if (order == null)
                throw UserFriendlyException.SameMessage("无效工单编号");

            _mapper.Map(dto, order);
            if (dto.Files.Any())
                order.FileJson = await _fileRepository.AddFileAsync(dto.Files, order.Id, "", HttpContext.RequestAborted);
            else
                order.FileJson = new List<Share.Dtos.File.FileJson>();
            await _judicialManagementOrdersRepository.UpdateAsync(order, HttpContext.RequestAborted);

            //处理执法部门
            if (dto.EnforcementOrdersHandler != null && dto.EnforcementOrdersHandler.Any())
            {
                List<EnforcementOrdersHandler> enforcementOrdersHandlers = new();
                foreach (var item in dto.EnforcementOrdersHandler)
                {
                    enforcementOrdersHandlers.Add(new EnforcementOrdersHandler
                    {
                        OrderId = order.Id,
                        OrderNo = order.No,
                        OrderSoure = EOrderSoure.Enforcement,
                        OrgCode = item.Value,
                        OrgName = item.Key
                    });
                    if (enforcementOrdersHandlers != null && enforcementOrdersHandlers.Any())
                    {
                        await _enforcementOrdersHandlerRepository.RemoveAsync(p => p.OrderId == order.Id, false, HttpContext.RequestAborted);
                        await _enforcementOrdersHandlerRepository.AddRangeAsync(enforcementOrdersHandlers, HttpContext.RequestAborted);
                    }

                }
            }
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [LogFilter("启用/禁用司法工单")]
        public async Task Update(string id)
        {
            var order = await _judicialManagementOrdersRepository.GetAsync(id, HttpContext.RequestAborted);
            if (order == null)
                throw UserFriendlyException.SameMessage("工单查询失败");
            if (order.IsItCounted)
                order.IsItCounted = false;
            else
                order.IsItCounted = true;
            await _judicialManagementOrdersRepository.UpdateAsync(order, HttpContext.RequestAborted);
        }

        ///// <summary>
        ///// 关联执法部门
        ///// </summary>
        ///// <param name="dto"></param>
        ///// <returns></returns>
        //[HttpPut("associated_law_enforcement_gencies")]
        //[LogFilter("关联执法部门")]
        //public async Task AssociatedLawEnforcementAgencies([FromBody] AssociatedLawEnforcementAgenciesDto dto)
        //{
        //    if (dto.LawEnforcementAgencies == null || dto.LawEnforcementAgencies.Count == 0)
        //        throw UserFriendlyException.SameMessage("请选择执法部门");

        //    var order = await _judicialManagementOrdersRepository.GetAsync(dto.Id, HttpContext.RequestAborted);
        //    if (order == null)
        //        throw UserFriendlyException.SameMessage("工单查询失败");
        //    //处理执法部门
        //    if (dto.LawEnforcementAgencies != null && dto.LawEnforcementAgencies.Any())
        //    {
        //        List<LawEnforcementAgencies> lawEnforcementAgencies = new();
        //        foreach (var item in dto.LawEnforcementAgencies)
        //        {
        //            lawEnforcementAgencies.Add(new LawEnforcementAgencies
        //            {
        //                OrderId = order.Id,
        //                OrderNo = order.No,
        //                OrderSoure = EOrderSoure.Enforcement,
        //                OrgCode = item.Value,
        //                OrgName = item.Key
        //            });
        //        }
        //        if (lawEnforcementAgencies != null && lawEnforcementAgencies.Any())
        //        {
        //            await _enforcementOrdersHandlerRepository.AddRangeAsync(lawEnforcementAgencies, HttpContext.RequestAborted);
        //            order.LawEnforcementAgencies = dto.LawEnforcementAgencies;
        //            await _judicialManagementOrdersRepository.UpdateAsync(order, HttpContext.RequestAborted);
        //        }
        //    }

        //}

        /// <summary>
        /// 查询工单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<JudicialManagementOrderDto> Get(string id)
        {
            var order = await _judicialManagementOrdersRepository.Queryable().FirstAsync(d => d.Id == id);
            if (order == null)
                return new();
            var dto = _mapper.Map<JudicialManagementOrderDto>(order);

            //如果是12345创建的工单，查询办理信息
            if (dto.OrderSoure == EOrderSoure.Hotline)
            {
                var data = await _orderRepository.GetAsync(p => p.No == order.No, HttpContext.RequestAborted);
                if (data != null)
                {
                    dto.CenterToOrgTime = data.CenterToOrgTime;
                    dto.ActualHandleOrgName = data.ActualHandleOrgName;
                    dto.ActualHandleTime = data.ActualHandleTime;
                    dto.TimeLimit = data.TimeLimit;
                    dto.TimeLimitUnit = data.TimeLimitUnit;
                    dto.TimeLimitCount = data.TimeLimitCount;
                    dto.ExpiredTime = data.ExpiredTime;
                    dto.IsResolved = data.IsResolved;
                    dto.FileOpinion = data.FileOpinion;
                    dto.CenterOpinion = data.CenterToOrgOpinion;
                    dto.EnforcementOrdersHandler = order.EnforcementOrdersHandler;
                }
            }

            if (dto.FileJson != null && dto.FileJson.Any())
            {
                var ids = order.FileJson.Select(x => x.Id).ToList();
                var files = await _fileRepository.GetFilesAsync(ids, HttpContext.RequestAborted);
                dto.Files = files.Where(x => string.IsNullOrEmpty(x.FlowKey)).ToList();
            }
            return dto;
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        [LogFilter("删除工单")]
        public async Task Remove(string id)
        {
            var order = await _judicialManagementOrdersRepository.GetAsync(id, HttpContext.RequestAborted);
            if (order == null) return;
            //if (order.Status != EOrderStatus.WaitForAccept)
            //    throw UserFriendlyException.SameMessage("非草稿工单不可删除");
            await _judicialManagementOrdersRepository.RemoveAsync(order);
        }

        /// <summary>
        /// 受理工单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("getownorderlist")]
        public async Task<PagedDto<EnforcementOrderListDto>> GetOwnOrderList([FromQuery] QueryEnforcementOrderNewDto dto)
        {
            var (total, items) = await _enforcementApplication.GetOwnOrderList(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<EnforcementOrderListDto>(total, _mapper.Map<List<EnforcementOrderListDto>>(items));
        }

        /// <summary>
        /// 受理工单--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("getownorderlist_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetOwnOrderListExport([FromBody] ExportExcelDto<QueryEnforcementOrderNewDto> dto)
        {
            var query = _enforcementApplication.GetOwnOrderList(dto.QueryDto);
            List<JudicialManagementOrders> 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<EnforcementOrderListDto>>(data);

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

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

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "自定义工单数据");
        }

        /// <summary>
        /// 司法行政监督管理工单查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("getorderlist")]
        public async Task<PagedDto<EnforcementOrderListDto>> GetOrderList([FromQuery] QueryEnforcementOrderNewDto dto)
        {
            var (total, items) = await _enforcementApplication.GetOrderList(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            var data = _mapper.Map<List<EnforcementOrderListDto>>(items);

            if (_sessionContext.RequiredOrgId == "001188")
            {
                foreach (var item in data)
                {
                    if (item.IsTheClueTrue.HasValue)
                        item.IsShowUpdateButton = true;
                }
            }
            return new PagedDto<EnforcementOrderListDto>(total, data);
        }

        /// <summary>
        /// 司法行政监督管理工单查询---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("getorderlist_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetOrderListExport([FromBody] ExportExcelDto<QueryEnforcementOrderNewDto> dto)
        {
            var query = _enforcementApplication.GetOrderList(dto.QueryDto);
            List<JudicialManagementOrders> 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<EnforcementOrderListDto>>(data);

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

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

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "工单中心数据");

        }

        /// <summary>
        /// 列表页面基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("base-data")]
        public async Task<object> BaseData()
        {
            var orgList = await _systemOrganizeRepository.Queryable().OrderBy(d => d.Id).ToTreeAsync(x => x.Children, it => it.ParentId, null);
            var judicialManagementOrg = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.JudicialManagementOrg);

            List<SystemOrganize> OrgsOptions = new();
            foreach (var item in judicialManagementOrg)
            {
                var tempOrg = orgList.Find(p => p.Id == item.DicDataValue);
                if (tempOrg != null)
                    OrgsOptions.Add(tempOrg);
            }
            var listChannelOptions = _sysDicDataCacheManager.GetSysDicDataCache(TimeLimitBaseDataConsts.SourceChannel).ToList();
            var ChannelOptions = new List<Kv>();
            foreach (var item in listChannelOptions)
            {
                ChannelOptions.Add(new Kv { Key = item.DicDataName, Value = item.DicDataValue });
            }
            ChannelOptions.Add(new Kv { Key = "自定义", Value = "ZDY" });
            var listAcceptTypeOptions = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.AcceptType).ToList();
            var AcceptTypeOptions = new List<Kv>();
            foreach (var item in listAcceptTypeOptions)
            {
                AcceptTypeOptions.Add(new Kv { Key = item.DicDataName, Value = item.DicDataValue });
            }
            var rsp = new
            {
                AcceptTypeOptions,
                ChannelOptions,
                OrgsOptions,
                EnforcementHotspot = await _enforcementHotspotRepository.Queryable().ToTreeAsync(it => it.Children, it => it.ParentId, null, it => it.Id)
            };
            return rsp;
        }

        /// <summary>
        /// 根据当前部门获取区域
        /// </summary>
        /// <returns></returns>
        [HttpGet("area/tree")]
        public async Task<object> GetAreaTree()
        {
            var areaCode = _sessionContext.OrgAreaCode;
            if (string.IsNullOrEmpty(areaCode))
                areaCode = "511500";
            if (areaCode == "511500")
            {
                return await _systemAreaRepository.Queryable()
                              .Where(p => p.Id == "511500" || p.ParentId == "511500")
                              .Select(p => new
                              {
                                  p.AreaName,
                                  p.Id
                              })
                              .OrderBy(p => p.Id)
                              .ToListAsync();
            }
            else
            {
                return await _systemAreaRepository.Queryable()
                             .Where(p => p.Id == _sessionContext.OrgAreaCode)
                             .Select(p => new
                             {
                                 p.AreaName,
                                 p.Id
                             })
                             .OrderBy(p => p.Id)
                             .ToListAsync();
            }
        }

        /// <summary>
        /// 线索核实  
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("clue_verification")]
        public async Task ClueVerificationAsync([FromBody] ClueVerificationDto dto)
        {
            if (dto.OrderIds == null || dto.OrderIds.Count == 0)
                throw UserFriendlyException.SameMessage("工单不能为空");

            if (dto.IsTheClueTrue.HasValue && dto.IsTheClueTrue.Value == true)
            {
                if (string.IsNullOrEmpty(dto.EventTypeId) || string.IsNullOrEmpty(dto.EventTypeName))
                    throw UserFriendlyException.SameMessage("事项不能为空");
            }

            foreach (var item in dto.OrderIds)
            {
                var order = await _judicialManagementOrdersRepository.GetAsync(p => p.Id == item, HttpContext.RequestAborted);
                if (order == null)
                    throw UserFriendlyException.SameMessage("工单查询失败");

                order.IsTheClueTrue = dto.IsTheClueTrue;

                if (!string.IsNullOrEmpty(dto.EventTypeName))
                    order.EventTypeName = dto.EventTypeName;
                else
                    order.EventTypeName = "";

                if (!string.IsNullOrEmpty(dto.EventTypeSpliceName))
                    order.EventTypeSpliceName = dto.EventTypeSpliceName;
                else
                    order.EventTypeSpliceName = "";

                if (!string.IsNullOrEmpty(dto.EventTypeId))
                {
                    order.EventTypeOneLevelId = dto.EventTypeId.Substring(0, 2);
                    order.EventTypeId = dto.EventTypeId;
                }
                else
                {
                    order.EventTypeOneLevelId = "";
                    order.EventTypeId = "";
                }
                if (!order.IsTheClueTrue.HasValue || order.IsTheClueTrue.Value == false)
                {
                    order.EventTypeName = "";
                    order.EventTypeSpliceName = "";
                    order.EventTypeOneLevelId = "";
                    order.EventTypeId = "";
                }
                order.CaseType = dto.CaseType ?? Share.Enums.Order.ECaseType.General;
                await _judicialManagementOrdersRepository.UpdateAsync(order, HttpContext.RequestAborted);
            }
        }

        /// <summary>
        /// 行政执法活动投诉事项类型- 获取层级分类
        /// </summary>
        /// <returns></returns>
        [HttpGet("treelist")]
        public async Task<List<JudicialComplaintsEventType>> GetTreeList()
        {
            return await _judicialComplaintsEventTypeRepository.Queryable().ToTreeAsync(it => it.Children, it => it.ParentId, null, it => it.Id);
        }

        /// <summary>
        /// 事项分类统计
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="Id"></param>
        /// <param name="AreaCode"></param>
        /// <returns></returns>
        [HttpGet("event_classification_statistics")]
        public async Task<object> GetEventClassificationStatisticsAsync(DateTime StartTime, DateTime EndTime, string Id, string AreaCode)
        {
            string areCodeText = "";
            if (string.IsNullOrEmpty(AreaCode))
            {
                if (_sessionContext.OrgAreaCode != "511500")
                    areCodeText = _sessionContext.OrgAreaCode;
            }
            else
                areCodeText = AreaCode;

            var items = await _judicialComplaintsEventTypeRepository.Queryable()
            .LeftJoin<JudicialManagementOrders>((x, o) => o.EventTypeSpliceName != null &&
            (x.EventTypeName == o.EventTypeSpliceName || o.EventTypeSpliceName.Contains(x.EventTypeName)))
           .Where((x, o) => o.CreationTime >= StartTime && o.CreationTime <= EndTime && o.IsItCounted == true)
           .WhereIF(!string.IsNullOrEmpty(areCodeText), (x, o) => o.AreaCode.StartsWith(areCodeText))
            .Where((x, o) => x.ParentId == Id)
            .GroupBy((x, o) => new { x.Id, x.EventTypeName })
            .Select((x, o) => new
            {
                Id = x.Id,
                Name = x.EventTypeName,
                Num = SqlFunc.AggregateSum(SqlFunc.IIF(o.Id != null, 1, 0)),
                Sublevel = SqlFunc.AggregateSum(SqlFunc.IIF(x.EventTypeName != o.EventTypeName, 1, 0)) > 0,
            })
            .MergeTable()
            .ToListAsync();

            var data = await _judicialManagementOrdersRepository.Queryable()
                .Where(d => d.CreationTime >= StartTime && d.CreationTime <= EndTime)
                .WhereIF(!string.IsNullOrEmpty(areCodeText), p => p.AreaCode.StartsWith(areCodeText))
                .GroupBy(d => d.Id)
                 .Select(d => new EventClassificationOrderCountDto
                 {
                     TheClueIsTrue = SqlFunc.AggregateSum(SqlFunc.IIF(d.IsEnforcementOrder.HasValue && d.IsEnforcementOrder.Value == true, 1, 0)),
                     TheClueIsNotTrue = SqlFunc.AggregateSum(SqlFunc.IIF(d.IsEnforcementOrder.HasValue && d.IsEnforcementOrder.Value == false, 1, 0)),
                     EnforcementOrder = SqlFunc.AggregateSum(SqlFunc.IIF(d.IsEnforcementOrder.HasValue && d.IsEnforcementOrder.Value == true, 1, 0)),
                     PassTheBuckOrder = SqlFunc.AggregateSum(SqlFunc.IIF(d.IsPassTheBuckOrder, 1, 0)),
                     ToBeVerified = SqlFunc.AggregateSum(SqlFunc.IIF(d.IsTheClueTrue == null, 1, 0)),
                 })
                   .ToListAsync();

            var orderCount = new
            {
                TheClueIsTrue = data.Sum(x => x.TheClueIsTrue),
                TheClueIsNotTrue = data.Sum(x => x.TheClueIsNotTrue),
                EnforcementOrder = data.Sum(x => x.EnforcementOrder),
                PassTheBuckOrder = data.Sum(x => x.PassTheBuckOrder),
                ToBeVerified = data.Sum(x => x.ToBeVerified),
                TotalOrder = data.Sum(x => x.TheClueIsNotTrue) + data.Sum(x => x.EnforcementOrder) + data.Sum(x => x.PassTheBuckOrder)
            };

            return new { List = items, OrderCount = orderCount };
        }

        /// <summary>
        /// 事项分类统计--明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("event_classification_statistics_order_list")]
        public async Task<PagedDto<EnforcementOrderListDto>> GetEventClassificationStatisticsOrderListAsync([FromQuery] QueryEventClassificationStatisticsDto dto)
        {
            var (total, items) = await _enforcementApplication.GetEventClassificationStatisticsOrderListAsync(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<EnforcementOrderListDto>(total, _mapper.Map<List<EnforcementOrderListDto>>(items));
        }

        /// <summary>
        /// 事项分类统计--明细--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("event_classification_statistics_order_list_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetEventClassificationStatisticsOrderListExportAsync([FromBody] ExportExcelDto<QueryEventClassificationStatisticsDto> dto)
        {
            var query = _enforcementApplication.GetEventClassificationStatisticsOrderListAsync(dto.QueryDto);
            List<JudicialManagementOrders> 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<EnforcementOrderListDto>>(data);

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

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

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "事项分类统计明细数据");

        }

        /// <summary>
        /// 执法部门办件统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("enforcement_departmental_processing_statistics")]
        public async Task<List<EmDepartmentalProcessingStatisticsDto>> GetDepartmentalProcessingStatisticsAsync([FromQuery] QueryDepartmentalProcessingStatisticsDto dto)
        {
            return await _enforcementApplication.GetDepartmentalProcessingStatisticsAsync(dto.StartTime, dto.EndTime).ToListAsync();

        }

        /// <summary>
        /// 执法部门办件统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("enforcement_departmental_processing_statistics_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetDepartmentalProcessingStatisticsExportAsync([FromBody] ExportExcelDto<QueryDepartmentalProcessingStatisticsDto> dto)
        {
            var list = await _enforcementApplication.GetDepartmentalProcessingStatisticsAsync(dto.QueryDto.StartTime, dto.QueryDto.EndTime).ToListAsync();

            list.Add(new EmDepartmentalProcessingStatisticsDto
            {
                OrgCode = "",
                OrgName = "合计",
                CountNum = list.Sum(p => p.CountNum),
                TheClueIsTrue = list.Sum(p => p.TheClueIsTrue),
                TheClueIsNotTrue = list.Sum(p => p.TheClueIsNotTrue),
                EnforcementOrder = list.Sum(p => p.EnforcementOrder)
            });

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

            var stream = ExcelHelper.CreateStream(dtos);

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

        }

        /// <summary>
        /// 执法部门办件统计---明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("enforcement_departmental_processing_statistics_order_list")]
        public async Task<PagedDto<EnforcementOrderListDto>> GetDepartmentalProcessingStatisticsOrderListAsync([FromQuery] QueryDepartmentalProcessingStatisticsDto dto)
        {
            var (total, items) = await _enforcementApplication.GetDepartmentalProcessingStatisticsOrderListAsync(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<EnforcementOrderListDto>(total, items);
        }

        /// <summary>
        /// 执法领域统计
        /// </summary>
        /// <param name="queryIndustryOrderStatisticsRequest"></param>
        /// <returns></returns>
        [HttpGet("enforcement_industry_statistics_order")]
        public async Task<List<IndustryOrderStaticsDto>> QueryIndustryOrderStatics([FromQuery] QueryIndustryOrderStatisticsRequest queryIndustryOrderStatisticsRequest)
        {
            return await _enforcementApplication.QueryIndustryOrderStatics(queryIndustryOrderStatisticsRequest);
        }

        /// <summary>
        /// 执法领域统计--导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("enforcement_industry_statistics_order_export")]
        public async Task<FileStreamResult> QueryIndustryOrderStaticsExportAsync([FromBody] ExportExcelDto<QueryIndustryOrderStatisticsRequest> dto)
        {
            var list = await _enforcementApplication.QueryIndustryOrderStatics(dto.QueryDto);

            list.Add(new IndustryOrderStaticsDto()
            {
                IndustryName = "总计",
                EnforcementOrderCount = list.Sum(x => x.EnforcementOrderCount),
                NotEnforcementOrderCount = list.Sum(x => x.NotEnforcementOrderCount),
                ToBeVerifiedOrderCount = list.Sum(x => x.ToBeVerifiedOrderCount),
                TotalOrderCount = list.Sum(x => x.TotalOrderCount)
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<IndustryOrderStaticsDto>(dto.ColumnInfos);
            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(IndustryOrderStaticsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "执法领域统计");
        }

        /// <summary>
        /// 执法部门办件统计---明细---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("enforcement_departmental_processing_statistics_order_list_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetDepartmentalProcessingStatisticsOrderListExportAsync([FromBody] ExportExcelDto<QueryDepartmentalProcessingStatisticsDto> dto)
        {
            var query = _enforcementApplication.GetDepartmentalProcessingStatisticsOrderListAsync(dto.QueryDto);
            List<EnforcementOrderListDto> 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<EnforcementOrderListDto>(dto.ColumnInfos);

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

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "执法部门办件统计明细数据");

        }

        /// <summary>
        /// 区域分类统计
        /// </summary>
        /// <returns></returns>
        [HttpGet("regional_classification_statistics")]
        public async Task<object> GetRegionalClassificationStatisticsAsync([FromQuery] QueryRegionalClassificationStatisticsDto dto)
        {
            return await _enforcementApplication.GetRegionalClassificationStatisticsAsync(dto.StartTime, dto.EndTime).ToListAsync();
        }

        /// <summary>
        /// 区域分类统计--导出
        /// </summary>
        /// <returns></returns>
        [HttpPost("regional_classification_statistics_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetRegionalClassificationStatisticsExportAsync([FromBody] ExportExcelDto<QueryRegionalClassificationStatisticsDto> dto)
        {
            var list = await _enforcementApplication.GetRegionalClassificationStatisticsAsync(dto.QueryDto.StartTime, dto.QueryDto.EndTime).ToListAsync();

            list.Add(new RegionalClassificationStatisticsDto()
            {
                AreaCode = "",
                AreaName = "总计",
                OrderCountNum = list.Sum(x => x.OrderCountNum),
                TheClueIsTrue = list.Sum(x => x.TheClueIsTrue),
                TheClueIsNotTrue = list.Sum(x => x.TheClueIsNotTrue),
                EnforcementOrder = list.Sum(x => x.EnforcementOrder)
            });
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<RegionalClassificationStatisticsDto>(dto.ColumnInfos);
            var dtos = list
                .Select(stu => _mapper.Map(stu, typeof(RegionalClassificationStatisticsDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "区域分类统计数据");
        }

        /// <summary>
        /// 区域分类统计---明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("regional_classification_statistics_order_list")]
        public async Task<PagedDto<EnforcementOrderListDto>> GetRegionalClassificationStatisticsOrderListAsync([FromQuery] QueryRegionalClassificationStatisticsDto dto)
        {
            var (total, items) = await _enforcementApplication.GetRegionalClassificationStatisticsOrderListAsync(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<EnforcementOrderListDto>(total, _mapper.Map<List<EnforcementOrderListDto>>(items));
        }

        /// <summary>
        /// 区域分类统计---明细---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("regional_classification_statistics_order_list_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetRegionalClassificationStatisticsOrderListExportAsync([FromBody] ExportExcelDto<QueryRegionalClassificationStatisticsDto> dto)
        {
            var query = _enforcementApplication.GetRegionalClassificationStatisticsOrderListAsync(dto.QueryDto);
            List<JudicialManagementOrders> 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<EnforcementOrderListDto>>(data);

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

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

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "区域分类统计明细数据");

        }

        /// <summary>
        /// 部门满意度统计
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("enforcement_visit_org_satisfaction_statistics")]
        public async Task<object> GetVisitAndOrgSatisfactionStatisticsAsync([FromQuery] QueryOrgSatisfactionStatisticsDto dto)
        {
            var list = await _enforcementApplication.GetVisitAndOrgSatisfactionStatisticsAsync(dto.StartTime, dto.EndTime, dto.TypeId).ToListAsync();

            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),
            };

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

        /// <summary>
        /// 部门满意度统计--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("enforcement_visit_org_satisfaction_statistics_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<object> GetVisitAndOrgSatisfactionStatisticsExportAsync([FromBody] ExportExcelDto<QueryOrgSatisfactionStatisticsDto> dto)
        {
            var list = await _enforcementApplication.GetVisitAndOrgSatisfactionStatisticsAsync(dto.QueryDto.StartTime, dto.QueryDto.EndTime, dto.QueryDto.TypeId).ToListAsync();

            list.Add(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),
            });
            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("enforcement_visit_org_satisfaction_statistics_order_list")]
        public async Task<PagedDto<EnforcementOrgSatisfactionOrderListDto>> GetVisitAndOrgSatisfactionStatisticsOrderListAsync([FromQuery] QueryOrgSatisfactionStatisticsDto dto)
        {
            var (total, items) = await _enforcementApplication.GetVisitAndOrgSatisfactionStatisticsOrderListAsync(dto).ToPagedListAsync(dto, HttpContext.RequestAborted);
            return new PagedDto<EnforcementOrgSatisfactionOrderListDto>(total, items);
        }

        /// <summary>
        /// 部门满意度统计---明细---导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("enforcement_visit_org_satisfaction_statistics_order_list_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetVisitAndOrgSatisfactionStatisticsOrderListExportAsync([FromBody] ExportExcelDto<QueryOrgSatisfactionStatisticsDto> dto)
        {
            var query = _enforcementApplication.GetVisitAndOrgSatisfactionStatisticsOrderListAsync(dto.QueryDto);
            List<EnforcementOrgSatisfactionOrderListDto> 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<EnforcementOrgSatisfactionOrderListDto>(dto.ColumnInfos);

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

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

        ///// <summary>
        ///// 处理司法历史工单数据
        ///// </summary>
        ///// <param name="Year"></param>
        ///// <param name="Month"></param>
        ///// <returns></returns>
        //[HttpGet("add_enforcement_old_order")]
        //public async Task AddEnforcementOldOrder(int Year, int Month)
        //{
        //    DateTime StartDate = DateTime.Parse(Year + "-" + Month + "-01 00:00:00");
        //    DateTime EndDate = StartDate.AddMonths(1).AddSeconds(-1);

        //    var list = await _orderRepository.Queryable()
        //        .Where(p => p.CreationTime >= StartDate && p.CreationTime <= EndDate && p.Status >= EOrderStatus.Filed && p.AcceptTypeCode != "10")
        //        .Select(p => new EnforcementOldOrder()
        //        {
        //            Id = p.Id,
        //            No = p.No,
        //            HotspotId = p.HotspotId,
        //            HandleTime = p.ActualHandleTime,
        //            OrgLevelOneCode = p.OrgLevelOneCode,
        //            ActualHandleOrgCode = p.ActualHandleOrgCode
        //        })
        //        .ToListAsync();

        //    if (list != null && list.Count > 0)
        //    {
        //        //查询指定热点数据
        //        var hotList = await _enforcementHotspotRepository.Queryable().ToListAsync();

        //        //查询指定部门数据
        //        var JudicialManagementOrg = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.JudicialManagementOrg).ToList();

        //        foreach (var item in list)
        //        {
        //            bool isAdd = false;

        //            //如果是特定热点写入数据
        //            if (hotList.Exists(p => p.Id == item.HotspotId))
        //                isAdd = true;

        //            if (!string.IsNullOrEmpty(item.OrgLevelOneCode))
        //            {
        //                //如果是特定部门办理写入数据
        //                if (JudicialManagementOrg.Exists(p => p.DicDataValue.Trim() == item.OrgLevelOneCode))
        //                    isAdd = true;
        //            }

        //            if (isAdd)
        //            {
        //                //是否存在此工单
        //                if (!await _enforcementOrdersRepository.AnyAsync(p => p.Id == item.Id, HttpContext.RequestAborted))
        //                {
        //                    //  不存在写入
        //                    EnforcementOrders enforcementOrders = new()
        //                    {
        //                        Id = item.Id,
        //                        OrderNo = item.No,
        //                        IsEnforcementOrder = false,
        //                        IsTheClueTrue = null,
        //                        IsPassTheBuckOrder = false,
        //                        CreationTime = item.HandleTime != null ? item.HandleTime.Value : DateTime.Now
        //                    };
        //                    await _enforcementOrdersRepository.AddAsync(enforcementOrders, HttpContext.RequestAborted);

        //                }
        //            }
        //        }
        //    }
        //}


    }
}
