using AutoMapper;
using Kean.Domain.Stock.Commands;
using Kean.Domain.Stock.Enums;
using Kean.Domain.Stock.Models;
using Kean.Domain.Stock.Repositories;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Threading;
namespace Kean.Domain.Stock.CommandHandlers
{
///
/// 设置库存状态命令处理程序
///
public sealed class SetQcStatusCommandHandler : CommandHandler
{
private readonly ICommandBus _commandBus; // 命令总线
private readonly IMapper _mapper; // 模型映射
private readonly IStockRepository _stockRepository; // 存储仓库
///
/// 依赖注入
///
public SetQcStatusCommandHandler(
ICommandBus commandBus,
IMapper mapper,
IStockRepository stockRepository)
{
_commandBus = commandBus;
_mapper = mapper;
_stockRepository = stockRepository;
}
///
/// 处理程序
///
public override async System.Threading.Tasks.Task Handle(SetQcStatusCommand command, CancellationToken cancellationToken)
{
if (command.ValidationResult.IsValid)
{
Models.Stock stock = null;
if (!string.IsNullOrEmpty(command.Barcode))
{
stock = await this._stockRepository.GetStock(command.Barcode);
}
List updateLines = new List();
foreach (var r in stock.Lines)
{
r.Enabled = command.Enable;
JObject jo = new JObject();
jo.Add("property", "Enabled");
jo.Add("message", command.Message);
r.Remark = jo;
updateLines.Add(r);
}
var updateCommand = _mapper.Map(stock);
updateCommand.Transaction = command.Enable ? nameof(StockType.Thaw) : nameof(StockType.Freeze);
updateCommand.Lines = updateLines;
updateCommand.Operator = command.Operator;
updateCommand.Tag = JsonConvert.SerializeObject(new
{
Transaction = "SetQcStatus"
});
await _commandBus.Execute(updateCommand, cancellationToken);
}
else
{
await _commandBus.Notify(command.ValidationResult,
cancellationToken: cancellationToken);
}
}
}
}