using DotNetCore.CAP;
using Hotline.Ai.Visit;
using Hotline.Application.CallCenter;
using Hotline.Application.ExportExcel;
using Hotline.Application.FlowEngine;
using Hotline.Application.JudicialManagement;
using Hotline.Application.Orders;
using Hotline.Application.Quality;
using Hotline.Application.StatisticalReport;
using Hotline.Authentications;
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;
using Hotline.FlowEngine.Definitions;
using Hotline.FlowEngine.Notifications;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.Import;
using Hotline.JudicialManagement;
using Hotline.Orders;
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.FlowEngine;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Realtime;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.JudicialManagement;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Quality;
using Hotline.Share.Mq;
using Hotline.Users;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using Newtonsoft.Json;
using SqlSugar;
using StackExchange.Redis;
using XC.RSAUtil;
using XF.Domain.Authentications;
using XF.Domain.Cache;
using XF.Domain.Exceptions;
using XF.Domain.Filters;
using XF.Domain.Locks;
using XF.Domain.Queues;
using XF.Domain.Repository;
using Order = Hotline.Orders.Order;

namespace Hotline.Api.Controllers;

/// <summary>
/// 
/// </summary>
//[AllowAnonymous]
public class TestController : BaseController
{
    private readonly ILogger<TestController> _logger;
    //private readonly IAuthorizeGenerator _authorizeGenerator;
    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 ITrClient _trClient;
    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<WorkflowStepHandler> _workflowStepHandleRepository;

    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 ITypedCache<List<User>> _cache;
    //private readonly ICacheManager<User> _cache;
    private readonly ICalcExpireTime _expireTime;


    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,
        //ITrClient trClient,
        ICapPublisher capPublisher,
        IQueue queue,
        IExportApplication exportApplication,
        IRepository<WorkflowTrace> workflowTraceRepository,
        IRepository<WorkflowStep> workflowStepRepository,
        IWorkflowRepository workflowRepository,
        //IRepository<WorkflowStepHandler> workflowStepHandleRepository,
        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
		)
    {
        _logger = logger;
        //_authorizeGenerator = authorizeGenerator;
        _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;
        //_trClient = trClient;
        _capPublisher = capPublisher;
        _queue = queue;
        _exportApplication = exportApplication;
        _workflowTraceRepository = workflowTraceRepository;
        _workflowStepRepository = workflowStepRepository;
        _workflowRepository = workflowRepository;
        //_workflowStepHandleRepository = workflowStepHandleRepository;
        _systemOrganizeRepository = systemOrganizeRepository;
        _orderRepository = orderRepository;
        _trCallRecordRepository = trCallRecordRepository;
        _qualityApplication = qualityApplication;
        _enforcementApplication = enforcementApplication;
        _workflowDomainService = workflowDomainService;
        _orderRepository = orderRepository;
        _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;
	}


    [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 r = _timeLimitDomainService.CalcEndTime(DateTime.Parse("2024-09-12 14:45:47"), Share.Enums.Settings.ETimeType.WorkDay, 2, 80, 50);
        _capPublisher.PublishDelay((DateTime.Now.AddMinutes(2) - DateTime.Now), EventNames.OrderRelateCall, "123");
        //await _capPublisher.PublishDelay(EventNames.OrderRelateCall, "123", cancellationToken: HttpContext.RequestAborted);
        return OpenResponse.Ok(DateTime.Now.ToString("F"));
    }


    /// <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")]
    public async Task<string> Test4()
    {
        return DateTime.Now.ToString("O");
    }

    [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",
"RGDH9951150024083150167",
"RGDH9951150024083150102",
"RGDH9951150024083050052",
"RGDH9951150024080750184",
"RGDH9951150024083050108",
"RGDH9951150024083050314",
"RGDH9951150024083050363",
"RGDH9951150024083150243",
"RGDH9951150024082850303",
"QT9951150024082150023",
"RGDH9951150024080750185",
"RGDH9951150024083150065",
"RGDH9951150024082850032",
"RGDH9951150024082950295",
"RGDH9951150024080750189",
"RGDH9951150024082650189",
"RGDH9951150024083050008",
"RGDH9951150024082950036",
"RGDH9951150024082850341",
"RGDH9951150024080750215",
"RGDH9951150024081450005",
"RGDH9951150024080750212",
"RGDH9951150024083050137",
"RGDH9951150024082450124",
"RGDH9951150024083150188",
"RGDH9951150024083150083",
"RGDH9951150024082850082",
"RGDH9951150024080750174",
"RGDH9951150024082950371",
"RGDH9951150024082950114",
"RGDH9951150024083050339",
"RGDH9951150024080750217",
"RGDH9951150024082950040",
"RGDH9951150024083050031",
"RGDH9951150024083150267",
"RGDH9951150024083050064",
"RGDH9951150024072650086",
"RGDH9951150024082950360",
"RGDH9951150024080750195",
"RGDH9951150024080750210",
"RGDH9951150024082950250",
"RGDH9951150024083050145",
"RGDH9951150024083050356",
"RGDH9951150024080750194",
"RGDH9951150024080750173",
"RGDH9951150024080750213",
"RGDH9951150024080750218",
"RGDH9951150024083150271",
"RGDH9951150024083150134",
"RGDH9951150024080750179",
"RGDH9951150024083050140",
"RGDH9951150024083150262",
"RGDH9951150024083050119",
"RGDH9951150024083150177",
"RGDH9951150024083050146",
"RGDH9951150024080750223",
"RGDH9951150024080750221",
"RGDH9951150024083150130",
"RGDH9951150024080750209",
"RGDH9951150024083150237",
"RGDH9951150024082850095",
"RGDH9951150024082850223",
"RGDH9951150024083050077",
"RGDH9951150024082950118",
"RGDH9951150024082850056",
"RGDH9951150024082550177",
"RGDH9951150024083050358",
"RGDH9951150024080750193",
"RGDH9951150024082150011",
"RGDH9951150024082950167",
"RGDH9951150024083050201",
"RGDH9951150024082850048",
"RGDH9951150024083150161",
"RGDH9951150024083050300",
"RGDH9951150024083150016",
"RGDH9951150024083150101",
"RGDH9951150024082850207",
"RGDH9951150024083150144",
"RGDH9951150024082750300",
"RGDH9951150024083050230",
"RGDH9951150024080750211",
"RGDH9951150024082750379",
"RGDH9951150024082850252",
"RGDH9951150024083050204",
"RGDH9951150024080750176",
"RGDH9951150024080750190",
"RGDH9951150024083150027",
"RGDH9951150024082850308",
"RGDH9951150024082850070",
"RGDH9951150024082950068",
"RGDH9951150024083050002",
"RGDH9951150024083050130",
"RGDH9951150024083050060",
"RGDH9951150024082950282",
"RGDH9951150024082950320",
"RGDH9951150024082850312",
"RGDH9951150024083150040",
"RGDH9951150024080750202",
"RGDH9951150024083150216",
"RGDH9951150024082750156",
"RGDH9951150024082850224",
"RGDH9951150024083150238",
"RGDH9951150024083050327",
"RGDH9951150024082950090",
"RGDH9951150024083150131",
"RGDH9951150024080750187",
"RGDH9951150024082350072",
"RGDH9951150024080750177",
"RGDH9951150024082950010",
"RGDH9951150024082850263",
"RGDH9951150024082850087",
"RGDH9951150024083050234",
"RGDH9951150024083150098",
"RGDH9951150024083050166",
"RGDH9951150024082850339",
"RGDH9951150024083150157",
"RGDH9951150024080150214",
"RGDH9951150024083150149",
"RGDH9951150024083150264",
"RGDH9951150024080750200",
"RGDH9951150024083150116",
"RGDH9951150024082950188",
"RGDH9951150024083050148",
"RGDH9951150024082750338",
"RGDH9951150024082950268",
"RGDH9951150024083050337",
"RGDH9951150024082250263",
"RGDH9951150024080750196",
"RGDH9951150024080750192",
"RGDH9951150024082850272",
"RGDH9951150024082650290",
"RGDH9951150024083150117",
"RGDH9951150024080750207",
"RGDH9951150024080750201",
"RGDH9951150024080750188",
"RGDH9951150024083050011",
"RGDH9951150024083050067",
"RGDH9951150024083050193",
"RGDH9951150024082850242",
"RGDH9951150024082950121",
"RGDH9951150024080750222",
"RGDH9951150024082950280",
"RGDH9951150024080750205",
"RGDH9951150024083050334",
"RGDH9951150024083150235",
"RGDH9951150024082950156",
"RGDH9951150024080750220",
"RGDH9951150024082750209",
"RGDH9951150024083150046",
"RGDH9951150024080750214",
"RGDH9951150024082850116",
"RGDH9951150024083050082",
"RGDH9951150024083150118",
"RGDH9951150024082950338",
"RGDH9951150024082950359",
"RGDH9951150024083150156",
"RGDH9951150024083150072",
"RGDH9951150024082150001",
"RGDH9951150024082850186",
"RGDH9951150024082750377",
"RGDH9951150024083150166",
"RGDH9951150024083050255",
"RGDH9951150024083050190",
"RGDH9951150024080750175",
"RGDH9951150024083050184",
"RGDH9951150024083050021",
"RGDH9951150024082850317",
"RGDH9951150024082950146",
"RGDH9951150024083150172",
"RGDH9951150024083050354",
"RGDH9951150024082850305",
"RGDH9951150024082850351",
"RGDH9951150024082950340",
"RGDH9951150024083150273",
"RGDH9951150024080750208",
"RGDH9951150024083150053",
"RGDH9951150024082850291",
"RGDH9951150024082950104",
"RGDH9951150024082850247",
"RGDH9951150024082850320",
"RGDH9951150024083050285",
"RGDH9951150024082850011",
"RGDH9951150024083050174",
"RGDH9951150024083150212",
"RGDH9951150024083050323",
"RGDH9951150024080750224",
"RGDH9951150024083150244",
"RGDH9951150024080750199",
"RGDH9951150024082850269",
"RGDH9951150024082850053",
"RGDH9951150024082950342",
"RGDH9951150024082950046",
"RGDH9951150024082950194"
        };
        _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 });
	}

}
