using DotNetCore.CAP;
using Hotline.CallCenter.Calls;
using Hotline.Share.Mq;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using Quartz;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Repository;
using XingTang.Sdk;

namespace Hotline.Application.Jobs
{
    /// <summary>
    /// 兴唐评价结果
    /// </summary>
    public class XingTangCallSatisfactionSyncJob : IJob, IDisposable
    {
        private readonly IRepository<CallNative> _callRepository;
        private readonly ISqlSugarClient _db;
        private readonly IRepository<CallSatisfaction> _callSatisfactionRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<XingTangCallSatisfactionSyncJob> _logger;
        private readonly ICapPublisher _capPublisher;

        public XingTangCallSatisfactionSyncJob(IRepository<CallNative> callRepository, ISqlSugarClient db,
            IRepository<CallSatisfaction> callSatisfactionRepository, IMapper mapper, ILogger<XingTangCallSatisfactionSyncJob> logger,
            ICapPublisher capPublisher)
        {
            _callRepository = callRepository;
            _db = db;
            _callSatisfactionRepository = callSatisfactionRepository;
            _mapper = mapper;
            _logger = logger;
            _capPublisher = capPublisher;
        }

        public void Dispose()
        {
        }

        public async Task Execute(IJobExecutionContext context)
        {
            var callSatisfactions = await _db.Queryable<XingtangSatisfaction>()
                .Where(d => (d.IsSync == null || !d.IsSync) && (d.Tries == null || d.Tries <= 50))
                .OrderBy(d => d.Id)
                .Take(10)
                .ToListAsync(context.CancellationToken);

            if (!callSatisfactions.Any()) return;
            var occupyCallSatisfactions = new List<XingtangSatisfaction>();
            foreach (var callSatisfaction in callSatisfactions)
            {
                callSatisfaction.IsSync = true;
                callSatisfaction.Tries += 1;

                var rows = await _db.Updateable(callSatisfaction)
                    .ExecuteCommandWithOptLockAsync();
                if (rows > 0)
                    occupyCallSatisfactions.Add(callSatisfaction);
            }

            if (!occupyCallSatisfactions.Any()) return;
            try
            {
                var callStatisfactions = _mapper.Map<List<CallSatisfaction>>(occupyCallSatisfactions);
                foreach (var item in callSatisfactions)
                {
                    var call = _callRepository.Queryable().Where(x => x.CallNo == item.CallNo).FirstAsync();
                    if (call != null)
                    {
                        item.Id = call.Id;
                    }
                }

                await _callSatisfactionRepository.AddRangeAsync(callStatisfactions, context.CancellationToken);
                await _capPublisher.PublishAsync(EventNames.HotlineCallSatisfactionAdd, callStatisfactions,
                    cancellationToken: context.CancellationToken);
            }
            catch (Exception e)
            {
                _logger.LogError($"获取通话记录评价：{e.Message} \n {e.StackTrace}");
                foreach (var callSatisfaction in occupyCallSatisfactions)
                {
                    callSatisfaction.IsSync = false;
                }

                await _db.Updateable(occupyCallSatisfactions)
                    .UpdateColumns(d => new { d.IsSync })
                    .ExecuteCommandAsync(context.CancellationToken);
            }
        }
    }
}