using DotNetCore.CAP;
using Hotline.Ai.Quality;
using Hotline.Application.CallCenter.Calls;
using Hotline.Application.Tels;
using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Tels;
using Hotline.Orders;
using Hotline.Permissions;
using Hotline.Quality;
using Hotline.Repository.SqlSugar.CallCenter;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Settings;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Enums.Quality;
using Hotline.Users;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using SqlSugar;
using Tr.Sdk;
using Tr.Sdk.Blacklist;
using Tr.Sdk.Tels;
using XF.Domain.Authentications;
using XF.Domain.Constants;
using XF.Domain.Exceptions;
using XF.Domain.Filters;
using XF.Domain.Repository;
using XF.Utility.EnumExtensions;
using static Grpc.Core.ChannelOption;

namespace Hotline.Api.Controllers
{
    public class IPPbxController : BaseController
    {
        private readonly ITrClient _trClient;
        private readonly IMapper _mapper;
        private readonly IUserDomainService _userDomainService;
        private readonly ISessionContext _sessionContext;
        private readonly IRepository<TrCallRecord> _trCallRecordRepository;
        private readonly ITrApplication _trApplication;
        private readonly IRepository<TrCallEvaluate> _trCallEvaluate;
        private readonly ISystemDicDataCacheManager _systemDicDataCacheManager;
        private readonly ILogger<IPPbxController> _logger;
        private readonly IOrderRepository _orderRepository;
        private readonly IRepository<OrderVisit> _orderVisitRepository;
        private readonly IUserCacheManager _userCacheManager;
        private readonly ICapPublisher _capPublisher;
        private readonly ITelRestRepository _telRestRepository;
        private readonly IRepository<User> _userRepository;
        private readonly ITelApplication _telApplication;
        private readonly IRepository<Quality.Quality> _qualiteyRepository;
        private readonly IAiQualityService _aiQualityService;
        private readonly IRepository<QualityTemplate> _qualityTemplate;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
        private readonly IRepository<TelActionRecord> _telActionRecordRepository;


        public IPPbxController(ITrClient trClient, IMapper mapper, IUserDomainService userDomainService,
            ISessionContext sessionContext, IRepository<TrCallRecord> trCallRecordRepository,
            ITrApplication trApplication, IRepository<TrCallEvaluate> trCallRecord,
            ISystemDicDataCacheManager systemDicDataCacheManager, ILogger<IPPbxController> logger,
            IOrderRepository orderRepository, IRepository<OrderVisit> orderVisitRepository,
            IUserCacheManager userCacheManager, ICapPublisher capPublisher,
            ITelRestRepository telRestRepository, IRepository<User> userRepository,
            ITelApplication telApplication, IRepository<Quality.Quality> qualiteyRepository,
            IAiQualityService aiQualityService, IRepository<QualityTemplate> qualityTemplate, 
            ISystemSettingCacheManager systemSettingCacheManager,IRepository<TelActionRecord> telActionRecordRepository)
        {
            _trClient = trClient;
            _mapper = mapper;
            _userDomainService = userDomainService;
            _sessionContext = sessionContext;
            _trCallRecordRepository = trCallRecordRepository;
            _trApplication = trApplication;
            _trCallEvaluate = trCallRecord;
            _systemDicDataCacheManager = systemDicDataCacheManager;
            _logger = logger;
            _orderRepository = orderRepository;
            _orderVisitRepository = orderVisitRepository;
            _userCacheManager = userCacheManager;
            _capPublisher = capPublisher;
            _telRestRepository = telRestRepository;
            _userRepository = userRepository;
            _telApplication = telApplication;
            _qualiteyRepository = qualiteyRepository;
            _aiQualityService = aiQualityService;
            _qualityTemplate = qualityTemplate;
            _systemSettingCacheManager = systemSettingCacheManager;
            _telActionRecordRepository = telActionRecordRepository;
        }

        #region 添添呼

        #region 分机
        /// <summary>
        /// 查询所有分机
        /// </summary>
        /// <returns></returns>
        [HttpGet("query-tels")]
        public async Task<List<TrTelDto>> TrQueryTels()
        {
            var tels = await _trClient.QueryTelsAsync(new QueryTelRequest() { }, HttpContext.RequestAborted);
            var returnlist = _mapper.Map<List<TrTelDto>>(tels);
            string callOutQueueId = _systemSettingCacheManager.GetSetting(SettingConstants.CallOutQueueId).SettingValue[0];
            returnlist.ForEach(x =>
            {
                x.CallOutQueue = callOutQueueId;
            });

            return returnlist;
        }

