using AutoMapper;
using Kean.Domain.Task.Commands;
using Kean.Domain.Task.Enums;
using Kean.Domain.Task.Events;
using Kean.Domain.Task.Repositories;
using Kean.Domain.Task.SharedServices.Proxies;
using Newtonsoft.Json;
using System;
using System.Threading;

namespace Kean.Domain.Task.CommandHandlers
{
    /// <summary>
    /// 任务取消命令处理程序
    /// </summary>
    public sealed class CallDeleteCommandHandler : CommandHandler<CallDeleteCommand>
    {
        private readonly ICommandBus _commandBus; // 命令总线
        private readonly IMapper _mapper; // 模型映射
        private readonly ITaskRepository _taskRepository; // 任务仓库
        private readonly IWarehouseRepository _warehouseRepository; // 库房仓库
        private readonly StockProxy _stockProxy; // 库房仓库
        private readonly WcsProxy _wcsProxy;
        private readonly Kean.Infrastructure.Soap.LED.LedService _ledService;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public CallDeleteCommandHandler(
            ICommandBus commandBus,
            IMapper mapper,
            ITaskRepository taskRepository,
            StockProxy stockProxy,
            WcsProxy wcsProxy,
            Kean.Infrastructure.Soap.LED.LedService ledService,
            IWarehouseRepository warehouseRepository)
        {
            _commandBus = commandBus;
            _mapper = mapper;
            _taskRepository = taskRepository;
            _stockProxy = stockProxy;
            _wcsProxy = wcsProxy;
            _ledService = ledService;
            _warehouseRepository = warehouseRepository;
        }

        /// <summary>
        /// 处理程序
        /// </summary>
        public override async System.Threading.Tasks.Task Handle(CallDeleteCommand command, CancellationToken cancellationToken)
        {
            if (command.ValidationResult.IsValid)
            {
                if (await _taskRepository.HasOutput(command.Id))
                {
                    await _wcsProxy.SetOutputStatus(command.Id, 901);
                    await _taskRepository.UpdateStatus(command.Id, TaskState.CallDelete);
                }
                else
                {
                    await _commandBus.Execute(new CancelCommand { Id = command.Id });
                }

            }
            else
            {
                await _commandBus.Notify(command.ValidationResult,
                    cancellationToken: cancellationToken);
            }
        }
    }
}