using DocumentFormat.OpenXml.Office.CustomUI;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Tels;
using Hotline.Users;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.CallCenter;
public class IPPbxApplication : IIPPbxApplication, IScopeDependency
{
    private readonly ITelRestRepository _telRestRepository;
    private readonly IRepository<Work> _workRepository;
    private readonly ITypedCache<Work> _cacheWork;
    private readonly IRepository<TelActionRecord> _telActionRecordRepository;

    public IPPbxApplication(ITelRestRepository telRestRepository, IRepository<Work> workRepository, ITypedCache<Work> cacheWork, IRepository<TelActionRecord> telActionRecordRepository)
    {
        _telRestRepository = telRestRepository;
        _workRepository = workRepository;
        _cacheWork = cacheWork;
        _telActionRecordRepository = telActionRecordRepository;
    }

    public async Task ResetTelStatus(string? workId, string? telNo, CancellationToken token = default)
    {
        Work? item = null;
        if (workId != null)
        {
            item = await _workRepository.GetAsync(workId, token);
        }
        else if (telNo != null)
        {
            item = await _workRepository.Queryable().Where(m => m.TelNo == telNo && !m.EndTime.HasValue).FirstAsync(token);
        }
        if (item == null) return;
        var telRest = await _telRestRepository.GetAsync(x => x.TelNo == item.TelNo && !x.EndTime.HasValue, token);
        if (telRest is not null)
        {
            telRest.EndRest();
            await _telRestRepository.UpdateAsync(telRest, token);
        }

        item.OffDuty();
        await _workRepository.UpdateAsync(item, token);
        _cacheWork.Remove(item.GetKey(KeyMode.UserId));
        _cacheWork.Remove(item.GetKey(KeyMode.TelNo));
        var listx = await _telActionRecordRepository.Queryable().Where(x => x.TelNo == item.TelNo && !x.EndTime.HasValue).ToListAsync();
        foreach (var itemx in listx)
        {
            itemx.EndAction();
            await _telActionRecordRepository.UpdateAsync(itemx);
        }

    }
}
