using DotNetCore.CAP;
using Hotline.Caching.Interfaces;
using Hotline.FlowEngine.Notifications;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.Orders;
using Hotline.Settings;
using Hotline.Settings.TimeLimits;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using XF.Domain.Constants;
using XF.Domain.Repository;

namespace Hotline.Application.Handlers.FlowEngine;

public class WorkflowRecallHandler : INotificationHandler<RecallNotify>
{
    private readonly IOrderDomainService _orderDomainService;
    private readonly IOrderRepository _orderRepository;
    private readonly IWorkflowDomainService _workflowDomainService;
    private readonly ITimeLimitDomainService _timeLimitDomainService;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;
    private readonly ICapPublisher _capPublisher;
    private readonly IMapper _mapper;
    private readonly ILogger<WorkflowRecallHandler> _logger;
    private readonly IRepository<OrderPublish> _orderPublishRepository;
    private readonly IRepository<OrderVisit> _orderVisitRepository;
    private readonly IRepository<OrderVisitDetail> _orderVisitedDetailRepository;
    private readonly IRepository<OrderPublishHistory> _orderPublishHistoryRepository;

    public WorkflowRecallHandler(
        IOrderDomainService orderDomainService,
        IOrderRepository orderRepository,
        IWorkflowDomainService workflowDomainService,
        ITimeLimitDomainService timeLimitDomainService,
        ISystemSettingCacheManager systemSettingCacheManager,
        IRepository<OrderPublish> orderPublishRepository,
        IRepository<OrderVisit> orderVisitRepository,
        IRepository<OrderVisitDetail> orderVisitedDetailRepository,
        IRepository<OrderPublishHistory> orderPublishHistoryRepository,
        ICapPublisher capPublisher,
        IMapper mapper,
        ILogger<WorkflowRecallHandler> logger)
    {
        _orderDomainService = orderDomainService;
        _orderRepository = orderRepository;
        _workflowDomainService = workflowDomainService;
        _timeLimitDomainService = timeLimitDomainService;
        _systemSettingCacheManager = systemSettingCacheManager;
        _capPublisher = capPublisher;
        _orderPublishRepository = orderPublishRepository;
        _orderVisitRepository = orderVisitRepository;
        _orderVisitedDetailRepository = orderVisitedDetailRepository;
        _orderPublishHistoryRepository = orderPublishHistoryRepository;
        _mapper = mapper;
        _logger = logger;
    }

    /// <summary>Handles a notification</summary>
    /// <param name="notification">The notification</param>
    /// <param name="cancellationToken">Cancellation token</param>
    public async Task Handle(RecallNotify notification, CancellationToken cancellationToken)
    {
        try
        {
            var workflow = notification.Workflow;
            var data = notification.Dto;

            switch (workflow.ModuleCode)
            {
                case WorkflowModuleConsts.OrderHandle:
     //               var order = await _orderDomainService.GetOrderAsync(workflow.ExternalId, withHotspot: true, withAcceptor: true,
     //                   withExtension: true, cancellationToken: cancellationToken);
     //               //order.UpdateHandlingStatus(workflow.IsInCountersign);
     //               _mapper.Map(workflow, order);
     //               order.FileEmpty();
					//if (notification.TargetStep.StepType is EStepType.Start)
     //               {
     //                   //if (!bool.TryParse(
     //                   //        _systemSettingCacheManager.GetSetting(SettingConstants.IsRecallToSeatDesignated)?.SettingValue[0],
     //                   //        out var isRecallToSeatDesignated))
     //                   //    isRecallToSeatDesignated = false;
     //                   //var isRecallToSeatDesignated = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsRecallToSeatDesignated).SettingValue[0]);
     //                   order.Status = EOrderStatus.SpecialToUnAccept;
     //                   //if (isRecallToSeatDesignated)
     //                   //{
     //                   //    if (data.HandlerType is EHandlerType.Role or EHandlerType.AssignedUser)
     //                   //    {
     //                   //        var handler = data.NextHandlers.FirstOrDefault();
     //                   //        if (handler != null)
     //                   //        {
     //                   //            order.SignerId = handler.Key;
     //                   //            order.SignerName = handler.Value;
     //                   //        }
     //                   //    }
     //                   //}
     //                   //else
     //                   //{
     //                   //    //order.BackToUnsign();
     //                   //}
     //               }
     //               else
     //               {
	    //                order.Status = EOrderStatus.Special;
     //               }
					//await _orderRepository.UpdateAsync(order, false, cancellationToken);
                    //var publish = await _orderPublishRepository.GetAsync(x => x.OrderId == order.Id, cancellationToken);
                    //if (publish != null)
                    //{
                    //    var publishHistory = _mapper.Map<OrderPublishHistory>(publish);
                    //    publishHistory.OrderPublishId = publish.Id;
                    //    publishHistory.ArrangeTitleAfter = publish.ArrangeTitle;
                    //    publishHistory.ArrangeTitleBefor = publish.ArrangeTitle;
                    //    publishHistory.ArrangeContentAfter = publish.ArrangeContent;
                    //    publishHistory.ArrangeContentBefor = publish.ArrangeContent;
                    //    publishHistory.ArrangeOpinionAfter = publish.ArrangeOpinion;
                    //    publishHistory.ArrangeOpinionBefor = publish.ArrangeOpinion;
                    //    await _orderPublishHistoryRepository.AddAsync(publishHistory, cancellationToken);
                    //    await _orderPublishRepository.RemoveAsync(publish, false, cancellationToken);
                    //}

                    //var visit = await _orderVisitRepository.GetAsync(x => x.OrderId == order.Id && x.VisitState != EVisitState.None, cancellationToken);
                    //if (visit != null)
                    //{
                    //    visit.VisitState = EVisitState.None;
                    //    await _orderVisitRepository.UpdateAsync(visit, cancellationToken);
                    //}
                    break;
                case WorkflowModuleConsts.KnowledgeAdd:
                case WorkflowModuleConsts.KnowledgeUpdate:
                case WorkflowModuleConsts.KnowledgeDelete:
                case WorkflowModuleConsts.KnowledgeOffshelf:
				case WorkflowModuleConsts.TelRestApply:
                    break;
            }
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(WorkflowEndHandler)}异常，{e}");
            throw;
        }
    }
}