using Hotline.BatchTask.Notifications;
using Hotline.FlowEngine.Notifications;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hotline.BatchTask;
using Hotline.Share.Enums.BatchTask;
using Hotline.Article;
using Hotline.Orders;
using Hotline.Share.Dtos.Article;
using Hotline.Share.Enums.Article;
using Hotline.Share.Enums.Order;
using XF.Domain.Authentications;
using XF.Domain.Repository;

namespace Hotline.Application.OrderApp.Handlers.OrderDelayHandler;

/// <summary>
/// 延期批量审批任务执行完成
/// </summary>
public class OrderDelayBatchReviewTaskCompetedHandler : INotificationHandler<ApptaskCompletedNotify>
{
    private readonly IRepository<Apptask> _apptaskRepository;
    private readonly IOrderDelayRepository _orderDelayRepository;
    private readonly ICircularRecordDomainService _circularRecordDomainService;

    public OrderDelayBatchReviewTaskCompetedHandler(
        IRepository<Apptask> apptaskRepository,
        IOrderDelayRepository orderDelayRepository,
        ICircularRecordDomainService circularRecordDomainService)
    {
        _apptaskRepository = apptaskRepository;
        _orderDelayRepository = orderDelayRepository;
        _circularRecordDomainService = circularRecordDomainService;
    }

    /// <summary>Handles a notification</summary>
    /// <param name="notification">The notification</param>
    /// <param name="cancellationToken">Cancellation token</param>
    public async Task Handle(ApptaskCompletedNotify notification, CancellationToken cancellationToken)
    {
        if (notification.ApptaskItem.TaskType is not ETaskType.OrderDelay) return;

        var apptask = await _apptaskRepository.Queryable()
            .Includes(d => d.ApptaskItems)
            .FirstAsync(d => d.Id == notification.ApptaskItem.ApptaskId, cancellationToken);
        var unSuccessItems = apptask.ApptaskItems
            .Where(d => d.TaskStatus != ETaskStatus.Succeeded)
            .ToList();
        if (unSuccessItems.Count > 0)
        {
            // 回滚delay状态为待审批
            await _orderDelayRepository.Updateable()
                .SetColumns(d => d.DelayState == EDelayState.Examining)
                .Where(d => unSuccessItems.Select(x => x.BusinessId).Contains(d.Id))
                .ExecuteCommandAsync(cancellationToken);
        }

        await _circularRecordDomainService.AddCircularMessage(new AddCircularDto
        {
            Title = $"{apptask.Name} 执行完成",
            Content = $"总共：{apptask.ApptaskItems.Count}个任务，成功：{apptask.ApptaskItems.Count(d => d.TaskStatus == ETaskStatus.Succeeded)}，失败：{apptask.ApptaskItems.Count(d => d.TaskStatus == ETaskStatus.Failed)}",
            CircularTypeId = "5",
            CircularTypeName = "系统消息",
            CircularType = ECircularType.Person,
            IsMustRead = false,
            SourceOrgId = apptask.CreatorId,
            SourceOrgName = apptask.CreatorName,
            CircularReadGroups = new List<CircularReadGroupDto>
            {
                new()
                {
                    UserId = apptask.CreatorId,
                    UserName = apptask.CreatorName
                }
            }
        }, cancellationToken);
    }
}