using DataSharing.Application.Identity;
using DataSharing.FwDataExchange;
using DataSharing.Province;
using DataSharing.Province.SendTask.SubmitCaseRecord;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.HotlineWeb;
using DataSharing.Share.Dtos.Province;
using DataSharing.Share.Dtos.Province.XieTong.Receive;
using DataSharing.Share.Dtos.Province.XieTong;
using DotNetCore.CAP;
using Google.Protobuf.WellKnownTypes;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Mq;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Polly;
using Quartz;
using StackExchange.Redis;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web;
using XC.RSAUtil;
using XF.Domain.Cache;
using XF.Domain.Exceptions;
using XF.Domain.Repository;
using DataSharing.Province.SendTask;
using Hotline.Share.Dtos.File;
using DataSharing.Police110.Encryption;
using Newtonsoft.Json.Converters;
using DataSharing.Share.Dtos.Police110.DaoShu110;
using Microsoft.OpenApi.Validations;
using Newtonsoft.Json;
using DataSharing.Share.Dtos.HotlineSetting;
using static Lucene.Net.Util.Fst.Util;
using DataSharing.SendTask.OtherPlatforms;

namespace DataSharing.Host.Controllers
{
    public class TestController : BaseController
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly IMediator _mediator;
        private readonly ICapPublisher _capPublisher;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly IRepository<DsOrder> _dataOrderRepository;
        private readonly IRepository<DsReceiveProvinceData> _dsReceiveProvinceDataRepository;
        private readonly IRepository<DsGetCaseMaterialInfo> _getCaseMaterialInfoRepository;
        private readonly IRepository<DsGetCaseBackApply> _getCaseBackApplyRepository;
        private readonly IRepository<DsSendCaseInfo> _sendCaseInfoRepository;
        private readonly XieTongClient _xieTongClient;
        private readonly HuiJuClient _huiJuClient;
        private readonly FwClient _fwClient;
        private readonly IRepository<SendFwErrorData> _sendFwErrorDataRepository;

        private readonly IIdentityAppService _identityAppService;
        private readonly IRepository<DsTelCall> _dsTelCallRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        private readonly IRepository<DsWaitSendTaskSubmitCaseRecord> _waitSendTaskSubmitCaseRecordRepository;
        private readonly IRepository<DsOrderSend> _dsOrderSendRepository;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly ISharingSessionContext _sessionContext;
        private readonly ITypedCache<string> _configurationInformationCache;
        private readonly string GetSetTypedCacheKey = "testgetsetTypedCache";
        private readonly ILogger<TestController> _logger;
        private readonly IRepository<DsGetCaseDistrecordSend> _getCaseDistrecordSendRepository;
        private readonly IRepository<DsSendTaskOtherPlatforms> _waitSendTaskOtherPlatformsRepository;

        public TestController(IMapper mapper,
             IMediator mediator,
             ICapPublisher capPublisher,
             IChannelConfigurationManager channelConfigurationManager,
             IRepository<DsOrder> dataOrderRepository,
             IRepository<DsReceiveProvinceData> dsReceiveProvinceDataRepository,
             IRepository<DsGetCaseMaterialInfo> getCaseMaterialInfoRepository,
             IRepository<DsGetCaseBackApply> getCaseBackApplyRepository,
             IRepository<DsSendCaseInfo> sendCaseInfoRepository,
             XieTongClient xieTongClient,
             FwClient fwClient,
             IRepository<SendFwErrorData> sendFwErrorDataRepository,

             HuiJuClient huiJuClient,
             IIdentityAppService identityAppService,
              IRepository<DsTelCall> dsTelCallRepository,
              ISharingConfigurationManager sharingConfigurationManager,
              IRepository<DsWaitSendTaskSubmitCaseRecord> waitSendTaskSubmitCaseRecordRepository,
            IRepository<DsOrderSend> dsOrderSendRepository,
           IRepository<DsOrder> dsOrderRepository,
           ISharingSessionContext sessionContext,
           ITypedCache<string> configurationInformationCache,
           ILogger<TestController> logger,
           IRepository<DsGetCaseDistrecordSend> getCaseDistrecordSendRepository,
            IRepository<DsSendTaskOtherPlatforms> waitSendTaskOtherPlatformsRepository
              )
        {
            _mapper = mapper;
            _mediator = mediator;
            _capPublisher = capPublisher;
            _channelConfigurationManager = channelConfigurationManager;
            _dataOrderRepository = dataOrderRepository;
            _dsReceiveProvinceDataRepository = dsReceiveProvinceDataRepository;
            _getCaseMaterialInfoRepository = getCaseMaterialInfoRepository;
            _getCaseBackApplyRepository = getCaseBackApplyRepository;
            _sendCaseInfoRepository = sendCaseInfoRepository;
            _xieTongClient = xieTongClient;
            _fwClient = fwClient;
            _sendFwErrorDataRepository = sendFwErrorDataRepository;

            _huiJuClient = huiJuClient;
            _identityAppService = identityAppService;
            _dsTelCallRepository = dsTelCallRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
            _waitSendTaskSubmitCaseRecordRepository = waitSendTaskSubmitCaseRecordRepository;
            _dsOrderSendRepository = dsOrderSendRepository;
            _dsOrderRepository = dsOrderRepository;
            _sessionContext = sessionContext;
            _configurationInformationCache = configurationInformationCache;
            _logger = logger;
            _getCaseDistrecordSendRepository = getCaseDistrecordSendRepository;
            _waitSendTaskOtherPlatformsRepository = waitSendTaskOtherPlatformsRepository;
        }
        #endregion

