using System.Collections.Concurrent;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Fw.Utility.Client;
using Google.Protobuf.WellKnownTypes;
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.CallCenter.BlackLists;
using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Configs;
using Hotline.CallCenter.Ivrs;
using Hotline.ContingencyManagement;
using Hotline.FlowEngine;
using Hotline.FlowEngine.Definitions;
using Hotline.FlowEngine.Notifications;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.Identity.Roles;
using Hotline.Import;
using Hotline.JudicialManagement;
using Hotline.Orders;
using Hotline.Push.Notifies;
using Hotline.Realtimes;
using Hotline.Repository.SqlSugar;
using Hotline.Repository.SqlSugar.CallCenter;
using Hotline.Repository.SqlSugar.System;
using Hotline.Repository.SqlSugar.Ts;
using Hotline.Settings;
using Hotline.Settings.Hotspots;
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.Push;
using Hotline.Share.Dtos.Realtime;
using Hotline.Share.Dtos.SendSms;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.JudicialManagement;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Push;
using Hotline.Share.Enums.Quality;
using Hotline.Share.Enums.Settings;
using Hotline.Share.Mq;
using Hotline.Share.Requests;
using Hotline.Tools;
using Hotline.Users;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using MongoDB.Driver;
using NewRock.Sdk;
using NewRock.Sdk.Security;
using SqlSugar;
using SqlSugar.SplitTableExtensions;
using StackExchange.Redis;
using Tr.Sdk;
using XC.RSAUtil;
using XF.Domain.Authentications;
using XF.Domain.Cache;
using XF.Domain.Entities;
using XF.Domain.Exceptions;
using XF.Domain.Filters;
using XF.Domain.Locks;
using XF.Domain.Queues;
using XF.Domain.Repository;
using XF.EasyCaching;
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 IAiVisitService _aiVisitService;
    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 IOrderDomainService _orderDomainService;
    private readonly ICallApplication _callApplication;
    //private readonly ITypedCache<List<User>> _cache;
    //private readonly ICacheManager<User> _cache;


    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,
        IAiVisitService aiVisitService,
        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,


   IOrderReportApplication orderReportApplication,
