using DotNetCore.CAP;
using Hotline.CallCenter.Calls;
using Hotline.Orders;
using Hotline.Share.Mq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Handlers.Order
{
    public class OrderRelateCallHandler: ICapSubscribe,ITransientDependency
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IRepository<TrCallRecord> _trCallRecordRepository;
        

        public OrderRelateCallHandler(IOrderRepository orderRepository, IRepository<TrCallRecord> trCallRecordRepository)
        {
            _orderRepository = orderRepository;
            _trCallRecordRepository = trCallRecordRepository;
        }

        /// <summary>
        /// 工单关联通话记录
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.OrderRelateCall)]
        public async Task OrderRelateCallAsync(string orderId,CancellationToken cancellationToken)
        {
            var order = await _orderRepository.GetAsync(orderId, cancellationToken);
            if (order!=null)
            {
                var callRecords = await _trCallRecordRepository.Queryable().Where(p => p.OtherAccept == order.CallId && string.IsNullOrEmpty(p.OtherAccept) == false).ToListAsync(cancellationToken);
                if (callRecords.Any())
                {
                    foreach (var callRecord in callRecords)
                    {
                        if (callRecord != null && string.IsNullOrEmpty(callRecord.ExternalId))
                        {
                            callRecord.ExternalId = orderId;
                            callRecord.CallOrderType = Share.Enums.CallCenter.ECallOrderType.Order;
                            await _trCallRecordRepository.UpdateAsync(callRecord, cancellationToken);
                        }
                    }
                }
            }
        }
    }
}