        #region 转Json
        /// <summary>
        /// 转Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static string ModelToJson(object obj)
        {
            string jsonstr = "";
            try
            {
                IsoDateTimeConverter timejson = new IsoDateTimeConverter
                {
                    DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
                    //如果是年月日的话就是 ：DateTimeFormat = "yyyy'-'MM'-'dd" 注意第一个y前面没有单引号 最后一个d后面也没有单引号
                };
                jsonstr = JsonConvert.SerializeObject(obj, timejson);
            }
            catch (Exception)
            {
            }
            return jsonstr;
        }
        #endregion
        /// <summary>
        /// 拉取12315数据测试
        /// </summary>
        /// <returns></returns>
        [HttpGet("TestGetExecute")]
        [AllowAnonymous]
        public async Task Execute()
        {
            var sm4 = "4034d80c19bbd01d";
            var apiR = DaoShuDeResponse<string>.Succeed(null,"sssss");
            var apiR111 = DaoShuDeResponse<string>.Failed(null);
            // 返回数据转Json
            string jsonResult = ModelToJson(apiR);
            // 加密：json通过sm4加密转base64
            string base64 = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResult);

            var ss = @"{""rcode"":0,""rmsg"":""调用成功"",""rdata"":null}";


            string base6411111 = Sm4Crypto.Encrypt_ECB_Base64(sm4, ss);

            var sss = "";
            //#region 定时拉取12315的数据
            ////定时拉取12315的数据
            //var listSendCaseInfo = await _sendCaseInfoRepository
            //        .Queryable()
            //        .Where(p => p.IsEnd == false && p.State == "0")
            //        .OrderBy(p => p.CreationTime)
            //        .ToListAsync();
            //List<DsSendCaseInfo> dsData = [];

            //if (listSendCaseInfo != null && listSendCaseInfo.Count > 0)
            //{
            //    foreach (var item in listSendCaseInfo)
            //    {
            //        //状态更改为推送中
            //        item.State = "1";
            //        //使用乐观锁，控制数据
            //        if (await _sendCaseInfoRepository.Updateable(item).ExecuteCommandWithOptLockAsync() > 0)
            //        {
            //            dsData.Add(item);
            //        }
            //    }
            //}

            // _logger.LogInformation($"定时拉取12315数据获取条数：-------------" + dsData.Count);

            ////处理数据
            //if (dsData != null && dsData.Count > 0)
            //{
            //    foreach (var itemData in dsData)
            //    {
            //        GetCaseDistrecordSendInfo distrecordSendInfo = new() { CaseSerial = itemData.CaseSerial };

            //        #region 处理请求参数
            //        var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            //        var request = new ProvinceRequest<GetCaseDistrecordSendInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
            //        request.SetData(distrecordSendInfo);
            //        var jsonData = request.ToString();

            //        var baseAddress = configProvince.XieTong;
            //        if (!baseAddress.EndsWith('/'))
            //            baseAddress += "/";

            //        var url = baseAddress + "market/get_case_distrecord_send";
            //        #endregion
            //         _logger.LogInformation("定时拉取12315请求地址--------------------------------------" + url);
            //         _logger.LogInformation("定时拉取12315请求参数--------------------------------------" + jsonData);
            //        var response = await _xieTongClient.RequestAsync<ProvinceDistrecordResponse>(url, "Post", jsonData, HttpContext.RequestAborted);

            //         _logger.LogInformation($"工单：{itemData.CaseSerial}，请求的结果：-------------" + System.Text.Json.JsonSerializer.Serialize(response));

            //        if (response is null || response.status is null || response.custom is null)
            //        {
            //            itemData.State = "0";
            //            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //            continue;
            //        }

            //        //如果没有成功，修改为待读取
            //        if (response.status.code != "1")
            //        {
            //            itemData.State = "0";
            //            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //            continue;
            //        }


            //        //这里处理业务
            //        if (response.custom.STEP_List != null && response.custom.STEP_List.Count > 0)
            //        {
            //            //这里调用业务接口，推送办理数据
            //            List<SharingWorkflowTraceDto> Traces = [];
            //            //遍历返回的数据
            //            foreach (var item in response.custom.STEP_List)
            //            {
            //                //检测当前数据是否存在，如果存在不处理，不存在新增到数据库并推送到业务系统
            //                if (!await _getCaseDistrecordSendRepository.AnyAsync(p => p.CaseSerial == response.custom.CASE_SERIAL && p.RowGuid == item.RowGuid, HttpContext.RequestAborted))
            //                {
            //                    var tempData = _mapper.Map<DsGetCaseDistrecordSend>(item);
            //                    tempData.CaseSerial = response.custom.CASE_SERIAL;
            //                    tempData.AreaCode = _sharingConfigurationManager.GetCityCode();
            //                    await _getCaseDistrecordSendRepository.AddAsync(tempData);

            //                    #region 宜宾正常流程推送
            //                    //宜宾正常流程推送
            //                    if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
            //                    {
            //                        Traces.Add(new()
            //                        {
            //                            HandlerName = item.OperatorName,
            //                            HandlerOrgName = item.OperatorouName,
            //                            HandleTime = string.IsNullOrEmpty(item.HandleTime) == true ? null : Convert.ToDateTime(item.HandleTime),
            //                            Opinion = item.HandleOpinion
            //                        });
            //                    }
            //                    #endregion

            //                    #region 自贡只要有返回直接归档
            //                    //自贡只要有返回直接归档
            //                    if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.ZiGong)
            //                    {
            //                        if (item.OperateStatus == "市场监管局反馈" || item.OperateStatus == "市场监管局不立案")
            //                        {
            //                            var listFiles = await GetFileData(item.CliengGuid, response.custom.CASE_SERIAL, "办理上传");
            //                            OrderResultDto orderResult = new()
            //                            {
            //                                OrderId = itemData.No,
            //                                FinishType = "1",
            //                                Opinion = item.HandleOpinion,
            //                                Files = listFiles,
            //                                Source = "province"
            //                            };
            //                            //向业务系统推送消息
            //                            await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResult, cancellationToken: HttpContext.RequestAborted);
            //                            //修改为工单已经办结
            //                            itemData.IsEnd = true;
            //                            itemData.State = "1";
            //                            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //                        }
            //                    }
            //                    #endregion