        /// <summary>
        /// 查询所有分机状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("query-telstate")]
        [AllowAnonymous]
        public async Task<IReadOnlyList<TrTelStateDto>> TrQueryTelState([FromQuery] string? state)
        {
            var tels = await _trClient.QueryTelStateAsync(new QueryTelStateRequest() { State = state }, HttpContext.RequestAborted);
            var workList = _userCacheManager.GetWorks();
            var query = from tel in tels.AgentList
                        join works in workList on tel.TelNo equals works.TelNo into workD
                        from work in workD.DefaultIfEmpty()
                        select new TrTelStateDto
                        {
                            Id = tel.Id,
                            TelNo =tel.TelNo,
                            ChannelUUid =tel.ChannelUUid,
                            TelName =tel.TelName,
                            Type = tel.Type,
                            Weight =tel.Weight,
                            Queue = tel.Queue,
                            State = tel.State,
                            OldState = tel.OldState,
                            Device = tel.Device,
                            SipIp = tel.SipIp,
                            PrivateData = tel.PrivateData,
                            SipState = tel.SipState,
                            CreatedAt = tel.CreatedAt,
                            UpdatedAt = tel.UpdatedAt,
                            CallDirection = tel.CallDirection,
                            OtherNumber = tel.OtherNumber,
                            GateWay = tel.GateWay,
                            AnsweredAt = tel.AnsweredAt,
                            WorkUserId = (work != null) ? work.UserId: "",
                            WorkUserName = (work != null) ? work.UserName: "",
                        };
            var list = query.OrderBy(x=>x.TelNo).OrderByDescending(x=>x.CreatedAt).ToList();
            return list;// _mapper.Map<IReadOnlyList<TrTelStateDto>>(tels.AgentList);
        }


        #endregion

        #region 黑白名单