IRepository<EnforcementOrders> enforcementOrdersRepository,
IRepository<JudicialManagementOrders> judicialManagementOrdersRepository,
IRepository<EnforcementOrdersHandler> enforcementOrdersHandlerRepository,
IRepository<ContingencyManagementHotspot> contingencyManagementHotspotRepository,
IRepository<Hotspot> hotspotRepository,
IOrderDomainService orderDomainService,
ICallApplication callApplication
        )
    {
        _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;
        _aiVisitService = aiVisitService;
        _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;
        _orderDomainService = orderDomainService;
        _callApplication = callApplication;
	}


    /// <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(item.CreationTime, item.FiledTime.Value,
                  item.ProcessType is EProcessType.Zhiban)
                  : 0;
                var centerToOrgHandleDurationWorkday = item.FiledTime.HasValue && item.CenterToOrgTime.HasValue
                    ? _timeLimitDomainService.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("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 _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);
        //_capPublisher.PublishDelay(DateTime.Now.AddSeconds(10) - DateTime.Now, EventNames.HotlineBatchSmsTask, new PublishBatchSmsTaskDto() { TaskId = "123123" });

        return OpenResponse.Ok(DateTime.Now.ToString("F"));
    }

    [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);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet("t2")]
    public async Task GetVoiceEndAnswerAsyncTest()
    {
        //var answer = await _ivrDomainService.GetVoiceEndAnswerAsync("3", HttpContext.RequestAborted);
        //Console.WriteLine(answer.Content);
        throw new UserFriendlyException(2001, "test");
    }

    [HttpGet("wfdefine")]
    public async Task GetWorkflowDefine([FromQuery] string id)
    {
        //var query = _workflowTraceRepository.Queryable()
        //    .LeftJoin<Workflow>((t, w) => t.WorkflowId == w.Id)
        //    .LeftJoin<Order>((t, w, o) => w.ExternalId == o.Id)
        //    .Where((t, w, o) => o.No.Length == 14);

        //if (!string.IsNullOrEmpty(id))
        //    query = query.Where(d => d.WorkflowId == id);
        //var list = await query
        //    .Select((t, w, o) => new { t, w, o })
        //    .ToListAsync(HttpContext.RequestAborted);

        //var toUsers = list.Where(d => d.t.FlowAssignType == EFlowAssignType.User).ToList();
        //var userIds = toUsers.SelectMany(d => d.t.Handlers).Select(d => d.Key).Distinct().ToList();
        //var users = await _userRepository.Queryable()
        //    .Includes(d => d.Organization)
        //    .Where(d => userIds.Contains(d.Id))
        //    .ToListAsync(HttpContext.RequestAborted);
        ////var orgTraces = list.Where(d => d.FlowAssignType == EFlowAssignType.Org).ToList();
        //var stepHandlers = new List<WorkflowStepHandler>();
        //foreach (var toUser in toUsers)
        //{
        //    foreach (var traceHandler in toUser.t.Handlers)
        //    {
        //        var user = users.FirstOrDefault(d => d.Id == traceHandler.Key);
        //        if (user != null)
        //            stepHandlers.Add(new WorkflowStepHandler
        //            {
        //                WorkflowId = toUser.w.Id,
        //                ExternalId = toUser.w.ExternalId,
        //                WorkflowStepId = toUser.t.StepId,
        //                FlowAssignType = toUser.t.FlowAssignType.Value,
        //                UserId = user.Id,
        //                Username = user.Name,
        //                OrgId = user.OrgId,
        //                OrgName = user.Organization.Name,
        //                IsActualHandler = user.Id == toUser.t.HandlerId
        //            });
        //    }
        //}

        //var toOrgs = list.Where(d => d.t.FlowAssignType == EFlowAssignType.Org).ToList();
        //foreach (var toOrg in toOrgs)
        //{
        //    foreach (var handler in toOrg.t.Handlers)
        //    {
        //        stepHandlers.Add(new WorkflowStepHandler
        //        {
        //            WorkflowId = toOrg.w.Id,
        //            ExternalId = toOrg.w.ExternalId,
        //            WorkflowStepId = toOrg.t.StepId,
        //            FlowAssignType = toOrg.t.FlowAssignType.Value,
        //            OrgId = handler.Key,
        //            OrgName = handler.Value,
        //            IsActualHandler = handler.Key == toOrg.t.HandlerOrgId
        //        });
        //    }
        //}

        //_logger.LogInformation($"生成handlers: {stepHandlers.Count} 条");

        //await _workflowStepHandleRepository.AddRangeAsync(stepHandlers, HttpContext.RequestAborted);
    }

    /// <summary>
    /// 处理FlowAssignType
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpPost("t3")]
    public async Task TestExportExcel()
    {
        var orders = await _orderRepository.Queryable()
            //.Includes(d => d.Workflow, x => x.Steps.Where(d => d.BusinessType == EBusinessType.Send))
            //.Where(d=>d.Workflow.Steps.Any(d=>d.BusinessType == EBusinessType.Send))
            .Where(d => d.Status != EOrderStatus.WaitForAccept && d.CenterToOrgTime == null)
            .ToListAsync(HttpContext.RequestAborted);

        var orderIds = orders.Select(d => d.Id).ToList();
        var steps = await _workflowStepRepository.Queryable()
            .Where(d => orderIds.Contains(d.ExternalId) &&
                        d.BusinessType == EBusinessType.Send &&
                        d.Status == EWorkflowStepStatus.Handled)
            .OrderBy(d => d.CreationTime)
            .ToListAsync(HttpContext.RequestAborted);

        _logger.LogWarning($"取到steps: {steps.Count} 条");
        var updateOrders = new List<Order>();
        foreach (var order in orders)
        {
            var step = steps.Where(d => d.ExternalId == order.Id)
                .OrderBy(d => d.CreationTime)
                .FirstOrDefault();
            if (step is null) continue;

            order.CenterToOrgTime = step.HandleTime;
            order.CenterToOrgHandlerId = step.HandlerId;
            order.CenterToOrgHandlerName = step.HandlerName;
            order.CenterToOrgOpinion = step.Opinion;

            var handleDuration = order.CenterToOrgTime.HasValue && order.ActualHandleTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
                    order.ActualHandleTime.Value, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var fileDuration = order.CenterToOrgTime.HasValue && order.FiledTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
                    order.FiledTime.Value, order.ProcessType is EProcessType.Zhiban)
                : 0;
            //var allDuration = order.StartTime.HasValue
            //    ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value, order.FiledTime.Value,
            //        order.ProcessType is EProcessType.Zhiban)
            //    : 0;
            order.SetHandleDuration();
            order.SetFileDuration();

            order.HandleDurationWorkday = handleDuration;
            order.FileDurationWorkday = fileDuration;

            updateOrders.Add(order);
        }

        _logger.LogWarning($"更新工单：{updateOrders.Count} 条");
        await _orderRepository.UpdateRangeAsync(updateOrders, HttpContext.RequestAborted);
    }


    [AllowAnonymous]
    [HttpPost("t4")]
    public async Task TestExportExcel1()
    {
        var numbers = new List<string>
        {
            "20240623000180",
            "20240622000097",
            "20240621000055",
            "20240622000185",
            "20240623000025",
            "20240621000099",
            "20240621000270",
            "20240622000060",
            "20240621000144",
        };

        var orders = await _orderRepository.Queryable()
            .Includes(d => d.OrderExtension)
            .Where(d => numbers.Contains(d.No))
            .ToListAsync(HttpContext.RequestAborted);
        _logger.LogWarning($"order count: {orders.Count}");

        var workflowIds = orders.Select(d => d.WorkflowId).ToList();
        var workflows = await _workflowRepository.Queryable()
            .Includes(d => d.Steps, x => x.WorkflowTrace)
            .Where(d => workflowIds.Contains(d.Id))
            .ToListAsync(HttpContext.RequestAborted);

        //var workflowIds = orders.Select(d => d.WorkflowId).ToList();
        //var workflows = await _workflowRepository.Queryable()
        //    .Includes(d => d.Steps, x => x.WorkflowTrace)
        //    //.Includes(d=>d.Traces)
        //    .Where(d => workflowIds.Contains(d.Id))
        //    .ToListAsync(HttpContext.RequestAborted);

        var updateOrders = new List<Order>();
        foreach (var order in orders)
        {
            var workflow = workflows.First(d => d.Id == order.WorkflowId);

            _mapper.Map(workflow, order);
            var now = order.FiledTime.Value;//DateTime.Now;
            var handleDuration = order.StartTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value,
                now, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var fileDuration = order.CenterToOrgTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
                    now, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var allDuration = order.StartTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            var creationTimeHandleDurationWorkday = order.ActualHandleTime.HasValue
                   ? _timeLimitDomainService.CalcWorkTime(order.CreationTime, now,
                   order.ProcessType is EProcessType.Zhiban)
                   : 0;
            var centerToOrgHandleDurationWorkday = order.ActualHandleTime.HasValue && order.CenterToOrgTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;

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

            order.HandleDurationWorkday = handleDuration;
            order.FileDurationWorkday = fileDuration;
            order.AllDurationWorkday = allDuration;
            order.CreationTimeHandleDurationWorkday = creationTimeHandleDurationWorkday;
            order.CenterToOrgHandleDurationWorkday = centerToOrgHandleDurationWorkday;

            //计算实际办结时长
            order.SetHandleDuration();
            order.SetFileDuration();
            order.SetAllDuration();
            order.SetCreationTimeHandleDurationWorkday();
            order.SetCenterToOrgHandleDurationWorkday();

            var endStep = workflow.Steps.FirstOrDefault(d => d.StepType == EStepType.End);
            //var endTrace = workflow.Steps.FirstOrDefault(d => d.WorkflowTrace.StepType == EStepType.End)?.WorkflowTrace;
            if (endStep is null)
            {
                _logger.LogWarning($"endStep 为空, orderNo:{order.No}");
                continue;
            }

            var step = workflow.Steps.FirstOrDefault(d => d.Id == endStep.PrevStepId);
            //var trace = workflow.Steps.FirstOrDefault(d => d.WorkflowTrace.Id == endTrace.PrevStepId)?.WorkflowTrace;
            if (step is null)
            {
                _logger.LogWarning($"step 为空, orderNo:{order.No}");
                continue;
            }

            var trace = step.WorkflowTrace;
            order.FileUserId = trace.HandlerId;
            order.FileUserName = trace.HandlerName;
            order.FileUserOrgId = trace.HandlerOrgId;
            order.FileUserOrgName = trace.HandlerOrgName;
            order.FileOpinion = trace.Opinion;

            //记录冗余归档数据
            if (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;//notification.Dto.External == null ? false : notification.Dto.External.IsResolved;

            //await _orderRepository.UpdateAsync(order, cancellationToken);
            updateOrders.Add(order);

            //var callRecord = await _trCallRecordRepository.GetAsync(p => p.CallAccept == order.CallId, cancellationToken); //由CallAccept改为OtherAccept
            var orderFlowDto = new OrderFlowDto
            {
                Order = _mapper.Map<OrderDto>(order),
                WorkflowTrace = _mapper.Map<WorkflowTraceDto>(trace)
            };
            var callRecord = await _trCallRecordRepository.GetAsync(p => p.OtherAccept == order.CallId, HttpContext.RequestAborted);
            if (callRecord != null)
            {
                orderFlowDto.TrCallRecordDto = _mapper.Map<TrCallDto>(callRecord);
            }
            //这里需要判断是否是警情退回
            orderFlowDto.IsNonPoliceReturn = false;//notification.Dto.External == null ? false : notification.Dto.External.IsPoliceReturn;
            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFiled, orderFlowDto, cancellationToken: HttpContext.RequestAborted);
            //写入质检  针对受理之后直接结束的工单
            await _qualityApplication.AddQualityAsync(EQualitySource.Accepted, order.Id, HttpContext.RequestAborted);

            //司法行政监督管理-工单处理
            //await _enforcementApplication.AddEnforcementOrderAsync(order, HttpContext.RequestAborted);
        }

        //_logger.LogWarning($"更新orders：{updateOrders.Count}");
        //await _orderRepository.UpdateRangeAsync(updateOrders, HttpContext.RequestAborted);
    }

    [AllowAnonymous]
    [HttpGet("t5")]
    public async Task Test5()
    {
        var query = _orderRepository.Queryable()
            .Includes(d => d.Workflow, x => x.Steps)
            .Where(d => d.Status >= EOrderStatus.Filed &&
                        d.CurrentStepId == null)
            .OrderBy(d => d.Id);

        var size = 1000;
        var count = await query.CountAsync(HttpContext.RequestAborted);
        _logger.LogWarning($"共计 {count} 条");
        var batchs = (int)Math.Ceiling(Convert.ToDouble(count) / size);
        for (int i = 0; i < batchs; i++)
        {
            _logger.LogWarning($"第 {i} 批次开始");
            var orders = await query
                .Skip(i * size)
                .Take(size)
                .ToListAsync(HttpContext.RequestAborted);
            foreach (var order in orders)
            {
                if (order.No.Trim().Length != 14)
                {
                    order.CurrentStepId = order.ActualHandleStepId;
                    order.CurrentStepCode = order.ActualHandleStepCode;
                    order.CurrentStepName = order.ActualHandleStepName;
                    order.CurrentStepCreateTime = order.ActualHandleStepCreateTime;
                    order.CurrentStepAcceptTime = order.ActualHandleStepAcceptTime;
                    order.CurrentHandleTime = order.ActualHandleTime;
                    order.CurrentHandlerId = order.ActualHandlerId;
                    order.CurrentHandlerName = order.ActualHandlerName;
                    order.CurrentHandleOrgName = order.ActualHandleOrgName;
                    order.CurrentHandleOrgId = order.ActualHandleOrgCode;
                    order.CurrentHandleOrgAreaCode = order.ActualHandleOrgAreaCode;
                    order.CurrentHandleOrgAreaName = order.ActualHandleOrgAreaName;
                }
                else
                {
                    if (order.CounterSignType != null)
                    {
                        order.Workflow.CurrentStepId = order.Workflow.ActualHandleStepId;
                        order.Workflow.CurrentStepCode = order.Workflow.ActualHandleStepCode;
                        order.Workflow.CurrentStepName = order.Workflow.ActualHandleStepName;
                        order.Workflow.CurrentStepCreateTime = order.Workflow.ActualHandleStepCreateTime;
                        order.Workflow.CurrentStepAcceptTime = order.Workflow.ActualHandleStepAcceptTime;
                        order.Workflow.CurrentHandleTime = order.Workflow.ActualHandleTime;
                        order.Workflow.CurrentHandlerId = order.Workflow.ActualHandlerId;
                        order.Workflow.CurrentHandlerName = order.Workflow.ActualHandlerName;
                        order.Workflow.CurrentHandleOrgName = order.Workflow.ActualHandleOrgName;
                        order.Workflow.CurrentHandleOrgId = order.Workflow.ActualHandleOrgCode;
                        order.Workflow.CurrentHandleOrgAreaCode = order.Workflow.ActualHandleOrgAreaCode;
                        order.Workflow.CurrentHandleOrgAreaName = order.Workflow.ActualHandleOrgAreaName;

                        order.CurrentStepId = order.Workflow.ActualHandleStepId;
                        order.CurrentStepCode = order.Workflow.ActualHandleStepCode;
                        order.CurrentStepName = order.Workflow.ActualHandleStepName;
                        order.CurrentStepCreateTime = order.Workflow.ActualHandleStepCreateTime;
                        order.CurrentStepAcceptTime = order.Workflow.ActualHandleStepAcceptTime;
                        order.CurrentHandleTime = order.Workflow.ActualHandleTime;
                        order.CurrentHandlerId = order.Workflow.ActualHandlerId;
                        order.CurrentHandlerName = order.Workflow.ActualHandlerName;
                        order.CurrentHandleOrgName = order.Workflow.ActualHandleOrgName;
                        order.CurrentHandleOrgId = order.Workflow.ActualHandleOrgCode;
                        order.CurrentHandleOrgAreaCode = order.Workflow.ActualHandleOrgAreaCode;
                        order.CurrentHandleOrgAreaName = order.Workflow.ActualHandleOrgAreaName;
                    }
                    else
                    {
                        var endStep = order.Workflow.Steps.FirstOrDefault(d => d.StepType == EStepType.End);
                        if (endStep is null) continue;
                        var preStep = order.Workflow.Steps.FirstOrDefault(d => d.Id == endStep.PrevStepId);
                        if (preStep is null) continue;

                        order.Workflow.CurrentStepId = preStep.Id;
                        order.Workflow.CurrentStepCode = preStep.Code;
                        order.Workflow.CurrentStepName = preStep.Name;
                        order.Workflow.CurrentStepCreateTime = preStep.CreationTime;
                        order.Workflow.CurrentStepAcceptTime = preStep.AcceptTime;
                        order.Workflow.CurrentHandleTime = preStep.HandleTime;
                        order.Workflow.CurrentHandlerId = preStep.HandlerId;
                        order.Workflow.CurrentHandlerName = preStep.HandlerName;
                        order.Workflow.CurrentHandleOrgName = preStep.HandlerOrgName;
                        order.Workflow.CurrentHandleOrgId = preStep.HandlerOrgId;
                        order.Workflow.CurrentHandleOrgAreaCode = preStep.HandlerOrgAreaCode;
                        order.Workflow.CurrentHandleOrgAreaName = preStep.HandlerOrgAreaName;

                        order.CurrentStepId = order.Workflow.ActualHandleStepId;
                        order.CurrentStepCode = order.Workflow.ActualHandleStepCode;
                        order.CurrentStepName = order.Workflow.ActualHandleStepName;
                        order.CurrentStepCreateTime = order.Workflow.ActualHandleStepCreateTime;
                        order.CurrentStepAcceptTime = order.Workflow.ActualHandleStepAcceptTime;
                        order.CurrentHandleTime = order.Workflow.ActualHandleTime;
                        order.CurrentHandlerId = order.Workflow.ActualHandlerId;
                        order.CurrentHandlerName = order.Workflow.ActualHandlerName;
                        order.CurrentHandleOrgName = order.Workflow.ActualHandleOrgName;
                        order.CurrentHandleOrgId = order.Workflow.ActualHandleOrgCode;
                        order.CurrentHandleOrgAreaCode = order.Workflow.ActualHandleOrgAreaCode;
                        order.CurrentHandleOrgAreaName = order.Workflow.ActualHandleOrgAreaName;
                    }
                }
            }

            _logger.LogWarning($"更新数据：{orders.Count} 条");
            await _orderRepository.UpdateNav(orders)
                .Include(d => d.Workflow)
                .ExecuteCommandAsync();
        }


        //await _workflowTraceRepository.UpdateRangeAsync(updateSteps, HttpContext.RequestAborted);
    }

    [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}";
    }

    /// <summary>
    /// 处理错误工单数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("handle-order-data")]
    [AllowAnonymous]
    public async Task HandleData()
    {
        //var steps = await _workflowStepRepository.Queryable()
        //    .LeftJoin<Order>((ws, d) => ws.ExternalId == d.Id)
        //    .Where((ws, d) => d.Status == EOrderStatus.Handling && d.ProcessType == EProcessType.Zhiban && ws.Status == EWorkflowStepStatus.Handled && ws.StepType == EStepType.End)
        //    .ToListAsync(HttpContext.RequestAborted);
        var steps = await _workflowStepRepository.Queryable()
            .LeftJoin<Order>((ws, d) => ws.ExternalId == d.Id)
            .Where((ws, d) => d.Status == EOrderStatus.Handling && d.ProcessType == EProcessType.Zhiban && ws.Status == EWorkflowStepStatus.Handled && ws.StepType == EStepType.End)
            .ToListAsync(HttpContext.RequestAborted);

        _logger.LogInformation($"取到数据{steps.Count}条");
        foreach (var step in steps)
        {
            var order = await _orderDomainService.GetOrderAsync(step.ExternalId,
                        withExtension: true, cancellationToken: HttpContext.RequestAborted);
            var now = step.HandleTime.Value;
            var handleDuration = order.CenterToOrgTime.HasValue && order.ActualHandleTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
                order.ActualHandleTime.Value, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var fileDuration = order.CenterToOrgTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
                    now, order.ProcessType is EProcessType.Zhiban)
                : 0;
            var allDuration = order.StartTime.HasValue
                ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            var creationTimeHandleDurationWorkday = order.ActualHandleTime.HasValue
                ? _timeLimitDomainService.CalcWorkTimeEx(order.CreationTime, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            var centerToOrgHandleDurationWorkday = order.ActualHandleTime.HasValue && order.CenterToOrgTime.HasValue
                ? _timeLimitDomainService.CalcWorkTimeEx(order.CenterToOrgTime.Value, now,
                order.ProcessType is EProcessType.Zhiban)
                : 0;
            order.File(now, handleDuration, fileDuration, allDuration, creationTimeHandleDurationWorkday, centerToOrgHandleDurationWorkday);
            order.FileUserId = step.HandlerId;// notification.Trace.HandlerId;
            order.FileUserName = step.HandlerName;// notification.Trace.HandlerName;
            order.FileUserOrgId = step.HandlerOrgId;// notification.Trace.HandlerOrgId;
            order.FileUserOrgName = step.HandlerOrgName;// notification.Trace.HandlerOrgName;
            order.FileOrgIsCenter = step.HandlerOrgIsCenter; //notification.Trace.HandlerOrgIsCenter;
            order.FileOpinion = step.Opinion;//.Dto.Opinion;
            order.FileUserRole = EFileUserType.Seat;
            order.IsResolved = false;


            order.ActualHandleStepCode = step.Code;
            order.ActualHandleStepName = step.Name;
            order.ActualHandleStepId = step.Id;
            order.ActualHandleStepCreateTime = step.CreationTime;
            order.ActualHandleStepAcceptTime = step.AcceptTime;
            order.ActualHandleTime = step.HandleTime;
            order.ActualHandlerId = step.HandlerId;
            order.ActualHandlerName = step.HandlerName;
            order.ActualHandleOrgCode = step.HandlerOrgId;
            order.ActualHandleOrgName = step.HandlerOrgName;
            order.ActualHandleOrgAreaCode = step.HandlerOrgAreaCode;
            order.ActualHandleOrgAreaName = step.HandlerOrgAreaName;


            order.CurrentStepId = order.ActualHandleStepId;
            order.CurrentStepCode = order.ActualHandleStepCode;
            order.CurrentStepName = order.ActualHandleStepName;
            order.CurrentStepCreateTime = order.ActualHandleStepCreateTime;
            order.CurrentStepAcceptTime = order.ActualHandleStepAcceptTime;
            order.CurrentHandleTime = order.ActualHandleTime;
            order.CurrentHandlerId = order.ActualHandlerId;
            order.CurrentHandlerName = order.ActualHandlerName;
            order.CurrentHandleOrgName = order.ActualHandleOrgName;
            order.CurrentHandleOrgId = order.ActualHandleOrgCode;
            order.CurrentHandleOrgAreaCode = order.ActualHandleOrgAreaCode;
            order.CurrentHandleOrgAreaName = order.ActualHandleOrgAreaName;

            await _orderRepository.UpdateAsync(order, HttpContext.RequestAborted);
            //var workflowTrace = await _workflowTraceRepository.Queryable().Where(x => x.WorkflowId == step.WorkflowId && x.Code == "end").OrderByDescending(x=>x.HandleTime).FirstAsync();
            //var orderFlowDto = new OrderFlowDto
            //{
            //    Order = _mapper.Map<OrderDto>(order)
            //};
            //if (workflowTrace!=null)
            //{
            //    orderFlowDto.WorkflowTrace = _mapper.Map<WorkflowTraceDto>(workflowTrace);
            //}
            //if (order.SourceChannelCode == AppDefaults.SourceChannel.DianHua &&
            //            !string.IsNullOrEmpty(order.CallId))
            //{
               
            //    var call = await _callApplication.GetCallAsync(order.CallId, HttpContext.RequestAborted);
            //    if (call is not null)
            //        orderFlowDto.TrCallRecordDto = _mapper.Map<TrCallDto>(call);
            //}
            //await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderFiled, orderFlowDto, cancellationToken: HttpContext.RequestAborted);
        }
    }

    /// <summary>
    /// 处理工单流程错误数据   话务部直接归档件  没有归档节点
    /// </summary>
    /// <param name="StartTime"></param>
    /// <param name="EndTime"></param>
    /// <returns></returns>
    [HttpGet("oders_workflow_step")]
    [AllowAnonymous]
    public async Task AddJudicialManagementOrders()
    {

        var steps = await _workflowStepRepository.Queryable()
            .LeftJoin<Order>((ws, d) => ws.ExternalId == d.Id)
            .Where((ws, d) => d.Status == EOrderStatus.Handling && ws.NextStepCode == "end" && ws.Status == EWorkflowStepStatus.Handled && ws.StepType == EStepType.Start)
            .ToListAsync(HttpContext.RequestAborted);

        _logger.LogInformation($"取到数据 {steps.Count} 条");
        foreach (var item in steps)
        {
            ///组装数据
            //Workflow workflow
            Workflow workflow = await _workflowDomainService.GetWorkflowAsync(item.WorkflowId, withDefine: true, withSteps: true,
                cancellationToken: HttpContext.RequestAborted);
            //WorkflowStep startStep
            var startStep = workflow.Steps.FirstOrDefault(x => x.StepType == EStepType.Start);
            if (startStep is null) continue;
            //BasicWorkflowDto dto
            BasicWorkflowDto dto = new BasicWorkflowDto
            {
                NextStepCode = "end",
                NextStepName = "结束",
                BackToCountersignEnd = false,
                FlowDirection = null,
                HandlerType = 0,
                StepType = 0,
                NextHandlers = new List<FlowStepHandler>(),
                IsSms = false,
                NextMainHandler = "",
                IsStartCountersign = false,
                External = new External
                {
                    TimeLimit = null,
                    TimeLimitUnit = null,
                    IsPoliceReturn = false,
                    IsResolved = false,
                },
                BusinessType = EBusinessType.File,
                ReviewResult = 0,
                Remark = null,
                Opinion = startStep.Opinion,
                Files = new List<Share.Dtos.File.FileDto>()
            };
            //ISessionContext current
            ISessionContext current = new ProvinceSessionContext
            {
                //UserId = startStep.HandlerId,
                //UserName = startStep.HandlerName,
                OrgId = startStep.HandlerOrgId,
                OrgName = startStep.HandlerOrgName,
                OrgAreaCode = startStep.HandlerOrgAreaCode,
                OrgAreaName = startStep.HandlerOrgAreaName,
                OrgLevel = 1
            };

            //StepDefine firstStepDefine
            StepDefine firstStepDefine = workflow.WorkflowDefinition.FindStepDefine(startStep.NextStepCode);
            //FlowAssignInfo flowAssignInfo
            ////如果发起会签需检查是否支持发起会签
            //var startStepDefine = workflow.WorkflowDefinition.FindStartStepDefine();

            //下一节点是否为动态节点
            var isNextDynamic = false;

            FlowAssignInfo flowAssignInfo =
                await _workflowApplication.GetNextStepFlowAssignInfoAsync(workflow, startStep, dto, firstStepDefine, isNextDynamic, HttpContext.RequestAborted);
            //DateTime? expiredTime
            DateTime? expiredTime = startStep.StepExpiredTime;

            ///
            await _mediator.Publish(
                new StartWorkflowNotify(workflow, dto, flowAssignInfo, startStep.WorkflowTrace), HttpContext.RequestAborted);

            //firstStep是否为end，t: 实际办理节点为startStep, 并且handlerId赋值 f: 实际办理节点为firstStep, handlerId未赋值
            workflow.UpdateActualStepWhenHandle(startStep,
                current.RequiredUserId, current.UserName,
                current.RequiredOrgId, current.OrgName,
                current.OrgAreaCode, current.OrgAreaName,
                current.OrgLevel);

            workflow.UpdateCurrentStepWhenHandle(startStep,
                current.OrgAreaCode, current.OrgAreaName, current.OrgLevel);

            var endTrace = await _workflowDomainService.EndAsync(workflow, dto, firstStepDefine,
                startStep, current, expiredTime, HttpContext.RequestAborted);


        }

        _logger.LogInformation($"处理完成");
    }

    /// <summary>
    /// 处理工单流程错误数据   话务部直接归档件  没有归档节点
    /// </summary>
    /// <param name="StartTime"></param>
    /// <param name="EndTime"></param>
    /// <returns></returns>
    [HttpGet("order_participle")]
    [AllowAnonymous]
    public async Task OrderParticiple() {
		await _orderApplication.OrderParticiple("7月16日，刘先生看到兴文县县城第二人民医院对面新石海药业有限公司广场店药店套刷医保基金，将顾客不能刷统筹的药品替换为其他可以使用统筹的药品进行刷卡结算。\n    希望部门进行查处。", "1", DateTime.Now, HttpContext.RequestAborted);
	}
}
