using System.Text;
using System.Text.Json;
using System.Threading;
using DocumentFormat.OpenXml.Office2010.Excel;
using DotNetCore.CAP;
using Hotline.Ai.Quality;
using Hotline.Application.CallCenter;
using Hotline.Application.ExportExcel;
using Hotline.Application.FlowEngine;
using Hotline.Application.JudicialManagement;
using Hotline.Application.OrderApp;
using Hotline.Application.Quality;
using Hotline.Application.StatisticalReport;
using Hotline.Caching.Interfaces;
using Hotline.CallCenter.BlackLists;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Configs;
using Hotline.CallCenter.Ivrs;
using Hotline.CallCenter.Tels;
using Hotline.Configurations;
using Hotline.ContingencyManagement;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.Import;
using Hotline.JudicialManagement;
using Hotline.Orders;
using Hotline.Push.FWMessage;
using Hotline.Push.Notifies;
using Hotline.Realtimes;
using Hotline.Repository.SqlSugar;
using Hotline.Repository.SqlSugar.Ts;
using Hotline.Settings;
using Hotline.Settings.Hotspots;
using Hotline.Settings.TimeLimitDomain;
using Hotline.Settings.TimeLimits;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.ExportWord;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Home;
using Hotline.Share.Dtos.Identity;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Push;
using Hotline.Share.Dtos.Realtime;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.JudicialManagement;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Push;
using Hotline.Share.Mq;
using Hotline.ThirdAccountDomainServices.Interfaces;
using Hotline.Users;
using J2N.Text;
using JiebaNet.Segmenter.Common;
using Mapster;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using NETCore.Encrypt;
using NETCore.Encrypt.Internal;
using SqlSugar;
using System.Text;
using Hotline.BatchTask;
using XC.RSAUtil;
using XF.Domain.Authentications;
using XF.Domain.Cache;
using XF.Domain.Constants;
using XF.Domain.Filters;
using XF.Domain.Locks;
using XF.Domain.Queues;
using XF.Domain.Repository;
using Order = Hotline.Orders.Order;
using OrderDto = Hotline.Share.Dtos.Order.OrderDto;
using Hotline.Schedulings;
using Hotline.Share.Dtos.BatchTask;
using Hotline.Share.Enums.BatchTask;
using Hotline.Application.OrderApp.OrderVisitApp;
using Hotline.Share.Dtos.Order.OrderVisit;

namespace Hotline.Api.Controllers;

/// <summary>
/// 
/// </summary>
//[AllowAnonymous]
public class TestController : BaseController
{
    private readonly ILogger<TestController> _logger;
    private readonly IOptionsSnapshot<CallCenterConfiguration> _options;
    private readonly ISessionContext _sessionContext;
    private readonly IRepository<User> _userRepository;
    private readonly ITypedCache<User> _cache;
    private readonly IRealtimeService _realtimeService;
    private readonly IBlacklistDomainService _blacklistDomainService;
    private readonly IIvrDomainService _ivrDomainService;
    private readonly ISugarUnitOfWork<HotlineDbContext> _uow;
    private readonly IRepository<Identity.Roles.Role> _roleRepository;
    private readonly IMediator _mediator;
    private readonly IDistributedLock _distributedLock;
    private readonly IRepository<OrderUrge> _orderUrgeRepository;
    private readonly IRepositoryTextSearch<OrderTs> _repositoryts;
    private readonly ITimeLimitDomainService _timeLimitDomainService;
    private readonly IWfModuleDomainService _wfModuleDomainService;
    private readonly IDaySettingRepository _daySettingRepository;
    private readonly ICapPublisher _capPublisher;
    private readonly IQueue _queue;
    private readonly IExportApplication _exportApplication;
    private readonly IRepository<WorkflowTrace> _workflowTraceRepository;
    private readonly IRepository<WorkflowStep> _workflowStepRepository;
    private readonly IWorkflowRepository _workflowRepository;
    private readonly IRepository<SystemOrganize> _systemOrganizeRepository;
    private readonly IOrderRepository _orderRepository;
    private readonly IRepository<TrCallRecord> _trCallRecordRepository;
    private readonly IQualityApplication _qualityApplication;
    private readonly IEnforcementApplication _enforcementApplication;
    private readonly IWorkflowDomainService _workflowDomainService;
    private readonly IMapper _mapper;
    private readonly IOrderReportApplication _orderReportApplication;
    private readonly IRepository<EnforcementOrders> _enforcementOrdersRepository;
    private readonly IRepository<JudicialManagementOrders> _judicialManagementOrdersRepository;
    private readonly IRepository<EnforcementOrdersHandler> _enforcementOrdersHandlerRepository;
    private readonly IWorkflowApplication _workflowApplication;
    private readonly IRepository<ContingencyManagementHotspot> _contingencyManagementHotspotRepository;
    private readonly IRepository<Hotspot> _hotspotRepository;
    private readonly IOrderApplication _orderApplication;
    private readonly IRepository<Tel> _telRepository;
    private readonly IOrderDomainService _orderDomainService;
    private readonly ICallApplication _callApplication;
    private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;
    private readonly ICalcExpireTime _expireTime;
    private readonly ICallNativeRepository _callNativeRepository;
    private readonly IRepository<OldSendProData> _oldSendProDataRepository;
    private readonly IOrderScreenRepository _orderScreenRepository;
    private readonly IRepository<OrderVisit> _orderVisitRepository;
    private readonly IThirdIdentiyService _thirdIdentiyService;
    private readonly IServiceProvider _serviceProvider;
    private readonly IRepository<OrderDelay> _orderDelayRepository;
    private readonly IRepository<OrderSecondaryHandling> _orderSecondaryHandlingRepository;
    private readonly IRepository<Message> _messageRepository; 
    private readonly IRepository<Scheduling> _schedulingRepository;
    private readonly IApptaskDomainService _apptaskDomainService;