        /// <summary>
        /// 新增黑白名单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [Permission(EPermission.AddBlackList)]
        [HttpPost("add-blacklist")]
        public async Task AddBlacklist([FromBody] TrAddBlacklistDto dto)
        {
            await _trClient.AddBlacklistAsync(new AddBlacklistRequest() { Phone = dto.Phone, SpecialFlag = dto.SpecialFlag }, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 删除黑白名单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [Permission(EPermission.RemoveBlacklist)]
        [HttpPost("remove-blacklist")]
        public async Task DelBlacklist([FromBody] TrDelBlacklistDto dto)
        {
            await _trClient.DelBlacklistAsync(new DelBlacklistRequest() { Phone = dto.Phone, SpecialFlag = dto.SpecialFlag }, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 查询黑白名单
        /// </summary>
        /// <returns></returns>
        [Permission(EPermission.QueryPagedBlack)]
        [HttpGet("query-blacklist")]
        public async Task<IReadOnlyList<TrQueryBlacklistResponseDto>> QueryBlacklist([FromQuery] TrQueryBlacklistDto dto)
        {
            var blacklist = await _trClient.QueryBlacklistAsync(new QueryBlacklistRequest() { Phone = dto.Phone, SpecialFlag = dto.SpecialFlag }, HttpContext.RequestAborted);
            return _mapper.Map<IReadOnlyList<TrQueryBlacklistResponseDto>>(blacklist);
        }

        #endregion

        #region 签入后调用

        /// <summary>
        /// 上班
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("on-duty")]
        public async Task<TrOnDutyResponseDto> OnDuty([FromBody] TrOnDutyDto dto)
        {
            //return await _userDomainService.TrOnDutyAsync(_sessionContext.RequiredUserId,dto.TelNo, HttpContext.RequestAborted);
            return await _trApplication.OnSign(_sessionContext.RequiredUserId, dto.TelNo,(ETelModel)dto.TelModelState, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 下班
        /// </summary>
        /// <returns></returns>
        [HttpPost("off-duty")]
        public async Task OffDuty()
        {
            //await _userDomainService.TrOffDutyAsync(_sessionContext.RequiredUserId, HttpContext.RequestAborted);
            await _telApplication.SignOutAsync(_sessionContext.RequiredUserId, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 查询当前用户的分机状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("tel-state")]
        public async Task<TrOnDutyResponseDto> TelState()
        {
            return await _trApplication.TelState(_sessionContext.RequiredUserId,HttpContext.RequestAborted);
        }


        /// <summary>
        /// 切换状态
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isCallOut"></param>
        /// <returns></returns>
        [HttpPost("change-telmodel")]
        public async Task ChangeTelModel([FromBody] ChangeTelModelDto dto)
        {
            await _trApplication.ChangeTelModel(_sessionContext.RequiredUserId, dto.isCallOut,HttpContext.RequestAborted);
        }



        /// <summary>
        /// 下班-管理手动操作
        /// </summary>
        /// <param name="telNo"></param>
        /// <returns></returns>
        [HttpGet("off-duty-manage")]
        public async Task OffDuty([FromQuery]string telNo)
        {
           await _telApplication.SignOutByTelNoAsync(telNo, HttpContext.RequestAborted);
        }

        //提供关闭浏览器事件触发调用
        [HttpPost("off-duty-no-auth")]
        [AllowAnonymous]
        public async Task OffDutyWithNoAuthorize([FromQuery] string userId)
        {
            if (string.IsNullOrEmpty(userId))
                throw new UserFriendlyException("无效用户编号");
            await _telApplication.SignOutByTelNoAsync(userId, HttpContext.RequestAborted);
        }

        #endregion

        #region 添添呼小休
        /// <summary>
        /// 小休页面基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("rest/basedata")]
        public async Task<object> RestBasePaegData()
        {
            var rsp = new
            {
                RestReason = _systemDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.RestReason)
            };

            return rsp;
        }

        /// <summary>
        /// 小休
        /// </summary>
        /// <returns></returns>
        [HttpPost("rest")]
        public async Task Rest([FromBody] TrRestDto dto)
        {
            var work = _userCacheManager.GetWorkByUser(_sessionContext.RequiredUserId);
            if (work == null)
                throw UserFriendlyException.SameMessage("分机未签入，不能休息");

            var isResting = await _telRestRepository.IsRestingAsync(work.TelNo, HttpContext.RequestAborted);
            if (isResting)
                throw UserFriendlyException.SameMessage("当前坐席正在休息");

            var user = await _userRepository.GetAsync(work.UserId, HttpContext.RequestAborted);
            var telRest = new TelRest(work.TelNo, work.TelNo, work.UserId, work.UserName, dto.Reason, false, user.StaffNo);
            await _telRestRepository.AddAsync(telRest, HttpContext.RequestAborted);
            var telAction = new TelActionRecord(work.UserId, work.UserName, work.TelNo, work.QueueId, EActionType.TelRest);
            await _telActionRecordRepository.AddAsync(telAction, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 取消小休
        /// </summary>
        /// <returns></returns>
        [HttpPost("unrest")]
        public async Task UnRest()
        {
            var work = _userCacheManager.GetWorkByUser(_sessionContext.RequiredUserId);
            if (work is null)
                throw UserFriendlyException.SameMessage("分机未签入，不能操作");

            var telRest = await _telRestRepository.GetAsync(x => x.TelNo == work.TelNo && !x.EndTime.HasValue, HttpContext.RequestAborted);
            if (telRest is null)
                throw UserFriendlyException.SameMessage("未查询到分机休息信息");
            telRest.EndRest();
            await _telRestRepository.UpdateAsync(telRest, HttpContext.RequestAborted);

            var telAction = await _telActionRecordRepository.GetAsync(x => x.TelNo == work.TelNo && x.ActionType == EActionType.TelRest && !x.EndTime.HasValue, HttpContext.RequestAborted);
            if (telAction!=null)
            {
                telAction.EndAction();
                await _telActionRecordRepository.UpdateAsync(telAction);
            }
        }

        #endregion

        #region 添添呼话后整理

        /// <summary>
        /// 分机动作开始
        /// </summary>
        /// <returns></returns>
        [HttpGet("callennd-arrange-begin")]
        public async Task CallEndArrangeBegin(int actionType)
        {
            var work = _userCacheManager.GetWorkByUser(_sessionContext.RequiredUserId);

            if (work is null)
                throw UserFriendlyException.SameMessage("分机未签入，不能操作");

            //判断如果已经存在未结束的该动作就不新增
            var ishas = await _telActionRecordRepository.AnyAsync(x => x.TelNo == work.TelNo && x.ActionType == (EActionType)actionType && !x.EndTime.HasValue, HttpContext.RequestAborted);
            if (!ishas)
            {
                var telAction = new TelActionRecord(work.UserId, work.UserName, work.TelNo, work.QueueId, (EActionType)actionType);
                await _telActionRecordRepository.AddAsync(telAction, HttpContext.RequestAborted);
            }
        }

        /// <summary>
        /// 分机动作结束
        /// </summary>
        /// <returns></returns>
        [HttpGet("callend-arrange-end")]
        public async Task CallEndArrangeEnd(int actionType)
        {
            var work = _userCacheManager.GetWorkByUser(_sessionContext.RequiredUserId);
            if (work is null)
                throw UserFriendlyException.SameMessage("分机未签入，不能操作");

            var telAction = await _telActionRecordRepository.GetAsync(x => x.TelNo == work.TelNo && x.ActionType == (EActionType)actionType && !x.EndTime.HasValue, HttpContext.RequestAborted);
            if (telAction != null)
            {
                telAction.EndAction();
                await _telActionRecordRepository.UpdateAsync(telAction);
            }
        }


        #endregion


        #region 通话记录（对外）
        /// <summary>
        /// 接收通话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("receivecallrecord")]
        public async Task<OpenResponse> ReceiveCallRecord([FromBody] ReceiveCallRecordDto dto)
        {
            _logger.LogInformation($"收到通话记录结果回传：{JsonConvert.SerializeObject(dto)}");

            var model = _mapper.Map<TrCallRecord>(dto);
            model.Duration = 0;
            model.RingTimes = 0;
            model.QueueTims = 0;
            model.OnState = Share.Enums.CallCenter.EOnState.NoOn;
            
            //计算通话时长
            if (model.AnsweredTime != null)
            {
                model.OnState = Share.Enums.CallCenter.EOnState.On; //是否接通

                TimeSpan tsend = new TimeSpan(model.OverTime.Ticks);
                TimeSpan tsbegin = new TimeSpan(model.AnsweredTime.Value.Ticks);
                model.Duration = Convert.ToInt32(tsend.Subtract(tsbegin).TotalSeconds);
            }
            //计算振铃时长
            if (model.BeginRingTime != null)
            {
                TimeSpan tsbegin = new TimeSpan(model.BeginRingTime.Value.Ticks);
                if (model.EndRingTimg != null)
                {
                    TimeSpan tsend = new TimeSpan(model.EndRingTimg.Value.Ticks);
                    model.RingTimes = Convert.ToInt32(tsend.Subtract(tsbegin).TotalSeconds);
                }
                else
                {
                    TimeSpan tsend = new TimeSpan(model.OverTime.Ticks);
                    model.RingTimes = Convert.ToInt32(tsend.Subtract(tsbegin).TotalSeconds);
                }
            }
            //计算队列时长
            if (model.BeginQueueTime != null && model.EndQueueTime != null)
            {
                TimeSpan tsend = new TimeSpan(model.EndQueueTime.Value.Ticks);
                TimeSpan tsbegin = new TimeSpan(model.BeginQueueTime.Value.Ticks);
                model.QueueTims = Convert.ToInt32(tsend.Subtract(tsbegin).TotalSeconds);
            }
            //获取分机号
            if (model.CallDirection == ECallDirection.In)
            {
                model.TelNo = model.CDPN;
            }
            else
            {
                model.TelNo = model.CPN;
            }
            //判断是否是内部通话（目前分机都为4位）
            if (model.CPN.Length==4 && model.CDPN.Length ==4) //是内部通话
            {
                model.TelNo = model.CDPN;//如果是内部通话  响应分机为被叫号码
            }


            //获取关联 工单或是回访
            //var order = await _orderRepository.GetAsync(x => x.CallId == model.CallAccept, HttpContext.RequestAborted);//由CallAccept改为OtherAccept
            var order = await _orderRepository.GetAsync(x => x.CallId == model.OtherAccept && string.IsNullOrEmpty(x.CallId) == false, HttpContext.RequestAborted);
            if (order != null)
            {
                model.CallOrderType = ECallOrderType.Order;
                model.ExternalId = order.Id;
                try
                {
                    // 写入智能质检
                    var teAny = await _qualityTemplate.Queryable()
                        .LeftJoin<QualityTemplateDetail>((x, d) => x.Id == d.TemplateId)
                        .LeftJoin<QualityItem>((x, d, i) => d.ItemId == i.Id)
                        .Where((x, d, i) => i.IsIntelligent == 1)
                        .Where((x, d, i) => x.Grouping == ETemplateGrouping.Accepted).AnyAsync();
                    if (teAny)
                    {
                        var quality = await _qualiteyRepository.Queryable().Where(x => x.OrderId == order.Id && x.Source == Share.Enums.Quality.EQualitySource.Accepted).FirstAsync();
                        if (quality !=null)
                        {
							var setting = _systemSettingCacheManager.GetSetting(SettingConstants.ViteRecordPrefix);
							await _aiQualityService.CreateAiOrderQualityTask(quality, model, order, setting?.SettingValue[0], HttpContext.RequestAborted);
						}
                    }
                }
                catch{}
            }
            else
            {
                //var orderVisit = await _orderVisitRepository.GetAsync(x => x.CallId == model.CallAccept, HttpContext.RequestAborted);//由CallAccept改为OtherAccept
                var orderVisit = await _orderVisitRepository.GetAsync(x => x.CallId == model.OtherAccept && string.IsNullOrEmpty(x.CallId) == false, HttpContext.RequestAborted);
                if (orderVisit != null)
                {
                    model.CallOrderType = ECallOrderType.Visit;
                    model.ExternalId = orderVisit.Id;
                }
            }

            //获取用户
            var work = await _userCacheManager.GetWorkByTelNoLast(model.TelNo);
            if (!string.IsNullOrEmpty(model.AgentTransferNumber))
            {
                work = await _userCacheManager.GetWorkByTelNoLast(model.AgentTransferNumber);
            }
            if (work != null)
            {
                model.UserId = work.UserId;
                model.UserName = work.UserName;
                model.StaffNo = work.StaffNo;
            }
            await _trCallRecordRepository.AddAsync(model, HttpContext.RequestAborted);

            if (model.CallDirection == ECallDirection.In)
            {
                var publishCallRecordDto = new PublishCallRecrodDto() { };
                if (order != null)
                {
                    var orderDto = _mapper.Map<OrderDto>(order);
                    publishCallRecordDto.Order = orderDto;
                }
                var trCallDto = _mapper.Map<TrCallDto>(model);
                publishCallRecordDto.TrCallRecordDto = trCallDto;
                if (string.IsNullOrEmpty(model.AgentTransferNumber))
                {
                    //推省上
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineCallBye, publishCallRecordDto);
                }
            }

            return OpenResponse.Ok("success");
        }

        /// <summary>
        /// 接受通话语音评价
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("receivecallevaluate")]
        public async Task<OpenResponse> ReceiveCallEvaluate([FromBody] ReceiveCallEvaluateDto dto)
        {
            var model = _mapper.Map<TrCallEvaluate>(dto);
            await _trCallEvaluate.AddAsync(model, HttpContext.RequestAborted);
            return OpenResponse.Ok("success");
        }

        #endregion

        #region 通话记录（对内）
        /// <summary>
        /// 获取通话记录列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("calls/call-list")]
        public async Task<PagedDto<TrCallDto>> GetCallList([FromQuery] GetCallListDto dto)
        {
            var (total, items) = await _trCallRecordRepository.Queryable()
                .Includes(x => x.Order)
                .WhereIF(!string.IsNullOrEmpty(dto.CPN), x => x.CPN.Contains(dto.CPN))
                .WhereIF(!string.IsNullOrEmpty(dto.CDPN), x => x.CDPN.Contains(dto.CDPN))
                .WhereIF(!string.IsNullOrEmpty(dto.TelNo), x => x.TelNo.Contains(dto.TelNo))
                .WhereIF(!string.IsNullOrEmpty(dto.UserName), x => x.UserName.Contains(dto.UserName))
                .WhereIF(dto.CallDirection != null, x => x.CallDirection == dto.CallDirection)
                .WhereIF(dto.OnState != null, x => x.OnState == dto.OnState)
                .WhereIF(dto.EndBy != null, x => x.EndBy == dto.EndBy)

                .WhereIF(dto.BeginIvrTimeStart.HasValue, x => x.BeginIvrTime >= dto.BeginIvrTimeStart)
                .WhereIF(dto.BeginIvrTimeEnd.HasValue,x=> x.BeginIvrTime<= dto.BeginIvrTimeEnd)

                .WhereIF(dto.EndIvrTimeStart.HasValue, x => x.EndIvrTime >= dto.EndIvrTimeStart)
                .WhereIF(dto.EndIvrTimeEnd.HasValue,x=> x.EndIvrTime <= dto.EndIvrTimeEnd)

                .WhereIF(dto.BeginQueueTimeStart.HasValue, x => x.BeginQueueTime >= dto.BeginQueueTimeEnd)
                .WhereIF(dto.BeginQueueTimeEnd.HasValue,x=> x.BeginQueueTime <= dto.BeginQueueTimeEnd)

                .WhereIF(dto.EndQueueTimeStart.HasValue, x => x.EndQueueTime >= dto.EndQueueTimeStart)
                .WhereIF(dto.EndQueueTimeEnd.HasValue,x=> x.EndQueueTime <= dto.EndQueueTimeEnd)

                .WhereIF(dto.AnsweredTimeStart.HasValue, x => x.AnsweredTime >= dto.AnsweredTimeStart)
                .WhereIF(dto.AnsweredTimeEnd.HasValue,x=> x.AnsweredTime<= dto.AnsweredTimeEnd)

                .WhereIF(dto.OverTimeStart.HasValue, x => x.OverTime >= dto.OverTimeStart)
                .WhereIF(dto.OverTimeEnd.HasValue,x=> x.OverTime <= dto.OverTimeEnd)

                .WhereIF(dto.BeginRingTimeStart.HasValue,x=> x.BeginRingTime>= dto.BeginRingTimeStart)
                .WhereIF(dto.BeginRingTimeEnd.HasValue,x=> x.BeginRingTime<= dto.BeginRingTimeEnd)

                .WhereIF(dto.EndRingTimeStart.HasValue,x=> x.EndRingTimg >= dto.EndRingTimeStart)
                .WhereIF(dto.EndRingTimeEnd.HasValue, x=>x.EndRingTimg <= dto.EndRingTimeEnd)

                .WhereIF(dto.CallTimeStart.HasValue, x=>x.CreatedTime>= dto.CallTimeStart)
                .WhereIF(dto.CallTimeEnd.HasValue, x=>x.CreatedTime <= dto.CallTimeEnd)

                .WhereIF(!string.IsNullOrEmpty(dto.OrderNo), x => x.Order.No.Contains(dto.OrderNo))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), x => x.Order.Title.Contains(dto.Title))
                .WhereIF(!string.IsNullOrEmpty(dto.Gateway), x => x.Gateway.Contains(dto.Gateway))
                
                .WhereIF(dto.IsAiAnswered == true,x=>string.IsNullOrEmpty(x.UserId) == true)
                .OrderByDescending(x => x.CreatedTime)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize);
            return new PagedDto<TrCallDto>(total, _mapper.Map<IReadOnlyList<TrCallDto>>(items));
        }

        /// <summary>
        /// 通话记录基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("calls/basedata")]
        public async Task<object> CallBaseData()
        {
            return new
            {
                OnState = EnumExts.GetDescriptions<EOnState>(),
                CallDirection = EnumExts.GetDescriptions<ECallDirection>(),
                EndBy = EnumExts.GetDescriptions<EEndBy>(),
            };
        }


        #endregion

        #region 关联

        /// <summary>
        /// 可关联工单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("canlink-order")]
        public async Task<PagedDto<OrderDto>> CanLinkCallRecordOrder([FromQuery] CanLinkCallRecordOrderDto dto)
        {
            var (total, items) = await _orderRepository.Queryable()
                .Where(x => string.IsNullOrEmpty(x.CallId) && x.Source == Share.Enums.Order.ESource.Hotline)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.No.Contains(dto.Keyword) || x.Title.Contains(dto.Keyword))
                .OrderByDescending(x => x.CreationTime)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<OrderDto>(total, _mapper.Map<IReadOnlyList<OrderDto>>(items));
        }

        /// <summary>
        /// 可关联回访
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("canlink-ordervisit")]
        public async Task<PagedDto<OrderVisitDto>> CanLinkCallRecordOrderVisit([FromQuery] CanLinkCallRecordOrderVisitDto dto)
        {
            var (total, items) = await _orderVisitRepository.Queryable()
                .Includes(x => x.Order)
                .Where(x => string.IsNullOrEmpty(x.CallId) && x.VisitType == Share.Enums.Order.EVisitType.ArtificialVisit)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.No.Contains(dto.Keyword))
                .OrderByDescending(x => x.CreationTime)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<OrderVisitDto>(total, _mapper.Map<IReadOnlyList<OrderVisitDto>>(items));
        }

