using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hotline.Application.CallCenter.Calls;
using Hotline.Application.Tels;
using Hotline.Caching.Interfaces;
using Hotline.CallCenter.BlackLists;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Tels;
using Hotline.Settings;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.CallCenter;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.CallCenter;
using Microsoft.AspNetCore.Http;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Application.CallCenter
{
    public class TianRunCallApplication : DefaultCallApplication
    {
        private readonly ISessionContext _sessionContext;
        private readonly IRepository<TrCallRecord> _trCallRecordRepository;
        private readonly ITrApplication _trApplication;
        private readonly ITelApplication _telApplication;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;

        public TianRunCallApplication(
            ISessionContext sessionContext,
            IRepository<TrCallRecord> trCallRecordRepository,
            ITrApplication trApplication,
            ITelApplication telApplication,
            ISystemSettingCacheManager systemSettingCacheManager
        )
        {
            _sessionContext = sessionContext;
            _trCallRecordRepository = trCallRecordRepository;
            _trApplication = trApplication;
            _telApplication = telApplication;
            _systemSettingCacheManager = systemSettingCacheManager;
        }

        /// <summary>
        /// 新增黑名单
        /// </summary>
        public override async Task<string> AddBlackListAsync(AddBlacklistDto dto, CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 删除黑名单
        /// </summary>
        public override async Task RemoveBlackListAsync(string id, CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 查询黑名单
        /// </summary>
        public override async Task<List<Blacklist>> QueryBlackListsAsync(CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 签入
        /// </summary>
        public override async Task<TrOnDutyResponseDto> SignInAsync(SignInDto dto, CancellationToken cancellationToken) =>
            await _trApplication.OnSign(_sessionContext.RequiredUserId, dto.TelNo, (ETelModel)dto.TelModelState, cancellationToken);

        /// <summary>
        /// 签出
        /// </summary>
        public override Task SingOutAsync(CancellationToken cancellationToken) =>
            _telApplication.SignOutAsync(_sessionContext.RequiredUserId, cancellationToken);

        public override Task SingOutAsync(string telNo, CancellationToken cancellationToken) =>
            _telApplication.SignOutByTelNoAsync(telNo, cancellationToken);

        public override async Task<string> GetOrSetCallIdAsync(string callNo, CancellationToken cancellationToken)
        {
            return await Task.FromResult(callNo);
        }

        /// <summary>
        /// 查询当前用户的分机状态
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task<TrOnDutyResponseDto> GetTelStateAsync(CancellationToken cancellationToken) =>
            _trApplication.TelState(_sessionContext.RequiredUserId, cancellationToken);


        public override async Task<TrCallRecord?> GetTianrunCallAsync(string callId, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(callId)) return null;
            var callRecord = await _trCallRecordRepository.GetAsync(
                x => x.OtherAccept == callId && string.IsNullOrEmpty(x.OtherAccept) == false, cancellationToken);
            return callRecord;
        }

        /// <summary>
        /// 根据转写ID获取通话信息
        /// </summary>
        /// <returns></returns>
        public override async Task<TrCallRecord?> GetTianrunCallTransliterationAsync(string transliterationId, CancellationToken cancellationToken)
        {
	        if (string.IsNullOrEmpty(transliterationId)) return null;
	        var callRecord = await _trCallRecordRepository.GetAsync(
		        x => x.TransliterationId == transliterationId && string.IsNullOrEmpty(x.OtherAccept) == false, cancellationToken);
	        return callRecord;
        }

		/// <summary>
		/// 修改转写状态
		/// </summary>
		/// <returns></returns>
		public override async Task EditTransliterationStateAsync(string callId, ECallTransliterationState state , string transliterationId, CancellationToken cancellationToken)
        {
			await _trCallRecordRepository.Updateable().SetColumns(o => new TrCallRecord { TransliterationState  = state,TransliterationId = transliterationId })
				.Where(o => o.Id == callId).ExecuteCommandAsync(cancellationToken);
		}

		/// <summary>
		/// 关联通话记录与order（添润）
		/// </summary>
		public override async Task RelateTianrunCallWithOrderAsync(string callId, string orderId, CancellationToken cancellationToken)
        {
            var callRecord = await _trCallRecordRepository.GetAsync(
                p => p.OtherAccept == callId && string.IsNullOrEmpty(p.OtherAccept) == false, cancellationToken);
            if (callRecord != null && string.IsNullOrEmpty(callRecord.ExternalId))
            {
                callRecord.ExternalId = orderId;
                callRecord.CallOrderType = Share.Enums.CallCenter.ECallOrderType.Order;
                await _trCallRecordRepository.UpdateAsync(callRecord, cancellationToken);
            }
        }

        /// <summary>
        /// 查询通话记录
        /// </summary>
        public override async Task<List<TrCallRecord>> QueryTianrunCallsAsync(
            string? phone = null,
            ECallDirection? direction = null,
            DateTime? callStartTimeStart = null,
            DateTime? callStartTimeEnd = null,
            CancellationToken cancellationToken = default)
        {
            return await _trCallRecordRepository.Queryable()
                .WhereIF(!string.IsNullOrEmpty(phone), d => d.CPN == phone || d.CDPN == phone)
                .WhereIF(direction != null, d => d.CallDirection == direction)
                .WhereIF(callStartTimeStart != null, d => d.BeginIvrTime >= callStartTimeStart)
                .WhereIF(callStartTimeEnd != null, d => d.BeginIvrTime <= callStartTimeEnd)
                .OrderBy(x => x.CreatedTime)
                .ToListAsync(cancellationToken);
        }

        /// <summary>
        /// 查询分机操作选项
        /// </summary>
        /// <returns></returns>
        public override List<Kv> GetTelOperationOptions()
        {
            throw new NotImplementedException();
        }
    }
}