            //                    #region 广元、泸州、自贡 根据查询明细办结工单
            //                    //广元、泸州、自贡 根据查询明细办结工单
            //                    if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.GuangYuan
            //                        || _sharingConfigurationManager.GetCityCode() == ConfigurationConsts.LuZhou
            //                        || _sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YaAn)
            //                    {
            //                        var listFiles = await GetFileData(item.CliengGuid, response.custom.CASE_SERIAL, "办理上传");
            //                        OrderResultDto orderResult = new()
            //                        {
            //                            OrderId = itemData.No,
            //                            Opinion = item.HandleOpinion,
            //                            Files = listFiles,
            //                            Source = "province"
            //                        };
            //                        if (item.OperateStatus == "市场监管局反馈")
            //                        {
            //                            orderResult.FinishType = "1";
            //                        }
            //                        else if (item.OperateStatus == "市场监管局不立案")
            //                        {
            //                            orderResult.FinishType = "0";
            //                        }
            //                        //向业务系统推送消息
            //                        await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResult, cancellationToken: HttpContext.RequestAborted);
            //                        //修改为工单已经办结
            //                        itemData.IsEnd = true;
            //                        itemData.State = "1";
            //                        await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //                    }
            //                    #endregion

            //                }
            //            }
            //            #region 宜宾推送办理明细数据
            //            //宜宾推送办理明细数据
            //            if (_sharingConfigurationManager.GetCityCode() == ConfigurationConsts.YiBin)
            //            {
            //                if (Traces != null && Traces.Count > 0)
            //                {
            //                    SharingAddOrderTracesDto addOrderTracesDto = new()
            //                    {
            //                        OrderId = itemData.OrderID,
            //                        Traces = Traces
            //                    };
            //                    //往业务系统推送数据
            //                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderAddTraces, addOrderTracesDto, cancellationToken: HttpContext.RequestAborted);
            //                }
            //                itemData.State = "0";
            //                await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //            }
            //            #endregion
            //        }

            //        if (itemData.IsEnd == false)
            //        {
            //            itemData.State = "0";
            //            await _sendCaseInfoRepository.UpdateAsync(itemData, cancellationToken: HttpContext.RequestAborted);
            //        }

            //        Thread.Sleep(2000);
            //    }
            //}