        /// <summary>
        /// 关联工单或者回访
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("link-callrecord")]
        public async Task LinkCallRecord([FromBody] LinkCallRecordDto dto)
        {
            //var trRecord = await _trCallRecordRepository.GetAsync(x => x.CallAccept == dto.CallId, HttpContext.RequestAborted);//由CallAccept改为OtherAccept
            var trRecord = await _trCallRecordRepository.GetAsync(x => x.OtherAccept == dto.CallId, HttpContext.RequestAborted);
            if (dto.IsOrder)
            {
                if (trRecord.CallOrderType == ECallOrderType.Order && !string.IsNullOrEmpty(trRecord.ExternalId))
                    throw UserFriendlyException.SameMessage("通话记录已经关联工单");

                //工单
                var order = await _orderRepository.GetAsync(x => x.Id == dto.Id, HttpContext.RequestAborted);
                if (!string.IsNullOrEmpty(order.CallId))
                    throw UserFriendlyException.SameMessage("通话记录已经关联工单");

                order.CallId = dto.CallId;
                order.FromPhone = trRecord.CPN;
                order.TransferPhone = trRecord.Gateway;
                await _orderRepository.UpdateAsync(order, HttpContext.RequestAborted);
                trRecord.CallOrderType = ECallOrderType.Order;
                trRecord.ExternalId = order.Id;

                //推省上
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineCallConnectWithOrder, new PublishCallRecrodDto() { Order = _mapper.Map<OrderDto>(order), TrCallRecordDto = _mapper.Map<TrCallDto>(trRecord) });
            }
            else
            {
                //回访
                var visit = await _orderVisitRepository.GetAsync(x => x.Id == dto.Id, HttpContext.RequestAborted);
                visit.CallId = dto.CallId;
                await _orderVisitRepository.UpdateAsync(visit, HttpContext.RequestAborted);
                trRecord.CallOrderType = ECallOrderType.Visit;
                trRecord.ExternalId = visit.Id;
            }
            await _trCallRecordRepository.UpdateAsync(trRecord, HttpContext.RequestAborted);
        }



        #endregion

        #region 坐席动作记录

        /// <summary>
        /// 坐席动作列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("telaction-list")]
        public async Task<PagedDto<TelActionListRep>> TelActionList([FromQuery] TelActionListDto dto)
        {
            if (!dto.EndTime.HasValue)
            {
                dto.EndTime = DateTime.Now.Date;
            }
            dto.EndTime = dto.EndTime.Value.AddDays(1).AddSeconds(-1);

            var (total,items) = await _telActionRecordRepository.Queryable()
                .WhereIF(string.IsNullOrEmpty(dto.TelNo) == false, x => x.TelNo.Contains(dto.TelNo))
                .WhereIF(dto.ActionTtype != null, x => x.ActionType == dto.ActionTtype)
                .WhereIF(string.IsNullOrEmpty(dto.UserName) == false, x => x.UserName.Contains(dto.UserName))
                .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
                .OrderByDescending(x => x.CreationTime)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<TelActionListRep>(total, _mapper.Map<IReadOnlyList<TelActionListRep>>(items));
        }

        /// <summary>
        /// 坐席动作列表基础数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("telaction-basedata")]
        public async Task<object> TelActionBaseData()
        {
            return new
            {
                ActionType = EnumExts.GetDescriptions<EActionType>(),
            };
        }
        #endregion

        #region 话务队列信息
        /// <summary>
        /// 今日等待数
        /// </summary>
        /// <returns></returns>
        [HttpGet("query-todaywaitnum")]
        public async Task<int> QueryToDayWaitNum()
        {
            int count = await _trCallRecordRepository.Queryable()
                        .Where(x => x.CreatedTime.Date == DateTime.Now.Date)
                        .Where(x => x.QueueTims > 0 && x.Duration == 0)
                        .CountAsync();
            return count;
        }

        #endregion

        #endregion
    }
}
