using DocumentFormat.OpenXml.Spreadsheet;
using DotNetCore.CAP;
using Hotline.Application.Systems;
using Hotline.Caching.Interfaces;
using Hotline.CallCenter.BlackLists;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Tels;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.CallCenter;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Settings;
using Hotline.Share.Attributes;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.CallCenter;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Enums.Order;
using Hotline.Share.Mq;
using Hotline.Share.Tools;
using Hotline.Users;
using JiebaNet.Segmenter.Common;
using Mapster;
using MapsterMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Cache;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Application.CallCenter;

public abstract class DefaultCallApplication : ICallApplication
{
    private readonly IRepository<Tel> _telRepository;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;
    private readonly ICapPublisher _capPublisher;
    private readonly IRepository<TelGroup> _telGroupRepository;
    private readonly IWorkRepository _workRepository;
    private readonly ITelRestRepository _telRestRepository;
    private readonly IRepository<CallNative> _callNativeRepository;
    private readonly IRepository<TelOperation> _telOperationRepository;
    private readonly IRepository<CallidRelation> _callIdRelationRepository;
    private readonly ITypedCache<Work> _cacheWork;
    private readonly IUserCacheManager _userCacheManager;
    private readonly ISessionContext _sessionContext;
    private readonly IMapper _mapper;
    private readonly ILogger<DefaultCallApplication> _logger;
    private readonly ICallDomainService _callDomainService;
    private readonly IOrderVisitDomainService _orderVisitDomainService;
    private readonly IOrderRepository _orderRepository;
    private readonly IOrderVisitRepository _orderVisitRepository;
    private readonly ISystemLogRepository _systemLogRepository;
    private readonly IRepository<TelActionRecord> _telActionRecordRepository;

    public DefaultCallApplication(
        IRepository<Tel> telRepository,
        IRepository<TelGroup> telGroupRepository,
        IWorkRepository workRepository,
        ITelRestRepository telRestRepository,
        IRepository<CallNative> callNativeRepository,
        IRepository<TelOperation> telOperationRepository,
        IRepository<CallidRelation> callIdRelationRepository,
        ITypedCache<Work> cacheWork,
        IUserCacheManager userCacheManager,
        ISessionContext sessionContext,
        IMapper mapper,
        ILogger<DefaultCallApplication> logger,
        IOrderVisitDomainService orderVisitDomainService,
        ICallDomainService callDomainService,
        IOrderVisitRepository orderVisitRepository,
        ISystemSettingCacheManager systemSettingCacheManager,
        ICapPublisher capPublisher,
        IOrderRepository orderRepository,
        ISystemLogRepository systemLogRepository,
        IRepository<TelActionRecord> telActionRecordRepository)
    {
        _telRepository = telRepository;
        _telGroupRepository = telGroupRepository;
        _workRepository = workRepository;
        _telRestRepository = telRestRepository;
        _callNativeRepository = callNativeRepository;
        _telOperationRepository = telOperationRepository;
        _callIdRelationRepository = callIdRelationRepository;
        _cacheWork = cacheWork;
        _userCacheManager = userCacheManager;
        _sessionContext = sessionContext;
        _mapper = mapper;
        _logger = logger;
        _orderVisitDomainService = orderVisitDomainService;
        _callDomainService = callDomainService;
        _orderVisitRepository = orderVisitRepository;
        _systemSettingCacheManager = systemSettingCacheManager;
        _capPublisher = capPublisher;
        _orderRepository = orderRepository;
        _systemLogRepository = systemLogRepository;
        _telActionRecordRepository = telActionRecordRepository;
    }

    public DefaultCallApplication()
    {
    }

    /// <summary>
    /// 查询分机组和分机
    /// </summary>
    /// <returns></returns>
    public virtual async Task<IReadOnlyList<TelGroupDto>> QueryGroupTel(CancellationToken cancellationToken)
    {
        var data = await _telGroupRepository.Queryable().Includes(d => d.Tels)
          // .Select<TelGroupDto>()
          .ToListAsync(cancellationToken);
        return _mapper.Map<IReadOnlyList<TelGroupDto>>(data);
    }