            //#endregion
            _logger.LogInformation($"进来了时间是{DateTime.Now}");
        }

        /// <summary>
        ///  根据附件Id,工单编号查询所有附件
        /// </summary>
        /// <param name="CliengGuid">材料标识ID</param>
        /// <param name="CaseSerial">工单编号</param>
        /// <param name="Classify">材料分类</param>
        /// <returns></returns>
        private async Task<List<FileDto>> GetFileData(string CliengGuid, string CaseSerial, string Classify)
        {
            var list = await _getCaseMaterialInfoRepository.Queryable().Where(p => p.CliengGuid == CliengGuid && p.CaseSerial == CaseSerial).ToListAsync();

            List<FileDto> fileDtos = new();
            if (fileDtos == null || fileDtos.Count == 0)
                return fileDtos;
            foreach (var item in list)
            {
                fileDtos.Add(new FileDto()
                {
                    Name = item.FileName,
                    Type = item.Type,
                    Classify = Classify,
                    Additions = item.Additions,
                    Path = item.Path
                });
            }
            return fileDtos;
        }



        [HttpGet("asdasda")]
        [AllowAnonymous]
        public async Task asdasda()
        {
            ConfigurationSmartCitySystem config = _sharingConfigurationManager.GetZiGongConfig().SmartCitySystem;

            var baseAddress = config.AddressUrl;
            if (!baseAddress.EndsWith('/'))
                baseAddress += "/";
            var tasks = await _waitSendTaskOtherPlatformsRepository.GetAsync(p=>p.Id== "08dd28c7-1d17-4ac0-8078-b734f7fb8a61");
            HotlineClientResponse result = await _fwClient.RequestNoTokenOtherAsync<HotlineClientResponse>(baseAddress,  tasks.Path,
                "POST", tasks.Request, HttpContext.RequestAborted);
        }



        /// <summary>
        /// 
        /// </summary>
        [HttpGet("aaaaaaaaa")]
        [AllowAnonymous]
        public async void asdaa()
        {
            var data = _channelConfigurationManager.GetConfigurationProvince();
            //  var result = await _huiJuClient.RequestAsync<ProvinceResponse>(data.HuiJu + PtahDefaults.SubmitCaseInfo, "Post", "", HttpContext.RequestAborted);
            await _xieTongClient.RequestAsync<ProvinceResponse>(data.XieTong, "POST", "", HttpContext.RequestAborted);
            var ss = _sessionContext;
        }

        /// <summary>
        /// 处理历史数据标题
        /// </summary>
        /// <returns></returns>
        [HttpGet("updateordersource")]
        [AllowAnonymous]
        public async Task UpdateOrderSource()
        {
            var list = await _dsOrderSendRepository.Queryable()
                   .Where(p => p.Title == null || p.Title == "")
                   .ToListAsync();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var data = await _dsOrderRepository.GetAsync(p => p.OrderId == item.OrderId, HttpContext.RequestAborted);
                    if (data != null)
                    {
                        item.Title = data.Title;
                        _dsOrderSendRepository.Updateable(item).UpdateColumns(p => p.Title).ExecuteCommand();
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("getxietongtoken")]
        [AllowAnonymous]
        public async Task<string> GetXieTongToken()
        {
            string strToken = await _xieTongClient.GetTokenXieTongAsync(HttpContext.RequestAborted);
            return strToken;
        }

        /// <summary>
        /// 测试token
        /// </summary>
        /// <returns></returns>
        [HttpGet("gettesttokeninfo")]
        [AllowAnonymous]
        public async Task GetToken([FromQuery] string TEXT)
        {
            var userInfo = Request.Headers["userinfo"].ToString();
            if (string.IsNullOrEmpty(userInfo))
                throw UserFriendlyException.SameMessage("用户信息获取失败");

            var pkcs1 = new RsaPkcs1Util(Encoding.UTF8, "12345", "12345");
            var info = pkcs1.Decrypt(userInfo, RSAEncryptionPadding.Pkcs1);
            if (info == null)
                throw UserFriendlyException.SameMessage("用户信息获取失败");

            var user = System.Text.Json.JsonSerializer.Deserialize<UserInfo>(info);
            if (user == null)
                throw UserFriendlyException.SameMessage("用户信息获取失败");

            //DsWaitSendTaskSubmitCaseRecord data = new();
            //var list = await _waitSendTaskSubmitCaseRecordRepository.Queryable().ToListAsync();
            //for (int i = 0; i < list.Count; i++)
            //{
            //    list[i].TaskType=i.ToString();
            //    await _waitSendTaskSubmitCaseRecordRepository.UpdateAsync(list[i]);
            //    data = list[i];
            //}

            //for (int i =40; i < 200; i++)
            //{
            //    data.Id = Guid.NewGuid().ToString();
            //    data.TaskType= i.ToString();
            //    await _waitSendTaskSubmitCaseRecordRepository.AddAsync(data);
            //}



            List<ProvinceBathErrorObjsResponse> ErrorObjs = new List<ProvinceBathErrorObjsResponse>();

            var t = ErrorObjs.Exists(p => p.CaseSerial == "123456");

            List<ProvinceBathErrorObjsResponse> ErrorObjs1 = new List<ProvinceBathErrorObjsResponse>()
            {
                new ProvinceBathErrorObjsResponse()
                {
                    CaseSerial="1",CaseId="2"
                }
            };
            var t1 = ErrorObjs1.Exists(p => p.CaseSerial == "1");
            var t2 = ErrorObjs1.Exists(p => p.CaseSerial == "12");

            if (!string.IsNullOrEmpty(TEXT))
            {

                ProvinceResponse result = new();

                var ss = "";
                try
                {
                    var sss = System.Text.Json.JsonSerializer.Deserialize<ProvinceResponse>(TEXT);
                }
                catch (Exception ex)
                {

                    ss = ex.Message;
                }


            }


            //DsWaitSendTaskSubmitCaseRecord dsWaitSendTaskSubmitCaseRecord = new DsWaitSendTaskSubmitCaseRecord()
            //{
            //    State = EWaitSendTaskState.WaitPush,
            //    ProvinceNo = "111111",
            //    TaskType = "111",
            //    HttpMethod = "POST",
            //    Path = "11111",
            //    Request = "1",
            //    RequestData = new Share.Dtos.Province.HuiJu.SubmitCaseRecordInfo(),

            //};

            //await _waitSendTaskSubmitCaseRecordRepository.AddAsync(dsWaitSendTaskSubmitCaseRecord, HttpContext.RequestAborted);

            //dsWaitSendTaskSubmitCaseRecord.State = EWaitSendTaskState.Pushing;

            //await _waitSendTaskSubmitCaseRecordRepository.Updateable(dsWaitSendTaskSubmitCaseRecord).ExecuteCommandWithOptLockAsync();

            //获取附件上传Token
            // string strToken = await _xieTongClient.GetTokenAsync(HttpContext.RequestAborted);
            //  var token = await _huiJuClient.GetTokenHJAsync(HttpContext.RequestAborted);

            var peizhi = _channelConfigurationManager.GetConfigurationProvince();
            var peizhi1 = _channelConfigurationManager.GetConfigurationBusinessFile();
            var peizhi2 = _channelConfigurationManager.GetConfigurationHotlineClient();

            var peizhi3 = _sharingConfigurationManager.IsCity(ConfigurationConsts.YiBin);
            var peizhi4 = _sharingConfigurationManager.GetCityCode();
            var peizhi5 = _sharingConfigurationManager.GetCityName();


            var peizhi51 = _sharingConfigurationManager.GetHotlineName();
            var peizhi52 = _sharingConfigurationManager.GetPoliceOrgCode();
            var peizhi53 = _sharingConfigurationManager.GetProvinceAssignmentOrgCode();
            var peizhi54 = _sharingConfigurationManager.GetProvinceOrgCode();

            var peizhi6 = _sharingConfigurationManager.GetYiBinConfig();
            var peizhi7 = _sharingConfigurationManager.GetZiGongConfig();




            //  return token;
        }



        [HttpPost("test")]
        [AllowAnonymous]
        public async Task<string> Test([FromBody] LoginDto dto)
        {
            // return await _identityAppService.LoginAsync(dto, HttpContext.RequestAborted);

            var list = await _dsTelCallRepository.Queryable().Where(p => p.OverTime == null).ToListAsync();
            foreach (var item in list)
            {
                if (item.EndRingTimg != null)
                    item.AnsweredTime = item.EndRingTimg.Value.AddSeconds(2);
                else
                    item.AnsweredTime = item.BeginIvrTime.Value.AddSeconds(2);

                item.OverTime = item.AnsweredTime.Value.AddSeconds(item.Duration);

                Random random = new Random();

                // 生成一个从0到100的随机整数
                int randomNumber = random.Next(20, 180);
                item.FirstSendProvinceTime = item.OverTime.Value.AddSeconds(randomNumber);
                item.LastSendProvinceTime = item.FirstSendProvinceTime;
                await _dsTelCallRepository.UpdateAsync(item, HttpContext.RequestAborted);
            }

            var listOrder = await _dataOrderRepository.Queryable().Where(p => p.FirstSendProvinceTime == null).ToListAsync();
            foreach (var item in listOrder)
            {
                Random random = new Random();

                // 生成一个从0到100的随机整数
                int randomNumber = random.Next(20, 180);

                if (item.StartTime != null)
                    item.FirstSendProvinceTime = item.StartTime.Value.AddSeconds(randomNumber);
                else
                    item.FirstSendProvinceTime = item.CaseDate.Value.AddSeconds(randomNumber);

                item.LastSendProvinceTime = item.FirstSendProvinceTime;

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

            return "成功";
        }

        [HttpGet("test1")]
        public async Task<string> Test1()
        {
            return DateTime.Now.ToString();
        }

        [HttpGet("test2")]
        [AllowAnonymous]
        public async Task<string> Test2()
        {
            return $"test - {DateTime.Now.ToString()}";
        }

        /// <summary>
        /// 缓存写入测试
        /// </summary>
        /// <returns></returns>
        [HttpGet("TestSet")]
        [AllowAnonymous]
        public async Task<string> TestSet()
        {
            await _configurationInformationCache.SetAsync(GetSetTypedCacheKey, DateTime.Now.ToString(), TimeSpan.FromSeconds(5), HttpContext.RequestAborted);
            return "写入成功";
        }

        /// <summary>
        /// 缓存读取测试
        /// </summary>
        /// <returns></returns>
        [HttpGet("TestGet")]
        [AllowAnonymous]
        public async Task<string> TestGet()
        {
            string sss = @"{
	""Order"": {
		""Status"": 100,
		""StatusText"": ""办理中"",
		""ExpiredStatus"": 0,
		""ExpiredStatusText"": ""正常"",
		""ProcessType"": 10,
		""IsPublicity"": false,
		""No"": ""20241016000402"",
		""IsNo110"": false,
		""TagNames"": null,
		""StartTime"": ""2024-10-16T10:06:48.3111811+08:00"",
		""CenterToOrgTime"": null,
		""FiledTime"": null,
		""FileOpinion"": null,
		""HandleDuration"": 0,
		""HandleDurationWorkday"": 0,
		""AllDuration"": 0,
		""CreationTimeHandleDuration"": null,
		""CreationTimeHandleDurationWorkday"": null,
		""CenterToOrgHandleDuration"": null,
		""CenterToOrgHandleDurationWorkday"": null,
		""ActualHandleStepCode"": ""c986ab87-1508-493a-81e9-9b7681240bd8"",
		""ActualHandleStepName"": ""派单组"",
		""ActualHandleStepCreateTime"": ""2024-10-16T10:06:48.4537999+08:00"",
		""ActualHandleStepAcceptTime"": null,
		""ActualHandleTime"": null,
		""ActualHandlerId"": null,
		""ActualHandlerName"": null,
		""ActualHandleOrgName"": ""市民热线服务中心"",
		""ActualHandleOrgCode"": ""001"",
		""ActualHandleOrgAreaCode"": null,
		""ActualHandleOrgAreaName"": null,
		""ActualHandlerValue"": null,
		""ActualHandlerKey"": null,
		""ActualHandlerType"": null,
		""ActualOpinion"": ""办理中..."",
		""RealHandlerName"": null,
		""RealHandlerPhone"": null,
		""RealCommunicationMode"": null,
		""RealCommunicationTime"": null,
		""RealCommunicationAddress"": null,
		""RealIsContacted"": null,
		""RealContactLocale"": null,
		""CurrentStepId"": ""08dced87-3160-46b0-8184-f71fcf98e295"",
		""CurrentStepCode"": ""c986ab87-1508-493a-81e9-9b7681240bd8"",
		""CurrentStepName"": ""派单组"",
		""CurrentStepCreateTime"": ""2024-10-16T10:06:48.4537999+08:00"",
		""CurrentStepAcceptTime"": null,
		""CurrentStepAcceptText"": ""未签收"",
		""CurrentHandleTime"": null,
		""CurrentHandlerId"": null,
		""CurrentHandlerName"": null,
		""CurrentHandleOrgName"": ""市民热线服务中心"",
		""CurrentHandleOrgId"": ""001"",
		""CurrentHandleOrgLevel"": 1,
		""CurrentHandleOrgAreaCode"": null,
		""CurrentHandleOrgAreaName"": null,
		""OrgLevelOneCode"": ""001"",
		""OrgLevelOneName"": ""市民热线服务中心"",
		""AcceptorId"": ""48ba88f3-fd71-49f6-569c-3a11779305ff"",
		""AcceptorName"": ""黄小祝"",
		""AcceptorStaffNo"": """",
		""AcceptorOrgCode"": null,
		""AcceptorOrgName"": ""市民热线服务中心"",
		""CounterSignType"": null,
		""CounterSignTypeText"": ""未会签"",
		""SignerId"": ""48ba88f3-fd71-49f6-569c-3a11779305ff"",
		""SignerName"": ""黄小祝"",
		""CreationTime"": ""2024-10-16T10:06:34.416222"",
		""ContactMask"": ""183****0827"",
		""SmsSendedText"": ""已发送"",
		""Password"": ""361644"",
		""WorkflowId"": ""08dced87-314a-4a7f-8000-067f0035e290"",
		""Workflow"": null,
		""FromGenderText"": ""女士"",
		""IdentityTypeText"": ""市民"",
		""EmergencyLevel"": 0,
		""CanEdit"": false,
		""CanSign"": false,
		""CountersignId"": null,
		""IsCanDelay"": false,
		""IsCanCancelDelay"": false,
		""DelayString"": null,
		""CanPrevious"": false,
		""CanHandle"": false,
		""PreviousOpinion"": null,
		""CanInsteadHandle"": false,
		""DelayingCount"": 0,
		""IsUrgent"": false,
		""IsUrgentText"": """",
		""PublishState"": null,
		""DelayText"": ""否"",
		""SpecialNum"": 0,
		""DaysOverdue"": ""超期-7.0天"",
		""DaysOverdueOrgName"": null,
		""OrderExtension"": {
			""Id"": ""08dced87-2901-4140-8a7f-20720b976621"",
			""CreationTime"": ""2024-10-16T10:06:34.436904"",
			""ProvinceNo"": null,
			""OrderType"": null,
			""OrderTypeCode"": null,
			""LicenceTypeCode"": null,
			""LicenceType"": null,
			""LicenceNo"": null,
			""IdentityTypeCode"": null,
			""IdentityType"": null,
			""IdentityCode"": null,
			""Identity"": null,
			""NationalityCode"": null,
			""Nationality"": null,
			""NationCode"": null,
			""Nation"": null,
			""PostalCode"": null,
			""Email"": null,
			""OtherContact"": null,
			""EnterpriseName"": null,
			""UnifiedSocialCreditCode"": null,
			""RegisterAddress"": null,
			""RegisterNumber"": null,
			""EnterpriseContact"": null,
			""MarketTypeCode"": null,
			""MarketType"": null,
			""IndustryClassifyCode"": null,
			""IndustryClassify"": null,
			""BrandCode"": null,
			""Brand"": null,
			""Amount"": null,
			""ObjectClassifyCode"": null,
			""ObjectClassify"": null,
			""SalesModeCode"": null,
			""SalesMode"": null,
			""ECommercePlatformCode"": null,
			""ECommercePlatform"": null,
			""ExternalOrderNo"": null,
			""SalesChannel"": null,
			""SalesChannelCode"": null,
			""Patentee"": null,
			""PatentName"": null,
			""PatentTypeCode"": null,
			""PatentType"": null,
			""PatentNo"": null,
			""ProductName"": null,
			""ApprovalNumber"": null,
			""ProductBatchNo"": null,
			""ProductStandard"": null,
			""ProductExpiredTime"": null,
			""Manufacturer"": null,
			""SalesEnterprise"": null,
			""ConsumerAddress"": null,
			""ComplainClassifyCode"": null,
			""ComplainClassify"": null,
			""OccurrenceTime"": null,
			""ComplainTargetCode"": null,
			""ComplainTarget"": null,
			""BusinessPosition"": null,
			""ComplainTypes"": [],
			""ReportClassifyCode"": null,
			""ReportClassify"": null,
			""ReportTargetCode"": null,
			""ReportTarget"": null,
			""MedName"": null,
			""MedAddress"": null,
			""MedDepartment"": null,
			""MedDoctor"": null,
			""MedPatient"": null,
			""MedNo"": null,
			""MedIdNo"": null,
			""ExchTv"": null,
			""ExchTradeTime"": null,
			""ExchProduct"": null,
			""ExchAmount"": null,
			""ExchName"": null,
			""ExchAddress"": null,
			""ExchConsignee"": null,
			""ExchConsigneeAddress"": null,
			""AdTv"": null,
			""AdProduct"": null,
			""AdContent"": null,
			""ExpwyEntrance"": null,
			""ExpwyExit"": null,
			""ExpwyTime"": null,
			""ExpwyNo"": null,
			""ZwfwwAccount"": null,
			""ZwfwwContact"": null,
			""Location12366Sq"": null,
			""Info12366Sq"": null,
			""Type12366Sq"": null,
			""Location12366Zx"": null,
			""Info12366Zx"": null,
			""AcceptType12328"": null,
			""Client12328"": null,
			""MailClaimantName"": null,
			""MailClaimantPhone"": null,
			""MailClaimantEnterprise"": null,
			""MailSenderName"": null,
			""MailSenderPhone"": null,
			""MailSenderAddress"": null,
			""MailReceiverName"": null,
			""MailReceiverPhone"": null,
			""MailReceiverAddress"": null,
			""MailAmount"": null,
			""MailIsContacted"": null,
			""MailResult"": null,
			""EpEmail"": null,
			""EpAddress"": null,
			""EpObject"": null,
			""EpObjectAddress"": null,
			""EpIndustryType"": null,
			""EpKeyPoint"": null
		},
		""Hotspot"": {
			""HotSpotName"": ""预付卡消费纠纷"",
			""ParentId"": ""0322"",
			""PYCode"": null,
			""FullPYCode"": null,
			""ProvinceCode"": ""032201"",
			""OrderBy"": 0,
			""TrunkNum"": ""12345"",
			""HotSpotFullName"": ""市场管理-消费纠纷-预付卡消费纠纷""
		},
		""OrderDelays"": null,
		""OrderScreens"": null,
		""RepeatableEventDetails"": [],
		""OrderVisits"": null,
		""FileJson"": null,
		""RecordingBaseAddress"": null,
		""RecordingAbsolutePath"": null,
		""ReTransactNum"": 0,
		""Sensitive"": [],
		""SensitiveText"": """",
		""IsProvinceText"": ""市工单"",
		""IsResolved"": false,
		""IsResolvedText"": ""未解决"",
		""AuditUserName"": null,
		""AuditUserId"": null,
		""AuditTime"": ""0001-01-01T00:00:00"",
		""OverDays"": ""0天"",
		""CenterOpinion"": null,
		""SendBackOpinion"": null,
		""SendBackRefuseOpinion"": null,
		""SendBackAuditTime"": null,
		""OrderRemarks"": null,
		""CenterToOrgHandlerId"": null,
		""CenterToOrgHandlerName"": null,
		""IsReturnUnderApproval"": false,
		""SendBackAuditEndTime"": null,
		""Id"": ""08dced87-2901-4140-8a7f-20720b976621"",
		""SourceChannel"": ""电话"",
		""SourceChannelCode"": ""RGDH"",
		""CallId"": ""b9f57d0e-8b61-11ef-a9ca-3faa498d6f56"",
		""CallAddress"": null,
		""FromPhone"": ""18383170827"",
		""TransferPhone"": ""12315"",
		""FromName"": ""陶女士"",
		""FromGender"": 0,
		""IdentityType"": 1,
		""LicenceTypeCode"": null,
		""LicenceType"": null,
		""LicenceNo"": null,
		""AgeRangeCode"": null,
		""AgeRange"": null,
		""Contact"": ""18383170827"",
		""AcceptSms"": true,
		""SmsSended"": true,
		""IsSecret"": false,
		""Company"": null,
		""AcceptType"": ""投诉"",
		""AcceptTypeCode"": ""35"",
		""Title"": ""投诉婚庆公司不退定金"",
		""OrderTag"": null,
		""OrderTagCode"": null,
		""HotspotId"": ""032201"",
		""HotspotName"": ""预付卡消费纠纷"",
		""HotspotSpliceName"": ""市场管理-消费纠纷-预付卡消费纠纷"",
		""HotspotExternal"": ""0322,03"",
		""EventCategoryId"": ""032201"",
		""EventCategoryName"": ""预付卡消费纠纷"",
		""EventCategorySpliceName"": ""市场管理-消费纠纷-预付卡消费纠纷"",
		""EventCategoryExternal"": ""0322,03"",
		""IncidentTime"": null,
		""IncidentPurpose"": null,
		""DuplicateIds"": [],
		""PushTypeCode"": null,
		""PushType"": null,
		""Additions"": [],
		""Content"": "" 陶女士来电反映：8月，其在翠屏区上江北岷江西路恒大御景半岛商业街路花田喜事缴纳了3800元的定金，婚庆公司伪造其签名签署了庆典协议服务合同，并且定金收取超过了总金额20%，合同内容也并未给其解释，也没有开具定金发票，故其要求婚庆公司退还定金，但婚庆公司拒绝退还定金，其认为不合理。 希望退还定金。"",
		""Source"": 0,
		""Files"": [],
		""EnterpriseName"": null,
		""EnterpriseCode"": null,
		""ZhuanBanMingCheng"": null,
		""ZhuanBanCode"": null,
		""IsProvince"": false,
		""ProvinceNo"": ""RGDH9951150024101650402"",
		""ReceiveProvinceNo"": null,
		""ExpiredTimeProvince"": null,
		""ExternalId"": null,
		""ExpiredTime"": ""2024-10-23T10:06:48.105929"",
		""NearlyExpiredTime"": ""2024-10-22T10:06:48.105929"",
		""NearlyExpiredTimeOne"": ""2024-10-19T10:06:48.105929"",
		""TimeLimit"": ""5个工作日"",
		""TimeLimitCount"": 5,
		""TimeLimitUnit"": 2,
		""Transpond"": false,
		""TranspondCityId"": null,
		""TranspondCityName"": null,
		""TranspondCityValue"": null,
		""IsEnforcementOrder"": false,
		""IsFormalistWorkOrder"": false,
		""IsSensitiveWorkOrders"": false,
		""Is24HoursComplete"": false,
		""FocusOnEvents"": null,
		""IsThreePartyConference"": false,
		""IsProvinceZmhd"": false,
		""AuditFirstName"": null,
		""AuditFirstTime"": null,
		""OrderProvinceZmhdId"": null,
		""OrderPushTypes"": null,
		""Longitude"": null,
		""Latitude"": null,
		""AreaCode"": ""511502"",
		""Province"": null,
		""City"": ""宜宾市"",
		""County"": ""翠屏区"",
		""Town"": """",
		""Street"": ""上江北岷江西路恒大御景半岛商业街路花田喜事"",
		""Address"": ""宜宾市翠屏区"",
		""FullAddress"": ""宜宾市翠屏区上江北岷江西路恒大御景半岛商业街路花田喜事""
	},
	""WorkflowTrace"": {
		""Id"": ""08dced87-314b-4437-8d5e-878b6c05735d"",
		""StepId"": ""08dced87-314b-4437-8d5e-878b6c05735d"",
		""TraceType"": 1,
		""TraceTypeText"": ""正常流转"",
		""ExpiredTime"": ""0001-01-01T00:00:00"",
		""ParentId"": null,
		""SendHandleTimes"": 0,
		""Traces"": null,
		""Files"": null,
		""ExpiredStatus"": 1,
		""ExpiredStatusText"": ""办理完成-未超期"",
		""WorkflowId"": ""08dced87-314a-4a7f-8000-067f0035e290"",
		""Handlers"": [{
			""Key"": ""48ba88f3-fd71-49f6-569c-3a11779305ff"",
			""Value"": ""黄小祝""
		}],
		""TimeLimit"": null,
		""PrevChosenStepCode"": null,
		""AcceptorId"": ""48ba88f3-fd71-49f6-569c-3a11779305ff"",
		""AcceptorName"": ""黄小祝"",
		""AcceptorOrgId"": ""001"",
		""AcceptorOrgName"": ""市民热线服务中心"",
		""AcceptorOrgAreaCode"": ""511500"",
		""AcceptorOrgAreaName"": ""宜宾市"",
		""AcceptTime"": ""2024-10-16T10:06:48.3152078+08:00"",
		""HandlerId"": ""48ba88f3-fd71-49f6-569c-3a11779305ff"",
		""HandlerName"": ""黄小祝"",
		""HandlerOrgId"": ""001"",
		""HandlerOrgName"": ""市民热线服务中心"",
		""HandlerOrgAreaCode"": ""511500"",
		""HandlerOrgAreaName"": ""宜宾市"",
		""HandleTime"": ""2024-10-16T10:06:48.3152086+08:00"",
		""Name"": ""话务部"",
		""Code"": ""start"",
		""StepType"": 1,
		""BusinessType"": 0,
		""HandlerType"": 0,
		""CanReject"": false,
		""ExecuteMode"": 0,
		""CanStartCountersign"": false,
		""CountersignPolicy"": null,
		""InstanceMode"": 0,
		""InstancePolicy"": null,
		""TerminalDynamicMark"": null,
		""Tag"": """",
		""NextHandlers"": [{
			""Key"": ""807d58fb-f3bc-32c5-2f73-3a117792fbfd"",
			""Value"": ""官越""
		}],
		""NextMainHandler"": """",
		""NextStepCode"": ""c986ab87-1508-493a-81e9-9b7681240bd8"",
		""BackToCountersignEnd"": false,
		""IsSms"": false,
		""Opinion"": ""1"",
		""FileJson"": null,
		""StepExpiredTime"": ""2024-10-23T10:06:48.1059298+08:00"",
		""Handler"": ""黄小祝""
	},
	""TrCallRecordDto"": {
		""Id"": ""08dced86-9574-4fad-8075-5eae42415474"",
		""RecordingFileUrl"": ""http://127.0.0.1:29003/assets/recording/20241016/1041-18383170827-b9f57d0e-8b61-11ef-a9ca-3faa498d6f56.mp3"",
		""RecordingBaseAddress"": ""http://127.0.0.1:29003"",
		""RecordingAbsolutePath"": ""/assets/recording/20241016/1041-18383170827-b9f57d0e-8b61-11ef-a9ca-3faa498d6f56.mp3"",
		""CallDirection"": 0,
		""CallDirectionText"": ""来电"",
		""EndBy"": 1,
		""EndByText"": ""被叫方结束"",
		""CallAccept"": ""c21084b6-8b61-11ef-aa33-3faa498d6f56"",
		""CPN"": ""18383170827"",
		""CPNName"": ""18383170827"",
		""CDPN"": ""1041"",
		""TelNo"": ""1041"",
		""UserId"": ""48ba88f3-fd71-49f6-569c-3a11779305ff"",
		""UserName"": ""黄小祝"",
		""RecordingFileName"": ""/soft/ocean/ocean/www/assets/recording/20241016/1041-18383170827-b9f57d0e-8b61-11ef-a9ca-3faa498d6f56.mp3"",
		""CreatedTime"": ""2024-10-16T09:55:45"",
		""AnsweredTime"": ""2024-10-16T09:55:48"",
		""OverTime"": ""2024-10-16T10:02:15"",
		""Gateway"": ""12315"",
		""OtherStr"": null,
		""OtherAccept"": ""b9f57d0e-8b61-11ef-a9ca-3faa498d6f56"",
		""Status"": ""16"",
		""BeginIvrTime"": ""2024-10-16T09:55:32"",
		""EndIvrTime"": ""2024-10-16T09:55:42"",
		""BeginQueueTime"": ""2024-10-16T09:55:45"",
		""EndQueueTime"": ""2024-10-16T09:55:45"",
		""BeginRingTime"": ""2024-10-16T09:55:45"",
		""EndRingTimg"": ""2024-10-16T09:55:48"",
		""OlaQueue"": ""10095"",
		""BatchAccept"": null,
		""IvrDtmf"": ""1"",
		""DtmfType"": ""%E8%BD%AC%E5%91%BC%E5%85%A5%E7%BB%84"",
		""Duration"": 387,
		""RingTimes"": 3,
		""QueueTims"": 0,
		""OnState"": 1,
		""OnStateText"": ""接通"",
		""CallOrderType"": 1,
		""ExternalId"": ""08dced87-2901-4140-8a7f-20720b976621"",
		""Order"": null,
		""MobileAreaName"": null,
		""OFlag"": null,
		""OperatorName"": null,
		""TransliterationContent"": null,
		""TransliterationState"": 0,
		""TransliterationStateText"": ""未开始"",
		""TransliterationId"": null
	}
}";

            var data = System.Text.Json.JsonSerializer.Deserialize<PublishCallRecrodDto>(sss);

            await _capPublisher.PublishAsync(EventNames.HotlineOrderFlowStarted, data,
                           cancellationToken: HttpContext.RequestAborted);

            return null;
            //var data= await _configurationInformationCache.GetAsync(GetSetTypedCacheKey, HttpContext.RequestAborted);
            //return data;
        }
        [HttpGet("testsend")]
        [AllowAnonymous]
        public async Task testsend(string no, string pwd)
        {
            var strUrl = "http://localhost:6028/yb12345/iyb.asmx/GetDayCount";// "http://10.10.110.195:8182/yb12345/iyb.asmx/GetOrderByListOpen";
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("Code", 123456);                                                                                //请求Code
                                                                                                                    //dic.Add("CurrentPage", 1);                                             //工单编号
                                                                                                                    //dic.Add("PageSize", 500);      //承办意见
            var sss = await _fwClient.RequestNoTokenAsync<string>(strUrl, "POST", System.Text.Json.JsonSerializer.Serialize(dic), HttpContext.RequestAborted);
            var strResult = e_SendHttpPostBySync(strUrl, dic);

        }

        /// <summary>
        /// POST 提交数据
        /// </summary>
        /// <param name="strUrl"> 地址</param>
        /// <param name="headers">参数</param>
        /// <param name="strEncoding"></param>
        /// <param name="strContentType"></param>
        /// <returns></returns>
        private string e_SendHttpPostBySync(string strUrl, Dictionary<string, object> headers = null, string strEncoding = "UTF-8",
            string strContentType = "application/x-www-form-urlencoded")
        {
            // 返回数据
            string strResult = "";

            try
            {
                ServicePointManager.Expect100Continue = false;
                string postDataStr = SerializeDictionaryToParam2(headers);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
                request.Method = "POST";
                request.ContentType = strContentType;
                request.ContentLength = postDataStr.Length;

                StreamWriter write = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
                write.Write(postDataStr);
                write.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = "UTF-8";
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                strResult = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                strResult = "";
            }
            finally
            {
            }
            return strResult;
        }
        private string SerializeDictionaryToParam2<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            string strParam = "";
            int nIndex = 0;
            foreach (var item in dict)
            {
                if (0 == nIndex)
                    strParam += item.Key + "=" + item.Value;
                else
                    strParam += "&" + item.Key + "=" + item.Value;
                nIndex++;
            }
            return strParam;
        }




    }
}
