using DotNetCore.CAP;
using Hotline.Api.Filter;
using Hotline.ContingencyManagement;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.ContingencyManagement;
using Hotline.Share.Dtos.Order;
using Hotline.Tools;
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 ContingencyManagementController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly ISessionContext _sessionContext;
        private readonly IRepository<ContingencyManagementOrders> _contingencyManagementOrdersRepository;
        private readonly ICapPublisher _capPublisher;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="sessionContext"></param>
        /// <param name="contingencyManagementOrdersRepository"></param>
        /// <param name="capPublisher"></param>
        public ContingencyManagementController(IMapper mapper,
            ISessionContext sessionContext,
            IRepository<ContingencyManagementOrders> contingencyManagementOrdersRepository,
            ICapPublisher capPublisher)
        {
            _mapper = mapper;
            _sessionContext = sessionContext;
            _contingencyManagementOrdersRepository = contingencyManagementOrdersRepository;
            _capPublisher = capPublisher;
        }

        /// <summary>
        /// 应急数据查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<PagedDto<ContingencyManagementOrdersDto>> GetList([FromQuery] ContingencyManagementPagedKeywordRequest dto)
        {
            var (total, items) = await _contingencyManagementOrdersRepository.Queryable()
                .WhereIF(!string.IsNullOrEmpty(dto.Title), p => p.ArrangeTitle.Contains(dto.Title))
                .WhereIF(!string.IsNullOrEmpty(dto.No), p => p.No.Contains(dto.No))
                .WhereIF(!string.IsNullOrEmpty(dto.HotspotSpliceName), p => p.HotspotSpliceName.Contains(dto.HotspotSpliceName))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), p => p.AcceptType.Contains(dto.AcceptType))
                .WhereIF(!string.IsNullOrEmpty(dto.SourceChannel), p => p.SourceChannel.Contains(dto.SourceChannel))
                .WhereIF(dto.FiledStartTime.HasValue, p => p.FiledTime >= dto.FiledStartTime)
                .WhereIF(dto.FiledEndTime.HasValue, p => p.FiledTime <= dto.FiledEndTime)
                .WhereIF(dto.StartTime.HasValue, p => p.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, p => p.CreationTime <= dto.EndTime)
                .OrderByDescending(d => d.FiledTime)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

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

        /// <summary>
        /// 应急数据查询--导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("getlist_export")]
		[LogFilterAlpha("导出日志")]
		public async Task<FileStreamResult> GetListExport([FromBody] ExportExcelDto<ContingencyManagementPagedKeywordRequest> dto)
        {
            var query = _contingencyManagementOrdersRepository.Queryable()
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.Title), p => p.ArrangeTitle.Contains(dto.QueryDto.Title))
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.No), p => p.No.Contains(dto.QueryDto.No))
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.HotspotSpliceName), p => p.HotspotSpliceName.Contains(dto.QueryDto.HotspotSpliceName))
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.AcceptType), p => p.AcceptType.Contains(dto.QueryDto.AcceptType))
                .WhereIF(!string.IsNullOrEmpty(dto.QueryDto.SourceChannel), p => p.SourceChannel.Contains(dto.QueryDto.SourceChannel))
                .WhereIF(dto.QueryDto.FiledStartTime.HasValue, p => p.FiledTime >= dto.QueryDto.FiledStartTime)
                .WhereIF(dto.QueryDto.FiledEndTime.HasValue, p => p.FiledTime <= dto.QueryDto.FiledEndTime)
                .WhereIF(dto.QueryDto.StartTime.HasValue, p => p.CreationTime >= dto.QueryDto.StartTime)
                .WhereIF(dto.QueryDto.EndTime.HasValue, p => p.CreationTime <= dto.QueryDto.EndTime)
                .OrderByDescending(d => d.FiledTime);

            List<ContingencyManagementOrders> 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<ContingencyManagementOrdersDto>>(data);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<ContingencyManagementOrdersDto>(dto.ColumnInfos);
            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(ContingencyManagementOrdersDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);
            return ExcelStreamResult(stream, "应急清单数据");
        }

        /// <summary>
        /// 从新推送
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("repush")]
        public async Task RePush(string Id)
        {
            var orderData = await _contingencyManagementOrdersRepository.GetAsync(p => p.Id == Id, HttpContext.RequestAborted);

            if (orderData == null)
                throw UserFriendlyException.SameMessage("查询失败");
            //推送消息
            var pushaData = _mapper.Map<ContingencyManagementOrdersDto>(orderData);
            pushaData.Id = orderData.Id;
            //推送消息
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderContingencyManagement,
             pushaData, Hotline.Share.Mq.EventNames.HotlineOrderContingencyManagementState);
        }
    }
}