    /// <summary>
    /// 查询分机
    /// </summary>
    public virtual async Task<(int, IList<TelDto>)> QueryTelsAsync(QueryTelsInDto dto, CancellationToken cancellationToken)
    {
        var (total, items) = await _telRepository.Queryable()
            .Includes(x => x.Groups)
            .WhereIF(dto.No.NotNullOrEmpty(), x => x.No == dto.No.Trim())
            .Select<TelDto>()
            .ToPagedListAsync(dto.PageIndex, dto.PageSize, cancellationToken);
        return (total, items);
    }

    /// <summary>
    /// 查询分机组
    /// </summary>
    public virtual async Task<IReadOnlyList<TelGroupDto>> QueryTelGroupsAsync(CancellationToken cancellationToken)
    {
        return await _telGroupRepository.Queryable()
            .Select<TelGroupDto>()
            .ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 记录分机结束动作时间
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task EndActionAsync(EndActionInDto dto)
    {
        var telOperation = await _telOperationRepository.Queryable()
            .Where(m => m.StaffNo == dto.StaffNo && m.TelNo == dto.TelNo && !m.EndTime.HasValue)
            .WhereIF(dto.Status != -1, m => m.OperateState != dto.Status)
            .WhereIF(dto.Status == -1, m => m.OperateStateText == "未知")
            .OrderByDescending(m => m.CreationTime)
            .FirstAsync();
        if (telOperation == null) return;
        telOperation.EndAction();
        await _telOperationRepository.UpdateAsync(telOperation);
        _logger.LogInformation($"分机动作结束成功: 入参 [{dto.ToJson()}] 受影响 TelOperationId: {telOperation.Id}");
    }

    /// <summary>
    /// 新增黑名单
    /// </summary>
    public abstract Task<string> AddBlackListAsync(AddBlacklistDto dto, CancellationToken cancellationToken);

    /// <summary>
    /// 删除黑名单
    /// </summary>
    public abstract Task RemoveBlackListAsync(string id, CancellationToken cancellationToken);

    /// <summary>
    /// 查询黑名单
    /// </summary>
    public abstract Task<List<Blacklist>> QueryBlackListsAsync(CancellationToken cancellationToken);

    /// <summary>
    /// 签入
    /// </summary>
    public virtual async Task<TrOnDutyResponseDto> SignInAsync(SignInDto dto, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(dto.TelNo))
            throw UserFriendlyException.SameMessage("无效分机号");
        var work = _userCacheManager.GetWorkByUserNoExp(_sessionContext.RequiredUserId);
        if (work is not null)
        {
            //if (work.TelNo != dto.TelNo)
            //{
            //    throw UserFriendlyException.SameMessage("当前用户已签入其他分机");
            //}
            throw UserFriendlyException.SameMessage("当前用户已签入");
        }

        var telWork = _userCacheManager.GetWorkByTelNoExp(dto.TelNo);
        if (telWork is not null)
        {
            throw UserFriendlyException.SameMessage("当前分机已被占用");
        }

        work = new Work(_sessionContext.RequiredUserId, _sessionContext.UserName,
            dto.TelNo, dto.TelNo, null, null,
            dto.GroupId, _sessionContext.StaffNo, null);
        await _workRepository.AddAsync(work, cancellationToken);

        try
        {
            //签入是否处理是否有小休
            var signInCheckRest = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.SignInCheckRest).SettingValue[0]);
            if (signInCheckRest)
            {
                //如果有未结束的小休，先结束
                var telRest = await _telRestRepository.GetAsync(x => x.TelNo == work.TelNo && !x.EndTime.HasValue, cancellationToken);
                if (telRest != null)
                {
                    telRest.EndRest();
                    await _telRestRepository.UpdateAsync(telRest, cancellationToken);
                }

                //如果有未结束的话机动作先结束话机动作
                var telAction = await _telActionRecordRepository.GetAsync(x => x.TelNo == work.TelNo && x.ActionType == EActionType.TelRest && !x.EndTime.HasValue, cancellationToken);
                if (telAction != null)
                {
                    telAction.EndAction();
                    await _telActionRecordRepository.UpdateAsync(telAction);
                }
            }