    public TestController(
        //INewRockClient client,
        ILogger<TestController> logger,
        //IAuthorizeGenerator authorizeGenerator,
        IOptionsSnapshot<CallCenterConfiguration> options,
        ISessionContext sessionContext,
        IRepository<User> userRepository,
        //ICacheManager<User> cache
        //ITypedCache<List<User>> cache
        ITypedCache<User> cache,
        IRealtimeService realtimeService,
        IBlacklistDomainService blacklistDomainService,
        IIvrDomainService ivrDomainService,
        ISugarUnitOfWork<HotlineDbContext> uow,
        IRepository<Identity.Roles.Role> roleRepository,
        IMediator mediator,
        IDistributedLock distributedLock,
        IRepository<OrderUrge> orderUrgeRepository,
        IRepositoryTextSearch<OrderTs> repositoryts,
        ITimeLimitDomainService timeLimitDomainService,
        IWfModuleDomainService wfModuleDomainService,
        IDaySettingRepository daySettingRepository,
        ICapPublisher capPublisher,
        IQueue queue,
        IExportApplication exportApplication,
        IRepository<WorkflowTrace> workflowTraceRepository,
        IRepository<WorkflowStep> workflowStepRepository,
        IWorkflowRepository workflowRepository,
        IRepository<SystemOrganize> systemOrganizeRepository,
        IOrderRepository orderRepository,
        IRepository<TrCallRecord> trCallRecordRepository,
        IQualityApplication qualityApplication,
        IEnforcementApplication enforcementApplication,
        IWorkflowDomainService workflowDomainService,
        IMapper mapper,
        IOrderApplication orderApplication,
        IRepository<Tel> telRepository,
        IOrderReportApplication orderReportApplication,
        IRepository<EnforcementOrders> enforcementOrdersRepository,
        IRepository<JudicialManagementOrders> judicialManagementOrdersRepository,
        IRepository<EnforcementOrdersHandler> enforcementOrdersHandlerRepository,
        IRepository<ContingencyManagementHotspot> contingencyManagementHotspotRepository,
        IRepository<Hotspot> hotspotRepository,
        IOrderDomainService orderDomainService,
        ICallApplication callApplication,
        IOptionsSnapshot<AppConfiguration> appOptions,
        ISystemSettingCacheManager systemSettingCacheManager,
        ICalcExpireTime expireTime,
        IRepository<OrderDelay> orderDelayRepository,
        ICallNativeRepository callNativeRepository,
        IRepository<OldSendProData> oldSendProDataRepository,
        IThirdIdentiyService thirdIdentiyService,
        IOrderScreenRepository orderScreenRepository,
        IRepository<OrderVisit> orderVisitRepository,
        IServiceProvider serviceProvider,
        IRepository<OrderSecondaryHandling> orderSecondaryHandlingRepository,
        IRepository<Message> messageRepository,
        IRepository<Scheduling> schedulingRepository,
        IApptaskDomainService apptaskDomainService)
    {
        _logger = logger;
        _options = options;
        _sessionContext = sessionContext;
        _userRepository = userRepository;
        _cache = cache;
        _realtimeService = realtimeService;
        _blacklistDomainService = blacklistDomainService;
        _ivrDomainService = ivrDomainService;
        _uow = uow;
        _roleRepository = roleRepository;
        _mediator = mediator;
        _distributedLock = distributedLock;
        _orderUrgeRepository = orderUrgeRepository;
        _repositoryts = repositoryts;
        _timeLimitDomainService = timeLimitDomainService;
        _wfModuleDomainService = wfModuleDomainService;
        _daySettingRepository = daySettingRepository;
        _capPublisher = capPublisher;
        _queue = queue;
        _exportApplication = exportApplication;
        _workflowTraceRepository = workflowTraceRepository;
        _workflowStepRepository = workflowStepRepository;
        _workflowRepository = workflowRepository;
        _systemOrganizeRepository = systemOrganizeRepository;
        _orderRepository = orderRepository;
        _trCallRecordRepository = trCallRecordRepository;
        _qualityApplication = qualityApplication;
        _enforcementApplication = enforcementApplication;
        _workflowDomainService = workflowDomainService;
        _mapper = mapper;
        _orderReportApplication = orderReportApplication;
        _enforcementOrdersRepository = enforcementOrdersRepository;
        _judicialManagementOrdersRepository = judicialManagementOrdersRepository;
        _enforcementOrdersHandlerRepository = enforcementOrdersHandlerRepository;
        _contingencyManagementHotspotRepository = contingencyManagementHotspotRepository;
        _hotspotRepository = hotspotRepository;
        _orderApplication = orderApplication;
        _telRepository = telRepository;
        _orderDomainService = orderDomainService;
        _callApplication = callApplication;
        _appOptions = appOptions;
        _systemSettingCacheManager = systemSettingCacheManager;
        _expireTime = expireTime;
        _callNativeRepository = callNativeRepository;
        _oldSendProDataRepository = oldSendProDataRepository;
        _thirdIdentiyService = thirdIdentiyService;
        _orderScreenRepository = orderScreenRepository;
        _orderVisitRepository = orderVisitRepository;
        _serviceProvider = serviceProvider;
        _orderDelayRepository = orderDelayRepository;
        _orderSecondaryHandlingRepository = orderSecondaryHandlingRepository;
        _messageRepository = messageRepository;
        _schedulingRepository = schedulingRepository;
        _apptaskDomainService = apptaskDomainService;
    }
    /// <summary>
    /// 测试
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet("test")]
    public async Task Test()
    {
        var schedulingList = await _schedulingRepository.Queryable().Includes(x => x.SchedulingUser).Where(x => x.SchedulingTime!.Value.Date == DateTime.Now.Date).ToListAsync();
        Random random = new Random();
        int randomNum = random.Next(schedulingList.Count);
        var userId = schedulingList[randomNum].SchedulingUser.UserId;
    }


    /// <summary>
    /// 测试获取电话号码
    /// </summary>
    /// <returns></returns>
    [HttpGet("phonenumber_test")]
    [AllowAnonymous]
    public async Task<ThirdPhoneOutDto> GetPhoneNumberTest()
    {
        var order = await _orderRepository.Queryable().Includes(d => d.Workflow).FirstAsync(d => d.ReceiveProvinceNo == "");

        var order1 = await _orderRepository.Queryable().Includes(d => d.Workflow).FirstAsync(d => d.ReceiveProvinceNo == "20202020202020");
        var order2 = await _orderRepository.Queryable().Includes(d => d.Workflow).FirstAsync(d => d.ReceiveProvinceNo == "ZMHD995100002024111101317");

        var inDto = new ThirdTokenDto
        {
            AppId = _systemSettingCacheManager.WxOpenAppId,
            Secret = _systemSettingCacheManager.WxOpenAppSecret,
            WebApiHost = "http://10.56.131.9:50200/wxapi/"
        };
        return await _thirdIdentiyService.GetPhoneNumberAsync(inDto, CancellationToken.None);
    }

    /// <summary>
    /// 修改泸州省工单编码区域
    /// </summary>
    /// <returns></returns>
    [HttpPost("updateoldsendprodata")]
    [AllowAnonymous]
    public async Task UpdateOldSendProData()
    {
        var list = await _oldSendProDataRepository.Queryable().Where(p => p.ProvinceNo.Contains("99511500")).ToListAsync();
        if (list != null && list.Any())
        {
            foreach (var item in list)
            {
                var prono = item.ProvinceNo;
                prono = prono.Replace("99511500", "99510500");
                item.NewProvinceNo = prono;
                await _oldSendProDataRepository.UpdateAsync(item);
            }
        }
    }

    /// <summary>
    /// 修改工单省编号
    /// </summary>
    /// <returns></returns>
    [HttpPost("updatesendprodata")]
    [AllowAnonymous]
    public async Task UpdateSendProData()
    {
        var list = await _oldSendProDataRepository.Queryable().Where(p => p.ProvinceNo.Contains("99511500")).ToListAsync();
        if (list != null && list.Any())
        {
            foreach (var item in list)
            {
                var data = await _orderRepository.GetAsync(p => p.Id == item.Id, HttpContext.RequestAborted);
                if (data != null)
                {
                    data.ProvinceNo = item.NewProvinceNo;
                    await _orderRepository.Updateable(data).UpdateColumns(d => d.ProvinceNo).ExecuteCommandAsync(HttpContext.RequestAborted);
                }
            }
        }
    }

    /// <summary>
    /// 从新推送省上数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("sendpushprodata")]
    [AllowAnonymous]
    public async Task SendPushProData(string provinceNo)
    {
        //推送 受理信息、结果信息、过程信息、话务信息、回访信息
        var list = await _oldSendProDataRepository.Queryable()
            .Where(p => p.CreatorName == null)
            .WhereIF(!string.IsNullOrEmpty(provinceNo), p => p.ProvinceNo == provinceNo).ToListAsync();
        if (list != null && list.Any())
        {
            foreach (var item in list)
            {
                var order = await _orderRepository.GetAsync(p => p.Id == item.Id, HttpContext.RequestAborted);
                if (order != null)
                {
                    item.CreatorName = item.NewProvinceNo;
                    await _oldSendProDataRepository.Updateable(item).UpdateColumns(d => d.CreatorName).ExecuteCommandAsync(HttpContext.RequestAborted);
                    //受理信息
                    #region 受理信息
                    //var publishCallRecordDto = new PublishCallRecrodDto() { };
                    //if (order.SourceChannelCode == AppDefaults.SourceChannel.DianHua &&
                    //    !string.IsNullOrEmpty(order.CallId))
                    //{
                    //    if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.TianRun)
                    //    {
                    //        var callRecord = await _callApplication.GetTianrunCallAsync(order?.CallId, HttpContext.RequestAborted);
                    //        if (callRecord != null)
                    //        {
                    //            publishCallRecordDto.TrCallRecordDto = _mapper.Map<TrCallDto>(callRecord);
                    //        }
                    //    }
                    //    else if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.XingTang)
                    //    {
                    //        var call = await _callApplication.GetCallAsync(order?.CallId, HttpContext.RequestAborted);
                    //        if (call is not null)
                    //        {
                    //            publishCallRecordDto.TrCallRecordDto = _mapper.Map<TrCallDto>(call);

                    //            // 工单开始办理如果获取的通话记录是呼出并且录音文件是空就不推送通话记录
                    //            // 如果 通话记录是呼入, 并且没有录音文件
                    //            if (_systemSettingCacheManager.OrderStartHandlerPushCallIsNull && call.Direction == ECallDirection.Out && !string.IsNullOrEmpty(call.AudioFile))
                    //            {
                    //                publishCallRecordDto.TrCallRecordDto = null;
                    //            }
                    //        }
                    //    }
                    //}
                    //publishCallRecordDto.Order = _mapper.Map<OrderDto>(order);

                    //await _capPublisher.PublishAsync(EventNames.HotlineOrderFlowStarted, publishCallRecordDto,
                    //    cancellationToken: HttpContext.RequestAborted);
                    #endregion

                    //结果信息
                    #region 受理信息、话务信息、结果信息
                    if (order != null)
                    {
                        var trace = await _workflowTraceRepository.Queryable()
                            .FirstAsync(d => d.WorkflowId == order.WorkflowId && d.StepType == EStepType.End, HttpContext.RequestAborted);
                        var orderFlowDto = new OrderFlowDto
                        {
                            Order = _mapper.Map<OrderDto>(order),
                            WorkflowTrace = _mapper.Map<WorkflowTraceDto>(trace)
                        };
                        if (order.SourceChannelCode == AppDefaults.SourceChannel.DianHua &&
                            !string.IsNullOrEmpty(order.CallId))
                        {
                            if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.TianRun)
                            {
                                var callRecord = await _callApplication.GetTianrunCallAsync(order?.CallId, HttpContext.RequestAborted);
                                if (callRecord != null)
                                {
                                    orderFlowDto.TrCallRecordDto = _mapper.Map<TrCallDto>(callRecord);
                                }
                            }
                            else if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.XingTang)
                            {
                                var call = await _callApplication.GetCallAsync(order?.CallId, HttpContext.RequestAborted);
                                if (call is not null)
                                {
                                    orderFlowDto.TrCallRecordDto = _mapper.Map<TrCallDto>(call);

                                    // 工单开始办理如果获取的通话记录是呼出并且录音文件是空就不推送通话记录
                                    // 如果 通话记录是呼入, 并且没有录音文件
                                    if (_systemSettingCacheManager.OrderStartHandlerPushCallIsNull && call.Direction == ECallDirection.Out && !string.IsNullOrEmpty(call.AudioFile))
                                    {
                                        orderFlowDto.TrCallRecordDto = null;
                                    }
                                }
                            }
                        }
                        //这里需要判断是否是警情退回
                        orderFlowDto.IsNonPoliceReturn = false;
                        await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFiled, orderFlowDto, cancellationToken: HttpContext.RequestAborted);
                        //_logger.LogWarning($"推送完成: {order.ProvinceNo}");
                    }

                    #endregion

                    //过程信息
                    #region 过程信息
                    //查询过程数据

                    if (order != null)
                    {
                        var listStep = await _workflowTraceRepository.Queryable()
                             .Where(p => p.WorkflowId == order.WorkflowId && p.TraceState == EWorkflowTraceState.Normal).ToListAsync();
                        if (listStep != null && listStep.Any())
                        {
                            foreach (var itemStep in listStep)
                            {
                                var orderDto = _mapper.Map<OrderDto>(order);
                                var flowDto = new OrderFlowDto
                                {
                                    Order = orderDto,
                                    WorkflowTrace = _mapper.Map<WorkflowTraceDto>(itemStep),
                                    ExpiredTimeChanged = false,
                                    HandlerOrgLevel = itemStep.HandlerOrgId.CalcOrgLevel()
                                };
                                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFlowHandled, flowDto, cancellationToken: HttpContext.RequestAborted);
                            }
                        }
                    }

                    #endregion
                    //话务信息

                    //回访信息
                    #region 回访信息

                    if (order != null && order.Status == EOrderStatus.Visited)
                    {
                        var listVist = await _orderRepository.Queryable()
                        .Includes(x => x.OrderVisits.Where(q => q.VisitState == EVisitState.Visited).ToList(), d => d.OrderVisitDetails)
                        .Where(x => x.Id == item.Id && x.Status == EOrderStatus.Visited).ToListAsync();

                        foreach (var itemVisit in listVist)
                        {
                            try
                            {
                                var visit = itemVisit.OrderVisits.FirstOrDefault();
                                if (visit != null)
                                {
                                    var visitRemark = visit.OrderVisitDetails.Where(q => q.VisitTarget == EVisitTarget.Org).FirstOrDefault()?.VisitContent;
                                    //推省上
                                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderVisited,
                                    new PublishVisitDto()
                                    {
                                        Order = _mapper.Map<OrderDto>(itemVisit),
                                        No = visit.No,
                                        VisitType = visit.VisitType,
                                        VisitName = visit.CreatorName,
                                        VisitTime = visit.VisitTime,
                                        VisitRemark = string.IsNullOrEmpty(visitRemark) == true ? "满意" : visitRemark,
                                        AreaCode = itemVisit.AreaCode!,
                                        SubjectResultSatifyCode = visit.NowEvaluate.Key,
                                        FirstSatisfactionCode = itemVisit.FirstVisitResultCode,
                                        ClientGuid = ""
                                    }, cancellationToken: HttpContext.RequestAborted);
                                }
                            }
                            catch { }
                        }
                    }

                    #endregion
                }
            }
        }
    }



    [HttpGet("time")]
    [AllowAnonymous]
    public async Task<OpenResponse> GetTime(string batchId, string taskId)
    {
        //await _repositoryts.AddVectorAsync("f595e730-909a-45e4-9138-a84bf15f4662", DateTime.Now,
        //    new List<string> { "xx", "bb" }, HttpContext.RequestAborted);

        //await _repositoryts.AddVectorAsync("f595e730-909a-45e4-9138-a84bf15f4663", DateTime.Now,
        //    new List<string> { "aa", "bb", "cc" }, HttpContext.RequestAborted);

        //var result0 = await _repositoryts.SearchAsync(new List<string> { "xx", "aa" }, HttpContext.RequestAborted);
        //var result = await _repositoryts.SearchAsync(new List<string> { "bb" }, HttpContext.RequestAborted);
        //var result1 = await _repositoryts.SearchAsync(new List<string> { "cc", "bb" }, HttpContext.RequestAborted);
        //var result2 = await _repositoryts.SearchAsync(new List<string> { "cc", "xx" }, HttpContext.RequestAborted);
        //var result3 = await _repositoryts.SearchAsync(new List<string> { "aa", "bb", "ss" }, HttpContext.RequestAborted);


        //await _orderDomainService.SendOverTimeSms(HttpContext.RequestAborted);
        //await _repositoryts.UpdateVectorAsync("f595e730-909a-45e4-9138-a84bf15f4662",
        //    new List<string> { "ss", "bb" }, HttpContext.RequestAborted);

        //_uow.Db.Ado.SqlQueryAsync<OrderUrge>("SELECT to_tsvector('fat cats ate fat rats') @@ to_tsquery('fat & rat')")

        //var tests = _uowWex.Db.Ado.SqlQuery<Test>("select * from view_telinfo_full where IsSynch=@IsSynch", new { IsSynch = 0 });
        //var a = _uowWex.Db.Ado.ExecuteCommand("update telinfo set IsSynch=1 where GUID=@CallId", new { CallId = "b1f97f3c-88b6-4f42-b8de-83ed448854b0" });
        //var rsp = await _wexClient.QueryTelsAsync(new QueryTelRequest {  }, HttpContext.RequestAborted);

        //int a = _timeLimitDomainService.CalcWorkTime(DateTime.Now, DateTime.Parse("2023-09-11 16:21:00"));
        //int m = _timeLimitDomainService.CalcWorkTime(DateTime.Parse("2023-09-19 12:00:00"), DateTime.Parse("2023-09-20 18:00:00"), false);
        //var r = _timeLimitDomainService.CalcEndTime(DateTime.Parse("2024-6-06 14:32:47"),"40");
        //var r = _timeLimitDomainService.CalcExpiredTime(DateTime.Parse("2024-02-29 10:12:33"), Share.Enums.FlowEngine.EFlowDirection.OrgToCenter, "10");
        //await _wfModuleDomainService.PersistenceModulesAsync(HttpContext.RequestAborted);

        //var rsp = await _daprClient.InvokeMethodAsync<ApiResponse<string>>(HttpMethod.Get, "identity", "api/v1/Test/time", HttpContext.RequestAborted);
        //var rsp1 = await _daprClient.InvokeMethodAsync<int, ApiResponse<string>>(HttpMethod.Post, "identity", "api/v1/Test/time1", 222, HttpContext.RequestAborted);
        //var a = await _trClient.QueryTelsAsync(new Tr.Sdk.Tels.QueryTelRequest() { }, HttpContext.RequestAborted);
        //await _daySettingRepository.IsWorkDay(DateTime.Now);

        //var r = _timeLimitDomainService.CalcWorkTime(DateTime.Parse("2024-6-06 14:32:47"), DateTime.Parse("2024-3-22 06:00:00"), false);
        //var r = _timeLimitDomainService.CalcWorkTime(DateTime.Parse("2024-3-24 17:20:00"), DateTime.Parse("2024-3-24 17:21:00"), false);
        //await _aiVisitService.QueryAiVisitTask(batchId, taskId, HttpContext.RequestAborted);
        //var r = _timeLimitDomainService.CalcWorkTimeReduce(DateTime.Now, 5);
        //var r = _timeLimitDomainService.CalcWorkTimeToDecimal(DateTime.Parse("2024-07-09 14:57:51"), DateTime.Parse("2024-07-10 14:20:42"), false);
        //var endTime = _timeLimitDomainService
        //.CalcEndTime(DateTime.Parse("2024-07-09 14:57:51"), ETimeType.WorkDay, -3, 0, 0);///.EndTime;
        //var timeResult = _timeLimitDomainService.CalcEndTime(DateTime.Now, ETimeType.WorkDay, 3, 80, 50);
        //var t = _timeLimitDomainService.CalcWorkTimeEx(DateTime.Parse("2024-07-22 11:30:00"), DateTime.Parse("2024-07-23 14:00:00"), false);
        //var r = await _aiVisitService.QueryAiVisitTaskEx("MTAwMDAx173ASS0kSUAqK2rl2sFGME", "", HttpContext.RequestAborted);
        //var r = await _aiVisitService.QueryAiVisitTaskResult(batchId, DateTime.Parse("2024-07-28"), DateTime.Parse("2024-08-01"), HttpContext.RequestAborted);

        //var r = _timeLimitDomainService.CalcExpiredTime(DateTime.Now, EFlowDirection.CenterToCenter, batchId);
        var times = _timeLimitDomainService.CalcEndTime(DateTime.Parse("2025-04-13 23:55:57.050283"), Share.Enums.Settings.ETimeType.Day,60, 80, 50);
        //_capPublisher.PublishDelay((DateTime.Now.AddMinutes(2) - DateTime.Now), EventNames.OrderRelateCall, "123");
        //var times = await _expireTime.CalcExpiredTime(DateTime.Parse("2025-01-14 09:45:00"), DateTime.Parse("2025-01-07 09:16:53.691249"), EFlowDirection.CenterToOrg, new OrderTimeClacInfo() { AcceptTypeCode = "20" });
        //await _expireTime.CalcWorkTimeToDecimal(visit.VisitTime.Value, DateTime.Now, false);
        //var times = await _expireTime.CalcWorkTimeToDecimal(DateTime.Parse("2024-12-16 21:36:27"), DateTime.Parse("2024-12-17 12:47:05"), false);
        //var query = _userRepository.Queryable().Where(x => false);
        //await _capPublisher.PublishDelay(EventNames.OrderRelateCall, "123", cancellationToken: HttpContext.RequestAborted);
        //var times = await _expireTime.CalcExpiredTime(DateTime.Parse("2025-04-13 23:55:57.050283"), DateTime.Parse("2025-04-13 23:55:57.050283"), EFlowDirection.CenterToOrg,);
        return OpenResponse.Ok(times);
    }


    /// <summary>
    /// 通过工单号重推回访到省上
    /// </summary>
    /// <param name="Nos"></param>
    /// <returns></returns>
    [HttpPost("publish-visit-province-no")]
    [AllowAnonymous]
    public async Task PublishVisitToProvinceByNo(string Nos)
    {
        Nos = Nos.Trim();
        string[] no = Nos.Split(',');
        for (int i = 0; i < no.Length; i++)
        {
            no[i] = no[i].Trim();
        }
        var list = await _orderRepository.Queryable()
             .Includes(x => x.OrderVisits.Where(q => q.VisitState == EVisitState.Visited).ToList(), d => d.OrderVisitDetails)
             .Where(x => no.Contains(x.No) && x.Status == EOrderStatus.Visited).ToListAsync();

        foreach (var item in list)
        {
            try
            {
                var visit = item.OrderVisits.FirstOrDefault();
                if (visit != null)
                {
                    var visitRemark = visit.OrderVisitDetails.Where(q => q.VisitTarget == EVisitTarget.Org).FirstOrDefault()?.VisitContent;
                    //推省上
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderVisited,
                    new PublishVisitDto()
                    {
                        Order = _mapper.Map<OrderDto>(item),
                        No = visit.No,
                        VisitType = visit.VisitType,
                        VisitName = visit.CreatorName,
                        VisitTime = visit.VisitTime,
                        VisitRemark = string.IsNullOrEmpty(visitRemark) == true ? "满意" : visitRemark,
                        AreaCode = item.AreaCode!,
                        SubjectResultSatifyCode = visit.NowEvaluate.Key,
                        FirstSatisfactionCode = item.FirstVisitResultCode,
                        ClientGuid = ""
                    }, cancellationToken: HttpContext.RequestAborted);
                }
            }
            catch { }
        }
    }

    /// <summary>
    /// 市场监管局数据处理
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("importmarketsupervision")]
    [AllowAnonymous]
    public async Task<List<GetCaseReultSendModel>> ImportMarketSupervision(IFormFile file)
    {

        using (var stream = new MemoryStream())
        {
            file.CopyTo(stream);
            var list = MiniExcel.Query<GetCaseReultSendModel>(stream).ToList();
            //Directory.Delete(filePath, true);
            return list;
        }

    }

    /// <summary>
    /// 推送回访到省上
    /// </summary>
    /// <returns></returns>
    [HttpPost("publishVisitToProvince")]
    [AllowAnonymous]
    public async Task PublsihVisitToProvince([FromBody] DateTime date)
    {
        //查询需要推送的数据
        var list = await _orderRepository.Queryable()
             .Includes(x => x.OrderVisits.Where(q => q.VisitState == EVisitState.Visited).ToList())
             .Where(x => x.CreationTime.Date == date.Date && x.Status == EOrderStatus.Visited && x.ProcessType == EProcessType.Zhiban && x.CounterSignType == null).ToListAsync();


        foreach (var item in list)
        {
            var visit = item.OrderVisits.FirstOrDefault();
            if (visit != null)
            {
                //推省上
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderVisited,
                new PublishVisitDto()
                {
                    Order = _mapper.Map<OrderDto>(item),
                    No = visit.No,
                    VisitType = visit.VisitType,
                    VisitName = visit.CreatorName,
                    VisitTime = visit.VisitTime,
                    VisitRemark = "满意",
                    AreaCode = item.AreaCode!,
                    SubjectResultSatifyCode = "4",
                    FirstSatisfactionCode = "4",
                    ClientGuid = ""
                }, cancellationToken: HttpContext.RequestAborted);
            }
        }
    }

    [HttpGet("addcontingencymanagementhotspot")]
    [AllowAnonymous]
    public async Task AddContingencyManagementHotspot([FromQuery] string? Id, string? ParentId)
    {
        if (!string.IsNullOrWhiteSpace(Id))
        {
            var data = await _hotspotRepository.GetAsync(Id, HttpContext.RequestAborted);
            if (data != null)
            {
                var newdata = _mapper.Map<ContingencyManagementHotspot>(data);
                newdata.Id = data.Id;
                await _contingencyManagementHotspotRepository.AddAsync(newdata, HttpContext.RequestAborted);
            }
        }
        if (!string.IsNullOrEmpty(ParentId))
        {
            var data = await _hotspotRepository.Queryable().Where(p => p.ParentId == ParentId).ToListAsync();
            if (data != null && data.Count > 0)
            {
                foreach (var item in data)
                {
                    var newdata = _mapper.Map<ContingencyManagementHotspot>(item);
                    newdata.Id = item.Id;
                    await _contingencyManagementHotspotRepository.AddAsync(newdata, HttpContext.RequestAborted);
                }
            }
        }
    }

    /// <summary>
    /// 处理司法工单数据
    /// </summary>
    /// <param name="StartTime"></param>
    /// <param name="EndTime"></param>
    /// <returns></returns>
    [HttpGet("addjudicial_management_orders")]
    [AllowAnonymous]
    public async Task AddJudicialManagementOrders(DateTime StartTime, DateTime? EndTime)
    {

        var list = await _enforcementOrdersRepository.Queryable()
                 .Includes(x => x.Order)
                 .Where(x => x.CreationTime >= StartTime && x.CreationTime <= EndTime && x.Order.AcceptTypeCode == "35")
                 .ToListAsync();
        foreach (var item in list)
        {
            var order = item.Order;
            if (order != null)
            {
                var orderData = await _judicialManagementOrdersRepository.GetAsync(p => p.Id == order.Id, HttpContext.RequestAborted);
                if (orderData == null)
                {
                    orderData = new JudicialManagementOrders();
                    //处理工单
                    _mapper.Map(order, orderData);
                    orderData.Id = order.Id;
                    orderData.IsEnforcementOrder = order.IsEnforcementOrder.HasValue ? order.IsEnforcementOrder.Value : false;
                    orderData.IsTheClueTrue = item.IsTheClueTrue;
                    orderData.IsPassTheBuckOrder = item.IsPassTheBuckOrder;
                    orderData.OrderSoure = EOrderSoure.Hotline;
                    orderData.CreationTime = item.CreationTime;
                    if (item.EventTypeId == "04" || item.EventTypeId == "05" || item.EventTypeId == "06" || item.EventTypeId == "07" || item.EventTypeId == "08" ||
                        item.EventTypeId == "0401" || item.EventTypeId == "0501" || item.EventTypeId == "0601" || item.EventTypeId == "0701" || item.EventTypeId == "0801")
                    {
                        orderData.EventTypeId = "0901";
                        orderData.EventTypeName = "其他情形";
                        orderData.EventTypeSpliceName = "其他类-其他情形";
                        orderData.EventTypeOneLevelId = "09";
                    }
                    else
                    {
                        orderData.EventTypeId = item.EventTypeId;
                        orderData.EventTypeName = item.EventTypeName;
                        orderData.EventTypeSpliceName = item.EventTypeSpliceName;
                        orderData.EventTypeOneLevelId = item.EventTypeOneLevelId;
                    }

                    List<Kv> kvs = new List<Kv>
                    {
                        new Kv { Key = order.OrgLevelOneName, Value = order.OrgLevelOneCode }
                    };
                    orderData.EnforcementOrdersHandler = kvs;


                    await _judicialManagementOrdersRepository.AddAsync(orderData, HttpContext.RequestAborted);

                    //处理部门
                    EnforcementOrdersHandler enforcementOrdersHandler = new EnforcementOrdersHandler()
                    {
                        OrderId = order.Id,
                        OrderNo = order.No,
                        OrderSoure = EOrderSoure.Hotline,
                        OrgCode = order.OrgLevelOneCode,
                        OrgName = order.OrgLevelOneName,
                        CreationTime = order.CreationTime
                    };
                    await _enforcementOrdersHandlerRepository.AddAsync(enforcementOrdersHandler, HttpContext.RequestAborted);
                }
            }
        }

    }

    /// <summary>
    /// 计算工单的办理时长
    /// </summary>
    /// <param name="StartTime"></param>
    /// <param name="EndTime"></param>
    /// <returns></returns>
    [HttpGet("update_order_handle_time")]
    [AllowAnonymous]
    public async Task UpdateOrderHandleTime(DateTime StartTime, DateTime? EndTime)
    {

        var list = await _orderRepository.Queryable()
           .Where(p => p.CreationTime >= StartTime && p.CreationTime <= EndTime && p.Status >= EOrderStatus.Filed)
           .Where(p => p.CreationTimeHandleDuration == null || p.CenterToOrgHandleDuration == null)
           .ToListAsync();

        if (list.Any())
        {
            foreach (var item in list)
            {
                var creationTimeHandleDurationWorkday = item.FiledTime.HasValue
                  ?
                  //_timeLimitDomainService.CalcWorkTimeEx(
                  await _expireTime.CalcWorkTimeEx(
                      item.CreationTime, item.FiledTime.Value,
                  item.ProcessType is EProcessType.Zhiban)
                  : 0;
                var centerToOrgHandleDurationWorkday = item.FiledTime.HasValue && item.CenterToOrgTime.HasValue
                    ?
                    //_timeLimitDomainService.CalcWorkTimeEx(
                    await _expireTime.CalcWorkTimeEx(
                        item.CenterToOrgTime.Value, item.FiledTime.Value,
                    item.ProcessType is EProcessType.Zhiban)
                    : 0;

                item.CreationTimeHandleDurationWorkday = creationTimeHandleDurationWorkday;
                item.CenterToOrgHandleDurationWorkday = centerToOrgHandleDurationWorkday;

                if (item.FiledTime.HasValue)
                {
                    var count = Math.Round((item.FiledTime - item.CreationTime).Value.TotalSeconds);
                    item.CreationTimeHandleDuration = count <= 0 ? 1 : count;
                }
                else
                    item.CreationTimeHandleDuration = 0;

                if (item.FiledTime.HasValue && item.CenterToOrgTime.HasValue)
                {
                    var count = Math.Round((item.FiledTime - item.CenterToOrgTime).Value.TotalSeconds);
                    item.CenterToOrgHandleDuration = count <= 0 ? 1 : count;
                }
                else
                    item.CenterToOrgHandleDuration = 0;

                await _orderRepository.UpdateAsync(item, HttpContext.RequestAborted);
            }
        }
    }

    [HttpGet("testo")]
    [AllowAnonymous]
    public async Task<OpenResponse> TestOrigin()
    {
        var now = DateTime.Now.ToString();
        return OpenResponse.Ok(now);
    }


    [HttpGet("init-orgname")]
    [AllowAnonymous]
    public async Task InitUserOrgFullName()
    {
        var list = await _userRepository.Queryable().Where(x => 1 == 1 && string.IsNullOrEmpty(x.FullOrgName)).ToListAsync();

        foreach (var item in list)
        {
            var orgFullName = "";
            var orgFullCode = "";
            var orgId = item.OrgId;
            int strLength = orgId.Length;
            int segmentsCount = strLength / 3;
            List<string> strings = new List<string>();

            for (int i = 0; i < segmentsCount; i++)
            {
                int startIndex = i * 3;
                int length = Math.Min(3, strLength - startIndex);
                strings.Add(orgId.Substring(startIndex, length));
            }

            if (strLength > 3)
            {
                orgFullCode = strings[0];
                strings.Remove(orgFullCode);

            }

            foreach (var str in strings)
            {
                orgFullCode = orgFullCode + str;

                var org = await _systemOrganizeRepository.GetAsync(orgFullCode);
                if (org != null)
                {

                    orgFullName = orgFullName + org.Name + "/";
                }
            }
            if (orgFullName.Length > 0)
            {
                orgFullName = orgFullName.Remove(orgFullName.Length - 1);
            }
            item.FullOrgName = orgFullName;
            await _userRepository.UpdateAsync(item);
        }
    }



    [HttpPost("import")]
    [AllowAnonymous]
    public async Task<List<ExcelContent>> Import(IFormFile file)
    {
        //var FileName = file.FileName;
        //var fileExtension = Path.GetExtension(FileName);
        ////新文件名
        //var newFileName = DateTime.Now.ToString("yyyyMMddhhmmss");
        ////文件保存路径
        //var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Upload", newFileName);
        ////判断路径是否存在
        //if (!Directory.Exists(filePath))
        //{
        //    //创建路径
        //    Directory.CreateDirectory(filePath);
        //}
        //filePath = Path.Combine(filePath, newFileName+ fileExtension);
        using (var stream = new MemoryStream())
        {
            file.CopyTo(stream);
            var list = MiniExcel.Query<ExcelContent>(stream).ToList();
            //Directory.Delete(filePath, true);
            return list;
        }

    }

    [AllowAnonymous]
    [HttpGet("export")]
    public async Task<object> Export()
    {
        List<ExcelContent> list = new List<ExcelContent>();
        ExcelContent excelContent = new ExcelContent() { ExternalId = "123123" };
        list.Add(excelContent);
        return _exportApplication.ExportData<ExcelContent>(list, "demo.xlsx");
    }

    [HttpGet("pgsql")]
    public async Task<string> Pgsql()
    {
        var role = new Identity.Roles.Role
        {
            Name = $"test_role_{TimeOnly.FromDateTime(DateTime.Now)}",
            DisplayName = "test_role_display",
            ClientId = "test"
        };
        var roleId = await _roleRepository.AddAsync(role, HttpContext.RequestAborted);
        role.Description = "Description";
        await _roleRepository.UpdateAsync(role, HttpContext.RequestAborted);

        return roleId;
    }

    [AllowAnonymous]
    [HttpGet("roles")]
    public async Task<List<Identity.Roles.Role>> GetRoles()
    {
        using var lockManager = new LockManager(_distributedLock, $"{nameof(TestController)}.{nameof(GetRoles)}");
        lockManager.InvokeInLock(() => { Console.WriteLine("do something"); }, TimeSpan.FromSeconds(10));

        await lockManager.InvokeInLockAsync(
            d => _roleRepository.Queryable(includeDeleted: true).ToListAsync(),
            TimeSpan.FromSeconds(10),
            HttpContext.RequestAborted);

        var a = await _roleRepository.Queryable()
            //.Where(d => !d.IsDeleted)
            .ToListAsync();
        //var a = await db.Queryable<Role>().ToListAsync();

        var b = await _roleRepository.Queryable(includeDeleted: true).ToListAsync();
        return a;
    }

    //[AllowAnonymous]
    [HttpGet("hash")]
    public async Task Hash()
    {
        var s = _sessionContext;
    }


    /// <summary>
    /// signalR测试（method: Ring）
    /// </summary>
    /// <returns></returns>
    [HttpGet("ring")]
    public async Task RingTest()
    {
        await _realtimeService.RingAsync(_sessionContext.RequiredUserId,
            new RingDto { Id = new Guid().ToString(), From = _sessionContext.Phone ?? "未知号码", To = "12345" },
            HttpContext.RequestAborted);
    }

    /// <summary>
    /// signalR测试（method: Answered）
    /// </summary>
    /// <returns></returns>
    [HttpGet("answered")]
    public async Task AnsweredTest()
    {
        await _realtimeService.AnsweredAsync(_sessionContext.RequiredUserId,
            new AnsweredDto() { Id = new Guid().ToString(), From = _sessionContext.Phone ?? "未知号码", To = "12345" },
            HttpContext.RequestAborted);
    }

    /// <summary>
    /// signalR测试（method: Bye）
    /// </summary>
    /// <returns></returns>
    [HttpGet("bye")]
    public async Task ByeTest()
    {
        await _realtimeService.ByeAsync(_sessionContext.RequiredUserId, new ByeDto() { Id = new Guid().ToString() },
            HttpContext.RequestAborted);
    }

    [AllowAnonymous]
    [HttpGet("t2")]
    public async Task<string> GetCacheAllowAnonymous()
    {
        var systemAdministrator = _systemSettingCacheManager.GetSetting(SettingConstants.SystemAdministrator)?.SettingValue[0];
        return systemAdministrator;
    }

    [HttpGet("t3")]
    public async Task<string> GetCacheWithAuth()
    {
        var systemAdministrator = _systemSettingCacheManager.GetSetting(SettingConstants.SystemAdministrator)?.SettingValue[0];
        return systemAdministrator;
    }

    [HttpGet("t4")]
    [AllowAnonymous]
    public async Task<string> Test4()
    {
        var a = await _expireTime.CalcWorkTimeToDecimal(DateTime.Parse("2024-12-17 22:33:22"), DateTime.Parse("2024-12-18 10:29:53"), false);
        return DateTime.Now.ToString("O");
    }


    /// <summary>
    /// 批量处理甄别耗时问题
    /// </summary>
    /// <returns></returns>
	[HttpGet("order_screen_timeconsuming")]
    [AllowAnonymous]
    public async Task OrderScreenTimeConsuming()
    {
        var screens = await _orderScreenRepository.Queryable().ToListAsync();
        foreach (var item in screens)
        {
            var visit = await _orderVisitRepository.Queryable().Where(x => x.Id == item.VisitId).FirstAsync();
            if (visit != null)
            {
                var time = await _expireTime.CalcWorkTimeToDecimal(visit.VisitTime.Value, item.CreationTime, false);
                await _orderScreenRepository.Updateable().SetColumns(x => new OrderScreen { TimeConsuming = time }).Where(x => x.Id == item.Id).ExecuteCommandAsync();
            }
        }

    }

    [AllowAnonymous]
    [HttpGet("t5")]
    public async Task<string> GetUserAllowAnonymous()
    {
        //var users = await _userRepository.Queryable()
        //    .FirstAsync(d => d.Name == "xf", HttpContext.RequestAborted);
        //return users.Id;
        //var setting = _systemSettingCacheManager.GetSetting(SettingConstants.CityBaseConfiguration)?.SettingValue[0];
        //CityBaseConfiguration cityBase = JsonConvert.DeserializeObject<CityBaseConfiguration>(setting);
        //var b = cityBase;

        //var a = await _expireTime.GetWorkDay(DateTime.Now);
        //自动延期订阅
        _capPublisher.PublishDelay(DateTime.Parse("2024-10-14 14:28:00") - DateTime.Now.AddHours(1), EventNames.HotlineOrderAutomaticDelay, new PublishAutomaticDelayDto() { OrderId = "08dcebff-2fae-4c30-824f-fe2ef4d582ae" });
        return string.Empty;
    }

    [HttpGet("t6")]
    public async Task<string> GetUserWithAuth()
    {
        var users = await _userRepository.Queryable()
            .FirstAsync(d => d.Name == "xf", HttpContext.RequestAborted);
        return users.Id;
    }

    [HttpGet("rsa")]
    public async Task<string> Rsa()
    {
        var keyList = RsaKeyGenerator.Pkcs1Key(2048, true);
        var privateKey = keyList[0];
        var publicKey = keyList[1];
        return $"{publicKey} \r\n {privateKey}";
    }

    [AllowAnonymous]
    [HttpGet("republish")]
    public async Task Republish()
    {
        var provinceNos = new List<string>
        {
            "RGDH9951150024082950312",
"RGDH9951150024080750198",
"RGDH9951150024083050009",
        };
        _logger.LogWarning($"推送数据共：{provinceNos.Count}");

        var unpublishOrders = await _orderRepository.Queryable()
            .Where(d => provinceNos.Contains(d.ProvinceNo) &&
                        !string.IsNullOrEmpty(d.ProvinceNo) &&
                        d.Status >= EOrderStatus.Filed)
            .ToListAsync(HttpContext.RequestAborted);

        _logger.LogWarning($"准备开始推送：{unpublishOrders.Count}");

        foreach (var order in unpublishOrders)
        {
            var trace = await _workflowTraceRepository.Queryable()
                .FirstAsync(d => d.WorkflowId == order.WorkflowId && d.StepType == EStepType.End,
                    HttpContext.RequestAborted);
            var orderFlowDto = new OrderFlowDto
            {
                Order = _mapper.Map<OrderDto>(order),
                WorkflowTrace = _mapper.Map<WorkflowTraceDto>(trace)
            };

            if (order.SourceChannelCode == AppDefaults.SourceChannel.DianHua &&
                !string.IsNullOrEmpty(order.CallId))
            {
                if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.TianRun)
                {
                    var callRecord = await _callApplication.GetTianrunCallAsync(order.CallId, HttpContext.RequestAborted);
                    if (callRecord != null)
                    {
                        orderFlowDto.TrCallRecordDto = _mapper.Map<TrCallDto>(callRecord);
                    }
                }
                else if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.XingTang)
                {
                    var call = await _callApplication.GetCallAsync(order.CallId, HttpContext.RequestAborted);
                    if (call is not null)
                        orderFlowDto.TrCallRecordDto = _mapper.Map<TrCallDto>(call);
                }
            }

            //这里需要判断是否是警情退回
            orderFlowDto.IsNonPoliceReturn = false;
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFiled, orderFlowDto, cancellationToken: HttpContext.RequestAborted);
            _logger.LogWarning($"推送完成: {order.ProvinceNo}");
        }

        _logger.LogWarning($"推送完成");
    }


    /// <summary>
    /// 自动延期测试
    /// </summary>
    /// <param name="ExpiredTime"></param>
    /// <param name="orderId"></param>
    /// <returns></returns>
    [HttpGet("automatic_delay")]
    [AllowAnonymous]
    public async Task AutomaticDelay(DateTime ExpiredTime, string orderId)
    {

        _capPublisher.PublishDelay(ExpiredTime - DateTime.Now.AddHours(1), EventNames.HotlineOrderAutomaticDelay, new PublishAutomaticDelayDto() { OrderId = orderId });
    }


    /// <summary>
    /// 根据省编号修复工单和通话记录
    /// </summary>
    /// <param name="ProvinceNos">省编号</param>
    /// <returns></returns>
    [HttpPost("push_order_call")]
    [AllowAnonymous]
    public async Task PushOrderCallAsync([FromBody] List<string> ProvinceNos)
    {
        var orders = await _orderRepository.Queryable()
            .Where(m => ProvinceNos.Contains(m.ProvinceNo))
            .ToListAsync();
        foreach (var order in orders)
        {
            var call = await _callNativeRepository.Queryable()
                .Where(m => m.Id == order.CallId)
                .FirstAsync();
            if (call == null) continue;
            var orderDto = order.Adapt<OrderDto>();
            await _capPublisher.PublishAsync(EventNames.HotlineCallConnectWithOrder, new PublishCallRecrodDto()
            {
                Order = orderDto,
                TrCallRecordDto = call.Adapt<TrCallDto>()
            }, cancellationToken: HttpContext.RequestAborted);
        }
    }

    /// <summary>
    /// 老系统数据同步
    /// </summary>
    /// <returns></returns>
    [HttpGet("old_data_synchronization")]
    [AllowAnonymous]
    public async Task oldDataSynchronization([FromQuery] string? no)
    {
        var orders = new List<Order>();
        if (string.IsNullOrEmpty(no))
        {
            orders = await _orderRepository.Queryable().Where(x => x.No.Length == 12 && x.ActualHandleTime == null && x.CenterToOrgTime == null)
                .Where(x => x.CreationTime >= DateTime.Parse("2024-01-01") && x.CreationTime < DateTime.Parse("2024-02-01")).ToListAsync();
        }
        else
        {
            orders = await _orderRepository.Queryable().Where(x => x.No == no).ToListAsync();
        }
        foreach (var order in orders)
        {

            var steps = await _workflowStepRepository.Queryable().Where(x => x.ExternalId == order.Id).ToListAsync();

            var actualHandleStep = steps.Where(x => x.HandlerOrgId == order.ActualHandleOrgCode).OrderByDescending(x => x.CreationTime).FirstOrDefault();
            var CenterToOrgStep = steps.Where(x => x.AssignerOrgId == "001" && x.HandlerOrgId != "001").OrderByDescending(x => x.CreationTime).FirstOrDefault();

            order.ActualHandleTime = actualHandleStep.HandleTime;
            order.CenterToOrgTime = CenterToOrgStep is null ? null : CenterToOrgStep.CreationTime;

            await _orderRepository.Updateable().SetColumns(x => new Order { ActualHandleTime = order.ActualHandleTime, CenterToOrgTime = order.CenterToOrgTime }).Where(x => x.Id == order.Id).ExecuteCommandAsync();


            var now = order.FiledTime.Value;
            var handleDuration = order.StartTime.HasValue
                ? //_timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.StartTime.Value,
                    now, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var fileDuration = order.CenterToOrgTime.HasValue
                ? // _timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.CenterToOrgTime.Value,
                    now, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var allDuration = order.StartTime.HasValue
                ?
                //_timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.StartTime.Value, now,
                    order.ProcessType is EProcessType.Zhiban)
                : 0;
            var creationTimeHandleDurationWorkday = order.ActualHandleTime.HasValue
                ?
                // _timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.CreationTime, now,
                    order.ProcessType is EProcessType.Zhiban)
                : 0;
            var centerToOrgHandleDurationWorkday = order.ActualHandleTime.HasValue && order.CenterToOrgTime.HasValue
                ?
                // _timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.CenterToOrgTime.Value, now,
                    order.ProcessType is EProcessType.Zhiban)
                : 0;
            creationTimeHandleDurationWorkday = creationTimeHandleDurationWorkday <= 0 ? 10 : creationTimeHandleDurationWorkday;
            centerToOrgHandleDurationWorkday = centerToOrgHandleDurationWorkday <= 0 ? 10 : centerToOrgHandleDurationWorkday;

            double? secondaryHandlingDurationWorkday = null;
            DateTime? secondaryHandlingAuditTime = null;

            //计算二次办理时长
            if (_appOptions.Value.IsZiGong)
            {

                //查询是否有二次办理申请通过的
                var orderSecondaryData = await _orderSecondaryHandlingRepository.GetAsync(p => p.OrderId == order.Id &&
                  p.IsHandel == false && p.State == ESecondaryHandlingState.End, HttpContext.RequestAborted);
                if (orderSecondaryData != null)
                {
                    orderSecondaryData.IsHandel = true;
                    await _orderSecondaryHandlingRepository.UpdateAsync(orderSecondaryData, HttpContext.RequestAborted);
                    if (orderSecondaryData.AuditTime.HasValue)
                    {
                        secondaryHandlingAuditTime = orderSecondaryData.AuditTime;
                        secondaryHandlingDurationWorkday = orderSecondaryData.AuditTime.HasValue
                            ?
                            await _expireTime.CalcWorkTimeEx(
                                orderSecondaryData.AuditTime.Value, now,
                            false)
                            : null;
                    }
                }
                //处理办理时长
            }

            order.File(now, handleDuration, fileDuration, allDuration, creationTimeHandleDurationWorkday, centerToOrgHandleDurationWorkday,
                secondaryHandlingDurationWorkday, secondaryHandlingAuditTime);

            // order.File(now, handleDuration, fileDuration, allDuration, creationTimeHandleDurationWorkday, centerToOrgHandleDurationWorkday, null, null);

        }

    }

    [HttpGet("aiXingTang")]
    [AllowAnonymous]
    public async Task aiXingTang()
    {
        var aiQualityService = _serviceProvider.GetRequiredService<IAiQualityService>();
        await aiQualityService.CreateAiOrderQualityTask("cs202501030002.mp3", HttpContext.RequestAborted);

    }

    /// <summary>
    /// 加密验证
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("check_token")]
    [AllowAnonymous]
    public async Task<string> CheckAES([FromBody] CheckTokenDto dto)
    {
        var aesKey = EncryptProvider.CreateAesKey();

        var key = aesKey.Key;
        var iv = aesKey.IV;

        //var key = "qlzeJrbj0CPkHdFBvEAxX47Y4nCbBPZW";
        //var iv = "JxeDP0sgnPJdH9fE";

        var encrypted = EncryptProvider.AESEncrypt(dto.Str, dto.Key);
        
        //带加密向量
        var encrypted1 = EncryptProvider.AESEncrypt(dto.Str, dto.Key, dto.Iv);

        var decrypted = EncryptProvider.AESDecrypt(dto.Encrypted, dto.Key);
        //带加密向量
        var decrypted1 = EncryptProvider.AESDecrypt(dto.Encrypted, dto.Key, dto.Iv);

        //var strString = dto.AppId + dto.Timestamp;
        //return dto.AppId + EncryptProvider.AESEncrypt(strString, dto.Secret, dto.AppId);
        return $"key: {key}, iv: {iv}";
    }

    /// <summary>
    /// 归档handle错误数据处理
    /// </summary>
    /// <returns></returns>
    [HttpGet("end_order_data_dispose")]
    [AllowAnonymous]
    public async Task EndOrderDataDispose(string No, DateTime fileTime)
    {
        var orderNo = await _orderRepository.Queryable().Where(x => x.No == No).FirstAsync(HttpContext.RequestAborted);

        var workflow = await _workflowRepository.Queryable().Where(x => x.ExternalId == orderNo.Id).FirstAsync(HttpContext.RequestAborted);

        var notification = await _workflowStepRepository.Queryable().Includes(x => x.Workflow, w => w.Steps).Where(x => x.ExternalId == orderNo.Id && x.BusinessType == EBusinessType.File && x.StepType == EStepType.End).FirstAsync(HttpContext.RequestAborted);
        var order = await _orderDomainService.GetOrderAsync(orderNo.Id,
                       withExtension: true, cancellationToken: HttpContext.RequestAborted);
        //order.CheckIfFiled();
        //order.UpdateHandlingStatus(workflow.IsInCountersign);
        _mapper.Map(workflow, order);
        if (notification != null)
        {
            DateTime now;
            if (notification.HandleTime.HasValue)
                now = notification.HandleTime.Value;
            else
                now = fileTime;// DateTime.Now;

            var handleDuration = order.CenterToOrgTime.HasValue && order.ActualHandleTime.HasValue
                ? // _timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.CenterToOrgTime.Value,
                order.ActualHandleTime.Value, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var fileDuration = order.CenterToOrgTime.HasValue
                ? //_timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.CenterToOrgTime.Value,
                    now, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var allDuration = order.StartTime.HasValue
                ? // _timeLimitDomainService.CalcWorkTime(
                await _expireTime.CalcWorkTime(
                    order.StartTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            var creationTimeHandleDurationWorkday = order.ActualHandleTime.HasValue
                ? //_timeLimitDomainService.CalcWorkTimeEx(
                await _expireTime.CalcWorkTimeEx(
                    order.CreationTime, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            var centerToOrgHandleDurationWorkday = order.ActualHandleTime.HasValue && order.CenterToOrgTime.HasValue
                ? //_timeLimitDomainService.CalcWorkTimeEx(
                await _expireTime.CalcWorkTimeEx(
                    order.CenterToOrgTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            creationTimeHandleDurationWorkday = creationTimeHandleDurationWorkday <= 0 ? 10 : creationTimeHandleDurationWorkday;
            centerToOrgHandleDurationWorkday = centerToOrgHandleDurationWorkday <= 0 ? 10 : centerToOrgHandleDurationWorkday;
            double? secondaryHandlingDurationWorkday = null;
            DateTime? secondaryHandlingAuditTime = null;

            //计算二次办理时长
            if (_appOptions.Value.IsZiGong)
            {

                //查询是否有二次办理申请通过的
                var orderSecondaryData = await _orderSecondaryHandlingRepository.GetAsync(p => p.OrderId == order.Id &&
                  p.IsHandel == false && p.State == ESecondaryHandlingState.End, HttpContext.RequestAborted);
                if (orderSecondaryData != null)
                {
                    orderSecondaryData.IsHandel = true;
                    await _orderSecondaryHandlingRepository.UpdateAsync(orderSecondaryData, HttpContext.RequestAborted);
                    if (orderSecondaryData.AuditTime.HasValue)
                    {
                        secondaryHandlingAuditTime = orderSecondaryData.AuditTime;
                        secondaryHandlingDurationWorkday = orderSecondaryData.AuditTime.HasValue
                            ?
                            await _expireTime.CalcWorkTimeEx(
                                orderSecondaryData.AuditTime.Value, now,
                            false)
                            : null;
                    }
                }
                //处理办理时长
            }

            order.File(now, handleDuration, fileDuration, allDuration, creationTimeHandleDurationWorkday, centerToOrgHandleDurationWorkday,
                secondaryHandlingDurationWorkday, secondaryHandlingAuditTime);
            order.FileUserId = notification.HandlerId;
            order.FileUserName = notification.HandlerName;
            order.FileUserOrgId = notification.HandlerOrgId;
            order.FileUserOrgName = notification.HandlerOrgName;
            order.FileOrgIsCenter = notification.HandlerOrgIsCenter;
            order.FileOpinion = notification.Opinion;

            //记录冗余归档数据
            if (notification.Workflow.Steps.Any(x => x.BusinessType == Share.Enums.FlowEngine.EBusinessType.Send))
            {
                order.FileUserRole = EFileUserType.Dispatch;
            }
            else
            {
                order.FileUserRole = EFileUserType.Seat;
            }
            if (order.ProcessType == EProcessType.Jiaoban)
            {
                order.FileUserRole = EFileUserType.Org;
            }

            //是否已解决
            order.IsResolved = true;

            await _orderRepository.UpdateAsync(order, HttpContext.RequestAborted);

            var trace = await _workflowStepRepository.Queryable().Includes(x => x.Workflow, w => w.Steps).Where(x => x.ExternalId == order.Id
                && x.BusinessType == EBusinessType.File && x.StepType == EStepType.End).FirstAsync(HttpContext.RequestAborted);
            var orderFlowDto = new OrderFlowDto
            {
                Order = _mapper.Map<OrderDto>(order),
                WorkflowTrace = _mapper.Map<WorkflowTraceDto>(trace)
            };

            //这里需要判断是否是警情退回
            orderFlowDto.IsNonPoliceReturn = false;
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFiled, orderFlowDto, cancellationToken: HttpContext.RequestAborted);
        }
    }


    /// <summary>
    /// 延期EndHandle错误数据处理
    /// </summary>
    /// <returns></returns>
    [HttpPost("end_order_delay")]
    [AllowAnonymous]
    public async Task EndOrderDelay([FromBody] OrderDelayEndHandleDto dto)
    {

        var delay = await _orderDelayRepository.GetAsync(dto.DelayId);
        if (delay != null)
        {
            //delay.Flowed(workflow.FlowedUserIds, workflow.FlowedOrgIds, workflow.HandlerUsers, workflow.HandlerOrgs);
            delay.DelayState = dto.IsReviewPass ? EDelayState.Pass : EDelayState.NoPass;
            await _orderDelayRepository.Updateable(delay)
                .UpdateColumns(d => d.DelayState)
                .ExecuteCommandAsync();
            if (dto.IsReviewPass)
            {
                //处理工单延期
                await _orderApplication.DelayOrderExpiredTimeAsync(delay.OrderId, delay.DelayNum,
                    delay.DelayUnit, delay.IsProDelay, HttpContext.RequestAborted);
            }
        }
    }

    ///// <summary>
    ///// 重推归档数据(设置超期时间和归档时间)
    ///// </summary>
    ///// <param name="no"></param>
    ///// <param name="expiredTime"></param>
    ///// <param name="filedTime"></param>
    ///// <returns></returns>
    //[HttpGet("repush-order-file")]
    //[AllowAnonymous]
    //public async Task RepushOrderFile(string no, DateTime expiredTime, DateTime filedTime)
    //{
    //    var order = await _orderRepository.Queryable()
    //        .FirstAsync(d => d.No == no, HttpContext.RequestAborted);

    //    var workflow = await _workflowDomainService.GetWorkflowAsync(order.WorkflowId, withTraces: true);

    //    var orderFlowDto = new OrderFlowDto
    //    {
    //        Order = _mapper.Map<OrderDto>(order),
    //        WorkflowTrace = _mapper.Map<WorkflowTraceDto>(notification.Trace)
    //    };

    //    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFiled, orderFlowDto, cancellationToken: cancellationToken);
    //}


    /// <summary>
    /// 工单 PushTypeCode 重推处理
    /// </summary>
    /// <returns></returns>
    [HttpPost("order_push_type_code")]
    [AllowAnonymous]
    public async Task OrderPushTypeCode([FromBody] OrderPushTypeCodeDto dto)
    {
        var orders = await _orderRepository.Queryable()
            .Where(d => d.PushTypeCode.Contains(dto.PushTypeCode) && d.Source == ESource.Hotline)
            .WhereIF(dto.StartTime.HasValue, d => d.CreationTime >= dto.StartTime) //受理时间开始
            .WhereIF(dto.EndTime.HasValue, d => d.CreationTime <= dto.EndTime) //受理时间结束
            .ToListAsync(HttpContext.RequestAborted);
        foreach (var order in orders)
        {
            var orderDto = _mapper.Map<OrderDto>(order);
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderExpiredTimeUpdate, orderDto,
                cancellationToken: HttpContext.RequestAborted);
        }
    }

    [AllowAnonymous]
    [HttpGet("ip")]
    public string GetIp()
    {
        var ipv4 = HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString();
        _logger.LogWarning($"ip: {ipv4}");

        var headers = Request.Headers.ToList();
        var sb = new StringBuilder();
        foreach (var header in headers)
        {
            sb.AppendFormat("key: {0}, value: {1}", header.Key, header.Value)
                .AppendLine();
        }

        _logger.LogWarning(sb.ToString());

        return ipv4;
    }

    [AllowAnonymous]
    [HttpGet("sms")]
    public async Task<string> PushSms(DateTime start, DateTime end, bool rightnow = false)
    {
        var smses = await _messageRepository.Queryable()
            .Where(d=>d.SendState < ESendState.Success)
            .Where(d => d.CreationTime >= start && d.CreationTime <= end)
            .ToListAsync(HttpContext.RequestAborted);

        var total = smses.Count;
        if(!rightnow)
            return $"共计: {total}";

        var successed = 0;
        Share.Dtos.Push.MessageDto messageDto;
        foreach (var message in smses)
        {
            PushMessageDto pushMessage = new()
            {
                ClientId = "Hotline",
                ExternalId = message.Id,
                Content = message.Content,
                Remark = message.Remark,
                Name = message.Name,
                TelNumber = message.TelNumber
            };
            //消息队列
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SendSms, pushMessage, cancellationToken:HttpContext.RequestAborted);
            successed++;
        }

        return $"共计: {total}, 成功：{successed}";
    }

    [AllowAnonymous]
    [HttpGet("addapptask")]
    public async Task AddAppTask()
    {
        await _apptaskDomainService.AddAsync(new AddApptaskRequest
        {
            TaskType = ETaskType.VoiceVisit,
            TryLimit = 5,
            ApptaskItems = new List<AddApptaskItemRequest>
            {
                new AddApptaskItemRequest
                {
                    BusinessId = Ulid.NewUlid().ToString(),
                    TaskParams = new VoiceVisitRequest
                    {
                        PhoneNo = "15881089499",
                        VisitId = Ulid.NewUlid().ToString()
                    }
                }
            }
        }, HttpContext.RequestAborted);
    }
}