            //记录签入日志
            var actionRecord = new TelActionRecord(work.UserId, work.UserName, work.TelNo, work.QueueId, EActionType.SignIn);

            await _telActionRecordRepository.AddAsync(actionRecord, cancellationToken);
        }
        catch (Exception)
        {

        }

        return new TrOnDutyResponseDto
        {
            TelNo = dto.TelNo,
            QueueId = dto.GroupId,
            StartTime = work.StartTime,
        };
    }

    /// <summary>
    /// 签出
    /// </summary>
    public virtual async Task SingOutAsync(CancellationToken cancellationToken)
    {
        var work = _userCacheManager.GetWorkByUserNoExp(_sessionContext.RequiredUserId);
        if (work is null) return;

        var telRest =
            await _telRestRepository.GetAsync(x => x.TelNo == work.TelNo && !x.EndTime.HasValue, cancellationToken);
        if (telRest is not null)
        {
            telRest.EndRest();
            await _telRestRepository.UpdateAsync(telRest, cancellationToken);
        }

        work.OffDuty();
        await _workRepository.UpdateAsync(work, cancellationToken);
        await _cacheWork.RemoveAsync(work.GetKey(KeyMode.UserId), cancellationToken);
        await _cacheWork.RemoveAsync(work.GetKey(KeyMode.TelNo), cancellationToken);

        try
        {
            var list = await _telActionRecordRepository.Queryable().Where(x => x.TelNo == work.TelNo && !x.EndTime.HasValue).ToListAsync();
            foreach (var item in list)
            {
                item.EndAction();
                await _telActionRecordRepository.UpdateAsync(item);
            }
        }
        catch (Exception)
        {
        }
    }

    /// <summary>
    /// 签出
    /// </summary>
    public virtual async Task SingOutAsync(string telNo, CancellationToken cancellationToken)
    {
        var work = _userCacheManager.GetWorkByTelNoExp(telNo);
        if (work is null) return;

        var telRest =
            await _telRestRepository.GetAsync(x => x.TelNo == work.TelNo && !x.EndTime.HasValue, cancellationToken);
        if (telRest is not null)
        {
            telRest.EndRest();
            await _telRestRepository.UpdateAsync(telRest, cancellationToken);
        }

        work.OffDuty();
        await _workRepository.UpdateAsync(work, cancellationToken);
        await _cacheWork.RemoveAsync(work.GetKey(KeyMode.UserId), cancellationToken);
        await _cacheWork.RemoveAsync(work.GetKey(KeyMode.TelNo), cancellationToken);

        var list = await _telActionRecordRepository.Queryable().Where(x => x.TelNo == work.TelNo && !x.EndTime.HasValue).ToListAsync();
        foreach (var item in list)
        {
            item.EndAction();
            await _telActionRecordRepository.UpdateAsync(item);
        }
    }

    /// <summary>
    /// 查询当前用户的分机状态
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public virtual async Task<TrOnDutyResponseDto> GetTelStateAsync(CancellationToken cancellationToken)
    {
        var work = _userCacheManager.GetWorkByUserNoExp(_sessionContext.RequiredUserId);
        if (work is null) return null;
        return await Task.FromResult(new TrOnDutyResponseDto
        {
            TelNo = work.TelNo,
            QueueId = work.QueueId,
            StartTime = work.StartTime,
            StaffNo = work.StaffNo
        });
    }

    /// <summary>
    /// 定量查询通话记录
    /// </summary>
    public virtual ISugarQueryable<CallNativeDto> QueryCallsFixedAsync(QueryCallsFixedDto dto, CancellationToken cancellationToken)
    {
        if (dto.SortField.NotNullOrEmpty())
            dto.SortField = dto.SortField.ToLower();
        var query = _callNativeRepository.Queryable(includeDeleted: true)
            .LeftJoin<Order>((d, o) => d.Id == o.CallId)
            .LeftJoin<OrderVisit>((d, o, v) => d.Id == v.CallId)
            .Where((d, o, v) => d.IsDeleted == false)
            // .WhereIF(string.IsNullOrEmpty(dto.ToNo), (d, o, v) => d.GroupId != "0")
            .WhereIF(!string.IsNullOrEmpty(dto.OrderNo), (d, o, v) => o.No == dto.OrderNo)
            .WhereIF(!string.IsNullOrEmpty(dto.FromNo), d => d.FromNo.Contains(dto.FromNo!))
            .WhereIF(!string.IsNullOrEmpty(dto.ToNo), d => d.ToNo.Contains(dto.ToNo!))
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), d => d.UserName == dto.UserName)
            .WhereIF(!string.IsNullOrEmpty(dto.TelNo), d => d.TelNo == dto.TelNo)
            .WhereIF(!string.IsNullOrEmpty(dto.CallNo), d => d.CallNo.Contains(dto.CallNo))
            .WhereIF(dto.EndBy != null, d => d.EndBy == dto.EndBy)
            .WhereIF(dto.CallStartTimeStart != null, d => d.BeginIvrTime >= dto.CallStartTimeStart)
            .WhereIF(dto.CallStartTimeEnd != null, d => d.BeginIvrTime <= dto.CallStartTimeEnd)
            .WhereIF(dto.IsConnected != null, d => d.AnsweredTime != null)
            .WhereIF(dto.Direction != null, d => d.Direction == dto.Direction)
            .WhereIF(dto.WaitDurationStart != null && dto.WaitDurationStart > 0, d => d.WaitDuration >= dto.WaitDurationStart)
            .WhereIF(dto.WaitDurationEnd != null && dto.WaitDurationEnd > 0, d => d.WaitDuration <= dto.WaitDurationEnd)
            .WhereIF(dto.IsMissOrder != null && dto.IsMissOrder.Value == true, (d, o, v) => string.IsNullOrEmpty(o.Id) == true)
            .WhereIF(dto.IsMissOrder != null && dto.IsMissOrder.Value == false, (d, o, v) => string.IsNullOrEmpty(o.Id) == false)
            .OrderByIF(dto.SortField.IsNullOrEmpty(), (d, o, v) => d.BeginIvrTime, OrderByType.Desc)
            .OrderByIF(dto is { SortField: "waitduration", SortRule: 0 }, (d, o, v) => d.WaitDuration, OrderByType.Asc)
            .OrderByIF(dto is { SortField: "waitduration", SortRule: 1 }, (d, o, v) => d.WaitDuration, OrderByType.Desc);

        query = query.WhereIF(dto.Type == 3, (d, o, v) => d.AnsweredTime == null);
        query = query.WhereIF(dto.Type == 1, (d, o, v) => d.Direction == ECallDirection.In && d.AnsweredTime != null);
        query = query.WhereIF(dto.Type == 2, (d, o, v) => d.Direction == ECallDirection.Out && d.AnsweredTime != null);

        query = query.WhereIF(dto.Type == 4, (d, o, v) => d.CallIdentity == ECallIdentity.White);
        query = query.WhereIF(dto.Type == 5, (d, o, v) => d.CallIdentity == ECallIdentity.Black);

        query = query.WhereIF(dto.Type != 3 && !string.IsNullOrEmpty(dto.StaffNo), d => d.StaffNo == dto.StaffNo);

        if (dto.Type == 2)
        {
            var d = query.Select((d, o, v) => new CallNativeDto
            {
                OrderId = SqlFunc.IsNull(v.OrderId, v.OrderId),
                OrderNo = SqlFunc.IsNull(v.Order.No, o.No),
                Title = SqlFunc.IsNull(v.Order.Title, o.Title),
                CallState = d.CallState,
                IsVisit = !SqlFunc.IsNullOrEmpty(v.Id),
                IsOrder = !SqlFunc.IsNullOrEmpty(o.Id),
            }, true);
#if DEBUG
            var sql = d.ToSqlString();
#endif
            return d;
        }
        if (dto.Type == 3 || dto.Type == 5)
        {
            return query.Select((d, o, v) => new CallNativeDto
            {
                OrderId = o.Id,
                OrderNo = o.No,
                CallState = d.CallState,
                Title = o.Title,
                IsVisit = !SqlFunc.IsNullOrEmpty(v.Id),
                IsOrder = !SqlFunc.IsNullOrEmpty(o.Id),
            }, true)
                .WhereIF(!string.IsNullOrEmpty(dto.StaffNo), d => d.StaffNo == dto.StaffNo);
        }
        return query.Select((d, o, v) => new CallNativeDto
        {
            OrderId = o.Id,
            OrderNo = o.No,
            CallState = d.CallState,
            Title = o.Title,
            IsVisit = !SqlFunc.IsNullOrEmpty(v.Id),
            IsOrder = !SqlFunc.IsNullOrEmpty(o.Id),
        }, true);
    }

    /// <summary>
    /// 查询分机操作记录（定量）
    /// </summary>
    [ExportExcel("分机操作记录")]
    public virtual ISugarQueryable<TelOperation> QueryTelOperationsAsync(QueryTelOperationsFixedDto dto)
    {
        return _telOperationRepository.Queryable()
            .Where(m => m.OperateStateText != "未知")
            .WhereIF(!string.IsNullOrEmpty(dto.UserName), d => d.UserName.Contains(dto.UserName))
            .WhereIF(!string.IsNullOrEmpty(dto.StaffNo), d => d.StaffNo.Contains(dto.StaffNo))
            .WhereIF(!string.IsNullOrEmpty(dto.GroupId), d => d.GroupId == dto.GroupId)
            .WhereIF(dto.TelNo != null, d => d.TelNo.Contains(dto.TelNo))
            .WhereIF(dto.OperateState != null, d => d.OperateState == dto.OperateState)
            .Where(x => x.OperateTime >= dto.StartTime && x.OperateTime <= dto.EndTime)
            .OrderByDescending(d => d.Id);
    }

    /// <summary>
    /// 依据通话记录编号获取映射后的callId
    /// </summary>
    public virtual async Task<string?> GetOrSetCallIdAsync(string? callNo, CancellationToken cancellationToken)
    {
        if (callNo == null) return null;
        var callOrder = await _callIdRelationRepository.GetAsync(callNo, cancellationToken);
        if (callOrder == null)
        {
            callOrder = new CallidRelation
            {
                Id = callNo,
                CallId = Ulid.NewUlid().ToString(),
            };
            try
            {
                await _callIdRelationRepository.AddAsync(callOrder, cancellationToken);
            }
            catch (Exception e)
            {
                _logger.LogError($"写入callidRelation失败：{e.Message}");
                return await GetOrSetCallIdAsync(callNo, cancellationToken);
            }
        }

        return callOrder.CallId;
    }

    public async Task<CallidRelation> GetRelationAsync(string callNo, CancellationToken cancellation)
    {
        return await _callIdRelationRepository.GetAsync(callNo, cancellation);
    }

    public async Task AddRelationAsync(CallidRelation relation, CancellationToken cancellation)
    {
        await _callIdRelationRepository.AddAsync(relation, cancellation);
    }

    /// <summary>
    /// 乐观并发更新映射关系
    /// </summary>
    public virtual async Task<int> UpdateRelationOptLockAsync(CallidRelation relation, CancellationToken cancellationToken)
    {
        return await _callIdRelationRepository.Updateable(relation).ExecuteCommandWithOptLockAsync();
    }

    /// <summary>
    /// 查询通话记录
    /// </summary>
    public virtual async Task<CallNative> GetCallAsync(string callId, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(callId)) return null;
        if (callId.StartsWith("2024"))
            return await _callNativeRepository.GetAsync(m => m.CallNo == callId && m.IsDeleted == false, cancellationToken);
        return await _callNativeRepository.GetAsync(m => m.Id == callId && m.IsDeleted == false, cancellationToken);
    }

    /// <summary>
    /// 查询通话记录
    /// 因为自贡的系统中有回访和通话记录未关联的异常数据, 使用此方法查询通话记录
    /// </summary>
    public virtual async Task<CallNative> GetCallByTimeAndToNoAsync(string toNo, DateTime time, CancellationToken cancellationToken)
    {
        var beginTime = time.AddMinutes(-5);
        var items = await _callNativeRepository.Queryable()
            .Where(m => m.BeginIvrTime >= beginTime && m.BeginIvrTime <= time)
            .Where(m => m.ToNo == toNo && m.Direction == ECallDirection.Out && !string.IsNullOrEmpty(m.AudioFile) && m.IsDeleted == false)
            .OrderBy(m => m.BeginIvrTime)
            .ToListAsync(cancellationToken);
        if (items.NotNullOrEmpty())
            return items.First();
        return null;
    }

    /// <summary>
    /// 查询通话记录
    /// 因为自贡的系统中有回访和通话记录未关联的异常数据, 使用此方法查询通话记录
    /// </summary>
    public virtual async Task<CallNative> GetCallByCallNoAsync(string callNo, CancellationToken cancellationToken)
    {
        return await _callNativeRepository.Queryable()
            .Where(m => m.CallNo == callNo && !string.IsNullOrEmpty(m.AudioFile))
            .FirstAsync(cancellationToken);
    }

    /// <summary>
    /// 查询通话记录列表
    /// </summary>
    /// <param name="callId"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public virtual async Task<List<CallNative>> GetCallListAsync(string callId, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(callId)) return null;
        return await _callNativeRepository.Queryable().Where(x => x.Id == callId).ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 查询通话记录
    /// </summary>
    public virtual async Task<List<CallNative>> QueryCallsAsync(
        string? phone,
        ECallDirection? direction,
        DateTime? callStartTimeStart,
        DateTime? callStartTimeEnd,
        CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(phone))
            return new List<CallNative>();
        return await _callNativeRepository.Queryable()
            .WhereIF(direction.HasValue, d => d.Direction == direction)
            .WhereIF(callStartTimeStart != null, d => d.BeginIvrTime >= callStartTimeStart)
            .WhereIF(callStartTimeEnd != null, d => d.BeginIvrTime <= callStartTimeEnd)
            .Where(d => d.FromNo == phone || d.ToNo == phone)
            .OrderBy(d => d.CreationTime)
            .ToListAsync(cancellationToken);
    }

    /// <summary>
    /// 根据 OrderId 返回用户电话评价枚举
    /// 默认返回 默认满意
    /// </summary>
    /// <param name="orderId"></param>
    /// <returns></returns>
    public virtual async Task<EVoiceEvaluate> GetReplyVoiceOrDefaultByOrderIdAsync(string orderId)
    {
        var callNative = await _callDomainService.GetByOrderIdAsync(orderId);
        if (callNative is null || callNative.ReplyTxt.IsNullOrEmpty())
            return EVoiceEvaluate.DefaultSatisfied;

        try
        {
            var smsReply = _orderVisitDomainService.GetVisitEvaluateByReplyTxt(callNative.ReplyTxt!.Trim());
            return smsReply!.VoiceEvaluate!.Value;
        }
        catch (UserFriendlyException)
        {
            return EVoiceEvaluate.DefaultSatisfied;
        }
    }

    /// <summary>
    /// 发送延迟消息让回访去关联通话记录
    /// 如果前端入参中的CallId为空, 就根据回访Id在systemLog中查询.前端在回访界面点击"回访"按钮拨号时会在systemLog中保存回访的号码,callNo,回访Id;
    /// 通过systemLog修复前端没有传callId这种情况;
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public virtual async Task<string> PublishVisitRelevanceCallIdAsync(OrderRelevanceCallIdDto dto, CancellationToken cancellationToken)
    {
        if (dto.CallId.IsNullOrEmpty())
        {
            try
            {
                var log = await _systemLogRepository.Queryable()
                    .Where(m => m.IpUrl == dto.Id && m.Name == "回访外呼已经接通")
                    .FirstAsync(cancellationToken);
                if (log is null || log.Remark.IsNullOrEmpty()) return null;
                var callRemark = log.Remark.FromJson<CallRemarkDto>();
                dto.CallId = callRemark.CallId;
            }
            catch (Exception e)
            {
                _logger.LogError($"PublishVisitRelevanceCallIdAsync: {e.ToJson()}");
            }
        }

        var seconds = _systemSettingCacheManager.VisitCallDelaySecond;
        await _capPublisher.PublishDelayAsync(TimeSpan.FromSeconds(seconds), EventNames.VisitCallDelay, dto, cancellationToken: cancellationToken);
        return dto.CallId;
    }

    /// <summary>
    /// 处理: EventNames.VisitCallDelay 消息
    /// 保存回访详情时发送延迟消息同步通话记录
    /// 如果回访通话记录有多条, 需要关联通话时长最长的那条
    /// </summary>
    public virtual async Task OrderVisitRelevanceCallIdAsync(VisitDto dto, CancellationToken cancellationToken)
    {
        var visit = await _orderVisitRepository.GetAsync(dto.Id);
        if (visit == null) return;

        var callId = await _callNativeRepository.Queryable()
            .Where(m => m.CallNo == dto.CallId && string.IsNullOrEmpty(m.AudioFile) == false)
            .OrderByDescending(m => m.Duration)
            .Select(m => m.Id)
            .FirstAsync(cancellationToken);
        if (callId == null) return;
        visit.CallId = callId;

        await _callIdRelationRepository.Updateable()
            .SetColumns(m => m.CallId == callId)
            .Where(m => m.Id == dto.CallId)
            .ExecuteCommandAsync(cancellationToken);
        await _orderVisitRepository.UpdateAsync(visit);
    }

    #region tianrun 临时方案

    public virtual Task<TrCallRecord?> GetTianrunCallAsync(string callId, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 根据转写ID获取通话信息
    /// </summary>
    /// <returns></returns>
    public virtual async Task<TrCallRecord?> GetTianrunCallTransliterationAsync(string transliterationId, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public virtual async Task EditTransliterationStateAsync(string callId, ECallTransliterationState state, string transliterationId, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 关联通话记录与order
    /// </summary>
    public virtual async Task RelateTianrunCallWithOrderAsync(string callId, string orderId,
        CancellationToken cancellationToken)
    {
        // 延迟一段时间后去通话记录中查询有通话音频记录文件的那通电话记录关联回工单.
        var second = _systemSettingCacheManager.VisitCallDelaySecond;
        await _capPublisher.PublishDelayAsync(TimeSpan.FromSeconds(second), EventNames.OrderRelateCall, orderId, cancellationToken: cancellationToken);
    }

    /// <summary>
    /// 处理工单和通话记录关联问题
    /// </summary>
    /// <param name="orderId"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public virtual async Task<string> OrderRelateCallHandlerAsync(string orderId, CancellationToken cancellationToken)
    {
        var orderCall = await _orderRepository.Queryable()
            .LeftJoin<CallNative>((o, c) => o.CallId == c.Id)
            .Where((o, c) => o.Id == orderId)
            .Select((o, c) => new { o.CallId, c.CallNo })
            .FirstAsync(cancellationToken);
        //#if DEBUG
        //        var order = await _orderRepository.GetAsync(orderId);
        //        var oldName = _sessionContext.UserName;
        //        _sessionContext.ChangeSession("08dcfe32-c260-40b4-839a-aeca1f76244c");
        //        var newName = _sessionContext.UserName;

        //#endif
        if (orderCall is null || orderCall.CallNo.IsNullOrEmpty())
        {
            string message = $"延迟更新工单通话, 工单: {orderId} 根据 order.id left join call_native 信息为空; 消息队列无须重试";
            _logger.LogInformation(message);
            return message;
        }

        var call = await _callNativeRepository.Queryable()
            .Where(m => m.Id == orderCall.CallId)
            .FirstAsync(cancellationToken);
        // Order已经关联的通话记录是呼入的,并且有通话录音, 所以不需要再次关联
        if (call != null && call.Direction == ECallDirection.In && call.AudioFile.NotNullOrEmpty())
        {
            // 推省上
            await _capPublisher.PublishAsync(EventNames.HotlineCallConnectWithOrder, new PublishCallRecrodDto()
            {
                Order = (await _orderRepository.GetAsync(orderId, cancellationToken)).Adapt<OrderDto>(),
                TrCallRecordDto = call.Adapt<TrCallDto>()
            }, cancellationToken: cancellationToken);
            var message = "Order已经关联的通话记录是呼入的,并且有通话录音, 所以不需要再次关联.(完成推省上)";
            _systemLogRepository.Add("延迟更新工单通话", orderId, message, status: 1, ipUrl: orderCall.CallId);
            return message;
        }

        call = await _callNativeRepository.Queryable()
            .Where(m => m.CallNo == orderCall.CallNo && m.Direction == ECallDirection.In)
            .OrderByDescending(m => m.Duration)
            .FirstAsync(cancellationToken);
        if (call == null)
        {
            var message = $"延迟更新工单通话, 工单: {orderId} 根据 CallNo: {orderCall.CallNo} direction = 0 查询 call_native 信息为空; 等兴唐把数据同步过来, 队列重试;";
            throw new ArgumentNullException(message);
        }

        // 需要更新的callId 和 order.callId 相同, 不处理
        if (orderCall.CallId == call.Id)
        {
            // 推省上
            await _capPublisher.PublishAsync(EventNames.HotlineCallConnectWithOrder, new PublishCallRecrodDto()
            {
                Order = (await _orderRepository.GetAsync(orderId, cancellationToken)).Adapt<OrderDto>(),
                TrCallRecordDto = call.Adapt<TrCallDto>()
            }, cancellationToken: cancellationToken);
            return "需要更新的callId 和 order.callId 相同(完成推省上)";
        }

        await _orderRepository.Updateable()
            .SetColumns(m => m.CallId == call.Id)
            .Where(m => m.Id == orderId)
            .ExecuteCommandAsync(cancellationToken);

        await _callIdRelationRepository.Updateable()
            .SetColumns(m => m.CallId == call.Id)
            .Where(m => m.Id == orderCall.CallId)
            .ExecuteCommandAsync(cancellationToken);

        // 推省上
        await _capPublisher.PublishAsync(EventNames.HotlineCallConnectWithOrder, new PublishCallRecrodDto()
        {
            Order = (await _orderRepository.GetAsync(orderId, cancellationToken)).Adapt<OrderDto>(),
            TrCallRecordDto = call.Adapt<TrCallDto>()
        }, cancellationToken: cancellationToken);
        var msg = $"原CallId: {orderCall.CallId}, 更新CallId: {call.Id}";
        _systemLogRepository.Add("延迟更新工单通话", orderId, msg, status: 1, ipUrl: orderCall.CallId);
        return msg + "(完成推省上)";
    }

    /// <summary>
    /// 查询通话记录
    /// </summary>
    public virtual Task<List<TrCallRecord>> QueryTianrunCallsAsync(
        string? phone = null,
        ECallDirection? direction = null,
        DateTime? callStartTimeStart = null,
        DateTime? callStartTimeEnd = null,
        CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 查询分机操作选项
    /// </summary>
    /// <returns></returns>
    public abstract List<Kv> GetTelOperationOptions();


    public virtual Task<ESeatEvaluate> GetSeatDefaultByOrderIdAsync(string orderId)
    {
        throw new NotImplementedException();
    }

    public virtual Task ChangeTelModel(bool isCallOut, CancellationToken requestAborted)
    {
        throw new NotImplementedException();
    }

    #endregion
}
