using DataSharing.HotlineWeb;
using DataSharing.Province.SendTask.SubmitCaseRecord;
using DataSharing.RawData;
using DataSharing.SendTask;
using DataSharing.Share.Consts;
using DataSharing.Share.Dtos.HotlineWeb;
using DataSharing.Share.Dtos.Province;
using DataSharing.Share.Dtos.Province.Extend;
using DataSharing.Share.Dtos.Province.HuiJu;
using DataSharing.Share.Dtos.Province.XieTong.Knowledge;
using DataSharing.Share.Dtos.Province.XieTong.Receive;
using DataSharing.Share.Dtos.Province.XieTong.Send;
using DataSharing.Share.Enums;
using DataSharing.Validators.HuiJu;
using DataSharing.Validators.XieTong;
using DataSharing.ZiGong;
using DotNetCore.CAP;
using Hotline.Share.Dtos.CallCenter;
using Hotline.Share.Dtos.File;
using Hotline.Share.Dtos.Knowledge;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace DataSharing.Province
{
    /// <summary>
    /// 省推送数据
    /// </summary>
    public class ProvinceService : IProvinceService, IScopeDependency
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly ILogger<ProvinceService> _logger;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly IRepository<DsOrderWorkFlow> _dataOrderWorkFlowRepository;
        private readonly IRepository<DsKnowledgeRawData> _knowledgeRawDataRepository;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly IRepository<DsSendCaseInfo> _sendCaseInfoRepository;
        private readonly ITypedCache<MissedCallModelDto> _missedCallModelCache;
        private readonly string MissedCallKey = "missedCallKey_";
        private readonly IRepository<DsOrderVisit> _dsOrderVisitRepository;
        private readonly IRepository<DsGetCaseBackApply> _getCaseBackApplyRepository;
        private readonly ICapPublisher _capPublisher;
        private readonly IRepository<DsTelCall> _dsTelCallRepository;
        private readonly ITypedCache<ConfigurationInformationDto> _configurationInformationCache;
        private readonly IRepository<DsOrderVisitSend> _dsOrderVisitSendRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IInitPushDataService _initPushDataService;
        private readonly IRepository<DsGetCaseMaterialInfo> _getCaseMaterialInfoRepository;
        private readonly IRepository<ConfigurationInformation> _configurationInformationRepository;
        private readonly IRepository<DsSendTaskSubmitCaseRecord> _sendTaskSubmitCaseRecordRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="dsOrderRepository"></param>
        /// <param name="dataOrderWorkFlowRepository"></param>
        /// <param name="knowledgeRawDataRepository"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="sendCaseInfoRepository"></param>
        /// <param name="missedCallModelCache"></param>
        /// <param name="dsOrderVisitRepository"></param>
        /// <param name="getCaseBackApplyRepository"></param>
        /// <param name="capPublisher"></param>
        /// <param name="dsTelCallRepository"></param>
        /// <param name="configurationInformationCache"></param>
        /// <param name="dsOrderVisitSendRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="initPushDataService"></param>
        /// <param name="getCaseMaterialInfoRepository"></param>
        public ProvinceService(IMapper mapper,
            ILogger<ProvinceService> logger,
             IRepository<DsOrder> dsOrderRepository,
             IRepository<DsOrderWorkFlow> dataOrderWorkFlowRepository,
             IRepository<DsKnowledgeRawData> knowledgeRawDataRepository,
             IChannelConfigurationManager channelConfigurationManager,
             IRepository<DsSendCaseInfo> sendCaseInfoRepository,
             ITypedCache<MissedCallModelDto> missedCallModelCache,
             IRepository<DsOrderVisit> dsOrderVisitRepository,
             IRepository<DsGetCaseBackApply> getCaseBackApplyRepository,
             ICapPublisher capPublisher,
             IRepository<DsTelCall> dsTelCallRepository,
             ITypedCache<ConfigurationInformationDto> configurationInformationCache,
             IRepository<DsOrderVisitSend> dsOrderVisitSendRepository,
             ISharingConfigurationManager sharingConfigurationManager,
             IInitPushDataService initPushDataService,
             IRepository<DsGetCaseMaterialInfo> getCaseMaterialInfoRepository,
             IRepository<ConfigurationInformation> configurationInformationRepository,
             IRepository<DsSendTaskSubmitCaseRecord> sendTaskSubmitCaseRecordRepository)
        {
            _mapper = mapper;
            _logger = logger;
            _dsOrderRepository = dsOrderRepository;
            _dataOrderWorkFlowRepository = dataOrderWorkFlowRepository;
            _knowledgeRawDataRepository = knowledgeRawDataRepository;
            _channelConfigurationManager = channelConfigurationManager;
            _sendCaseInfoRepository = sendCaseInfoRepository;
            _missedCallModelCache = missedCallModelCache;
            _dsOrderVisitRepository = dsOrderVisitRepository;
            _getCaseBackApplyRepository = getCaseBackApplyRepository;
            _capPublisher = capPublisher;
            _dsTelCallRepository = dsTelCallRepository;
            _configurationInformationCache = configurationInformationCache;
            _dsOrderVisitSendRepository = dsOrderVisitSendRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
            _initPushDataService = initPushDataService;
            _getCaseMaterialInfoRepository = getCaseMaterialInfoRepository;
            _configurationInformationRepository = configurationInformationRepository;
            _sendTaskSubmitCaseRecordRepository = sendTaskSubmitCaseRecordRepository;
        }
        #endregion

        #region 协同-第一批次---已处理

        /// <summary>
        /// 退回申请
        /// </summary>
        /// <param name="dtos"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task GetCaseBackApplyAsync(PublishOrderSendBackDto dtos, CancellationToken cancellationToken)
        {
            //验证数据
            foreach (var dto in dtos.SendDatas)
            {
                var validator = new GetCaseBackApplyValidator();
                var validResult = await validator.ValidateAsync(dto, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
            }

            foreach (var dto in dtos.SendDatas)
            {
                if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.Source == ESource.ProvinceStraight || dto.Order.AreaCode.Contains("519"))
                    dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

                //处理省上的退回申请
                if (dto.Order.Source == ESource.ProvinceStraight)
                {
                    var data = _mapper.Map<GetCaseBackApplyInfo>(dto);
                    data.CliengGuid = dto.SendBack.Id;
                    data.BackType = "1";
                    var tempData = _mapper.Map<DsGetCaseBackApply>(data);
                    tempData.OrderSendBackId = dto.SendBack.Id;

                    var backId = await _getCaseBackApplyRepository.AddAsync(tempData, cancellationToken);
                    if (!string.IsNullOrEmpty(backId))
                    {
                        #region 处理请求参数
                        var configProvince = _channelConfigurationManager.GetConfigurationProvince();
                        var request = new ProvinceRequest<GetCaseBackApplyInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
                        request.SetData(data);
                        var jsonData = request.ToString();
                        #endregion

                        //将待推送数据写入待推送表
                        await _initPushDataService.InitDsSendTaskProvinceOther("GetCaseBackApply", "get_case_back_apply", data.CaseSerial,
               jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong, generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

                        //处理附件
                        await FileDataAsync(dto.SendBack.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Process, dto.Order.AreaCode, cancellationToken: cancellationToken);
                    }
                }
            }
        }

        /// <summary>
        /// 服务工单督办过程
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SendSuperviseProcessInfoAsync(PublishSuperviseDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.Source == ESource.ProvinceStraight || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            var validator = new SendSuperviseProcessInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<SendSuperviseProcessInfo>(dto);

            data.ReplyOpinion = "已签收";

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SendSuperviseProcessInfo", "send_supervise_process_info", dto.Order.ReceiveProvinceNo,
             jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
             generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 服务工单督办结果
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SendSuperviseResultInfoAsync(PublishSuperviseDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.Source == ESource.ProvinceStraight || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            var validator = new SendSuperviseResultInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<SendSuperviseResultInfo>(dto);
            data.CliengGuid = dto.Supervise.Id;

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SendSuperviseResultInfo", "send_supervise_result_info", dto.Order.ReceiveProvinceNo,
             jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
             generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

            //处理附件
            await FileDataAsync(dto.Supervise.FileJson, dto.Order.ReceiveProvinceNo, data.CliengGuid, EMaterialType.Supervise, dto.Order.AreaCode, cancellationToken);

        }

        /// <summary>
        /// 工单发起甄别
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task ScreenCaseInfoSendAsync(PublishScreenDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.Source == ESource.ProvinceStraight || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            var validator = new ScreenCaseInfoSendInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<ScreenCaseInfoSendInfo>(dto);
            data.CliengGuid = Guid.NewGuid().ToString();
            data.ApplyType = dto.Screen.TypeDicName switch
            {
                "违反法律法规" => "10",
                "按正常流程处理" => "20",
                _ => "30",
            };

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("ScreenCaseInfoSend", "screen_case_info_send", data.CaseSerial,
            jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
            generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

            //处理附件
            await FileDataAsync(dto.Screen.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Process, dto.Order.AreaCode, cancellationToken: cancellationToken);

        }

        /// <summary>
        /// 服务工单申请延时
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task DelayCaseInfoSendAsync(PublishOrderDelayDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.Source == ESource.ProvinceStraight || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            var validator = new DelayCaseInfoSendInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<DelayCaseInfoSendInfo>(dto);
            data.CliengGuid = dto.Id;
            data.ApplyType = "1";

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("DelayCaseInfoSend", "delay_case_info_send", data.CaseSerial,
             jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
             generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

            //处理附件
            await FileDataAsync(dto.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Process, data.AreaCode, cancellationToken);
        }

        #endregion

        #region 汇聚-第二批次

        /// <summary>
        /// 热线工单流程开启
        /// </summary>
        /// <param name="pushdto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task OrderFlowStartedAsync(PublishCallRecrodDto pushdto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(pushdto.Order.AreaCode) || pushdto.Order.AreaCode.Contains("519"))
                pushdto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            var dto = pushdto.Order;

            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            //如果不是省上派下来的工单，需要汇聚到省上
            if (dto is not null && !dto.IsProvince)
            {
                ////先上传拓展信息
                //if (dto.OrderExtension != null)
                //    await SubmitCaseExtendsAsync(dto, cancellationToken);

                var data = InitDataAsync(dto);
                var validator = new SubmitCaseInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

                #region 处理请求参数
                var request = new ProvinceListRequest<SubmitCaseInfo>(configProvince.ClientId, configProvince.ClientSecret);
                request.SetData(new List<SubmitCaseInfo>() { data });
                var jsonData = request.ToString();
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskSubmitCaseInfo(dto.Id, data.CaseSerial, jsonData, data, pushdto.Order.StartTime, cancellationToken);

                //处理附件
                await FileDataAsync(dto.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Acceptance, data.AreaCode, cancellationToken);
            }

            //推送当前办理信息
            //  await SubmitCaseProcessFlowAsync(new OrderFlowDto { Order = pushdto.Order, WorkflowTrace = pushdto.WorkflowTrace, ExpiredTimeChanged = false }, cancellationToken);

            //再次推送通话记录
            if (pushdto.TrCallRecordDto is not null)
            {
                if (pushdto.TrCallRecordDto.OnState == EOnState.On && string.IsNullOrEmpty(pushdto.TrCallRecordDto.RecordingFileUrl))
                    return;

                //如果推送工单的时候判断通话记录是否是未接，并且是否已经上传，如果没有咋补再次推送通话记录
                var tellCall = await _dsTelCallRepository.AnyAsync(p => p.CallId == pushdto.TrCallRecordDto.OtherAccept, cancellationToken);
                if (pushdto.TrCallRecordDto.OnState == EOnState.NoOn && !tellCall)
                    return;
                //如果是正常通话记录,没有上传过
                if (tellCall == false)
                {
                    //如果挂机时间到现在超过了285秒就不在上传通话记录
                    TimeSpan timeDifference = DateTime.Now - pushdto.TrCallRecordDto.OverTime;
                    double secondsDifference = timeDifference.TotalSeconds;
                    if (secondsDifference > 285)
                        return;
                }

                var dataCall = _mapper.Map<SubmitCaseRecordInfo>(pushdto.TrCallRecordDto);
                dataCall.AreaCode = dto.AreaCode.Length > 6 ? dto.AreaCode.Substring(0, 6) : dto.AreaCode;
                dataCall.CaseSerial = dto.ProvinceNo;
                if (string.IsNullOrEmpty(dataCall.AccordUrl))
                    dataCall.AccordUrl = "";

                //处理通话记录时间
                SetCallTime(dataCall);

                var validator = new SubmitCaseRecordInfoValidator();
                var validResult = await validator.ValidateAsync(dataCall, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var requestCall = new ProvinceListRequest<SubmitCaseRecordInfo>(configProvince.ClientId, configProvince.ClientSecret);
                requestCall.SetData(new List<SubmitCaseRecordInfo>() { dataCall });
                var jsonDataCall = requestCall.ToString();
                jsonDataCall = jsonDataCall.Replace("0001-01-01 00:00:00", "");
                //将待推送数据写入待推送表
                var taskId = await _initPushDataService.InitDsSendTaskSubmitCaseRecord(dataCall.CaseSerial, pushdto.TrCallRecordDto.OtherAccept, pushdto.TrCallRecordDto.Id, jsonDataCall, dataCall, pushdto.TrCallRecordDto.OverTime, cancellationToken);

                //本地保存通话记录数据
                await InitTelCallData(pushdto.TrCallRecordDto, dto.ProvinceNo, taskId, cancellationToken);
                #endregion
            }
        }

        /// <summary>
        /// 热线工单期满时间变更--推送服务工单受理
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task HotlineOrderFlowRecalledAsync(OrderDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.AreaCode) || dto.AreaCode.Contains("519"))
                dto.AreaCode = _sharingConfigurationManager.GetCityCode();

            //如果不是省上派下来的工单，需要汇聚到省上
            if (!dto.IsProvince)
            {
                var data = InitDataAsync(dto);
                var validator = new SubmitCaseInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var configProvince = _channelConfigurationManager.GetConfigurationProvince();
                var request = new ProvinceListRequest<SubmitCaseInfo>(configProvince.ClientId, configProvince.ClientSecret);
                request.SetData(new List<SubmitCaseInfo>() { data });
                var jsonData = request.ToString();
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskSubmitCaseInfo(dto.Id, data.CaseSerial, jsonData, data, dto.StartTime, cancellationToken);
            }

        }

        /// <summary>
        /// 热线工单办理---服务工单处理/服务工单交办处理过程
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SubmitCaseProcessAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (string.IsNullOrEmpty(dto.WorkflowTrace.HandlerOrgAreaCode))
            {
                dto.WorkflowTrace.HandlerOrgAreaCode = dto.Order.AreaCode;
                if (dto.WorkflowTrace.HandlerOrgAreaCode.Length > 6)
                    dto.WorkflowTrace.HandlerOrgAreaCode = dto.WorkflowTrace.HandlerOrgAreaCode.Substring(0, 6);
            }

            await SubmitCaseProcessFlowAsync(dto, cancellationToken);
            //期满时间变更或者办理节点为话务部，重新推送数据
            if ((dto.ExpiredTimeChanged || dto.Order.ActualHandleStepName == "话务部") && !dto.Order.IsProvince)
            {
                var submitCaseInfo = InitDataAsync(dto.Order);
                var validator = new SubmitCaseInfoValidator();
                var validResult = await validator.ValidateAsync(submitCaseInfo, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var configProvince = _channelConfigurationManager.GetConfigurationProvince();
                var requestSubmitCaseInfo = new ProvinceListRequest<SubmitCaseInfo>(configProvince.ClientId, configProvince.ClientSecret);
                requestSubmitCaseInfo.SetData(new List<SubmitCaseInfo>() { submitCaseInfo });
                var jsonDataSubmitCaseInfo = requestSubmitCaseInfo.ToString();
                var urlSubmitCaseInfo = configProvince.HuiJu + "submit_case_info";
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskSubmitCaseInfo(dto.Order.Id, submitCaseInfo.CaseSerial, jsonDataSubmitCaseInfo, submitCaseInfo, dto.Order.StartTime, cancellationToken);
                //如果话务部派出去，再次上传附件
                if (dto.Order.ActualHandleStepName == "话务部")
                {
                    //处理附件
                    await FileDataAsync(dto.Order.FileJson, submitCaseInfo.CaseSerial, submitCaseInfo.CliengGuid, EMaterialType.Acceptance, submitCaseInfo.AreaCode, cancellationToken);
                }
            }
        }

        /// <summary>
        /// 补充流程节点附件
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SupplementFilesAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            if (dto != null && dto.WorkflowTrace != null && dto.WorkflowTrace.FileJson != null && dto.WorkflowTrace.FileJson.Any())
            {
                var areaCode = dto.Order.AreaCode.Length > 6 ? dto.Order.AreaCode.Substring(0, 6) : dto.Order.AreaCode;
                if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.AreaCode.Contains("519"))
                    areaCode = _sharingConfigurationManager.GetCityCode();

                ///如果是省上派下来的，直接将区域设置为系统市州
                if (dto.Order.Source == ESource.ProvinceStraight)
                    areaCode = _sharingConfigurationManager.GetCityCode();

                var orderNo = "";
                //省上下来的工单走协同的接口
                if (dto.Order.Source == ESource.ProvinceStraight)
                    orderNo = dto.Order.ReceiveProvinceNo;

                //如果不是省上派下来的工单或者省上来的工单，但是是政民互动直派的工单，需要推送已汇聚数据
                if (dto.Order.Source != ESource.ProvinceStraight || (dto.Order.Source == ESource.ProvinceStraight && dto.Order.IsProvince == false))
                    orderNo = dto.Order.ProvinceNo;

                //处理附件
                await FileDataAsync(dto.WorkflowTrace.FileJson, orderNo, dto.WorkflowTrace.Id, EMaterialType.Process, areaCode, cancellationToken);
            }
        }

        /// <summary>
        /// 服务工单回访评价/服务工单交办评价
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SubmitVisitInfoDataAsync(PublishVisitDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            dto.AreaCode = dto.Order.AreaCode.Length > 6 ? dto.Order.AreaCode.Substring(0, 6) : dto.Order.AreaCode;

            //存在更新，不存在新增
            var visitData = await _dsOrderVisitSendRepository.GetAsync(p => p.OrderId == dto.Order.Id, cancellationToken);
            if (visitData != null)
            {
                visitData.VisitType = dto.VisitType.ToString();
                visitData.VisitName = dto.VisitName;
                visitData.VisitTime = dto.VisitTime;
                visitData.VisitRemark = dto.VisitRemark;
                visitData.SubjectResultSatifyCode = dto.SubjectResultSatifyCode;
                await _dsOrderVisitSendRepository.UpdateAsync(visitData, cancellationToken);
            }
            else
            {
                ///写入推送数据表，用于统计满意度
                visitData = new()
                {
                    OrderId = dto.Order.Id,
                    OrderNo = dto.No,
                    ProvinceNo = dto.Order.ProvinceNo,
                    VisitType = dto.VisitType.ToString(),
                    VisitName = dto.VisitName,
                    VisitTime = dto.VisitTime,
                    VisitRemark = dto.VisitRemark,
                    SubjectResultSatifyCode = dto.SubjectResultSatifyCode,
                    IsProvince = dto.Order.IsProvince,
                    Source = dto.Order.Source.ToString()
                };
                await _dsOrderVisitSendRepository.AddAsync(visitData, cancellationToken);
            }

            var visitType = dto.VisitType switch
            {
                EVisitType.ArtificialVisit => "DH",
                EVisitType.SmsVisit => "DX",
                EVisitType.WebVisit => "WZ",
                EVisitType.WeChatVisit => "WX",
                EVisitType.AppVisit => "AP",
                _ => "DH",
            };

            //将未接通未做评价的默认为满意
            switch (dto.SubjectResultSatifyCode)
            {
                case "5":
                case "4":
                case "2":
                case "1":
                    break;
                case "-1":
                case "0":
                    dto.SubjectResultSatifyCode = "4";
                    break;
                case "6":
                case "7":
                    dto.SubjectResultSatifyCode = "3";
                    break;
                default:
                    dto.SubjectResultSatifyCode = "3";
                    break;
            }

            var configProvince = _channelConfigurationManager.GetConfigurationProvince();

            //如果省上下来的工单走服务工单交办评价接口
            if (dto.Order.Source == ESource.ProvinceStraight)
            {
                var data = _mapper.Map<GetVisitInfoReceiveInfo>(dto);

                data.VisitType = visitType;
                data.CliengGuid = Guid.NewGuid().ToString();
                var validator = new GetVisitInfoReceiveInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var request = new ProvinceRequest<GetVisitInfoReceiveInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
                request.SetData(data);
                var jsonData = request.ToString();
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskProvinceOther("GetVisitInfoReceive", "get_visit_info_receive", data.CaseSerial,
          jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
          generationTime: dto.Order.StartTime, visitTime: data.VisitTime, subjectResultSatify: data.SubjectResultSatify, cancellationToken: cancellationToken);

                //处理附件
                await FileDataAsync(null, data.CaseSerial, data.CliengGuid, EMaterialType.Visit, data.AreaCode, cancellationToken);
            }

            //如果不是省上派下来的工单或者省上来的工单，但是是政民互动直派的工单，需要推送已汇聚数据
            if (dto.Order.Source != ESource.ProvinceStraight || (dto.Order.Source == ESource.ProvinceStraight && dto.Order.IsProvince == false))
            {
                var data = _mapper.Map<SubmitVisitInfo>(dto);
                data.VisitType = visitType;
                data.CliengGuid = Guid.NewGuid().ToString();

                var validator = new SubmitVisitInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var request = new ProvinceListRequest<SubmitVisitInfo>(configProvince.ClientId, configProvince.ClientSecret);
                request.SetData(new List<SubmitVisitInfo>() { data });
                var jsonData = request.ToString();
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskProvinceOther("SubmitVisitInfo", "submit_visit_info", data.CaseSerial,
         jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu,
         generationTime: dto.Order.StartTime, visitTime: data.VisitTime, subjectResultSatify: data.SubjectResultSatify, cancellationToken: cancellationToken);

                //处理附件
                await FileDataAsync(null, data.CaseSerial, data.CliengGuid, EMaterialType.Visit, data.AreaCode, cancellationToken);

            }
        }

        /// <summary>
        /// 热线工单归档---服务工单结果/服务工单交办处理结果
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task OrderFiledAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (string.IsNullOrEmpty(dto.Order.ActualHandleOrgAreaCode))
            {
                dto.Order.ActualHandleOrgAreaCode = dto.Order.AreaCode;
                if (dto.Order.ActualHandleOrgAreaCode.Length > 6)
                    dto.Order.ActualHandleOrgAreaCode = dto.Order.ActualHandleOrgAreaCode.Substring(0, 6);
            }

            //先看看需要处理工单数据不
            SubmitCaseInfo data = new();
            if (dto != null && dto.Order != null && !dto.Order.IsProvince)
            {
                data = InitDataAsync(dto.Order);
                var validator = new SubmitCaseInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
            }

            //推送办理记录
            dto.ExpiredTimeChanged = false;

            //推送办理过程
            await SubmitCaseProcessFlowAsync(dto, cancellationToken);

            //判断是否是热线中心
            if (!string.IsNullOrEmpty(dto.Order.ActualHandleOrgCode) && dto.Order.ActualHandleOrgCode == "001")
                dto.Order.ActualHandleOrgName = "热线中心";
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();

            //IsProvince 如果是false 则推送服务工单受理
            if (dto != null && dto.Order != null && !dto.Order.IsProvince)
            {
                bool isDelay = false;
                //比较流程开启时间和归档时间，如果开启流程时间和归档时间间隔小于120秒，推送工单数据延迟2分钟
                if (dto.Order.StartTime.HasValue && dto.Order.FiledTime.HasValue)
                {
                    //计算时间差
                    TimeSpan timeDifference = dto.Order.FiledTime.Value - dto.Order.StartTime.Value;
                    double secondsDifference = timeDifference.TotalSeconds;
                    if (secondsDifference < 120)
                    {
                        //推送延迟消息
                        isDelay = true;
                        var time = DateTime.Now;
                        _capPublisher.PublishDelay(time.AddMinutes(2) - time, Hotline.Share.Mq.EventNames.HotlineOrderExpiredTimeUpdate, dto.Order);
                    }
                }

                //如果没有推送延迟消息那么就推送工单数据信息
                if (isDelay == false)
                {
                    #region 处理请求参数--推送工单数据

                    var request = new ProvinceListRequest<SubmitCaseInfo>(configProvince.ClientId, configProvince.ClientSecret);
                    request.SetData(new List<SubmitCaseInfo>() { data });
                    var jsonData = request.ToString();
                    #endregion

                    //将待推送数据写入待推送表
                    await _initPushDataService.InitDsSendTaskSubmitCaseInfo(dto.Order.Id, data.CaseSerial, jsonData, data, dto.Order.StartTime, cancellationToken);
                }

                //推送服务工单结果信息
                await SubmitCaseResultAsync(dto, cancellationToken);
            }

            //再次推送通话记录
            if (dto.TrCallRecordDto is not null)
            {
                if (dto.TrCallRecordDto.OnState == EOnState.On && string.IsNullOrEmpty(dto.TrCallRecordDto.RecordingFileUrl))
                    return;

                //如果推送工单的时候判断通话记录是否是未接，并且是否已经上传，如果没有则不再次推送通话记录
                var tellCall = await _sendTaskSubmitCaseRecordRepository.AnyAsync(p => p.CallId == dto.TrCallRecordDto.OtherAccept, cancellationToken);
                if (dto.TrCallRecordDto.OnState == EOnState.NoOn && !tellCall)
                    return;

                //如果是正常通话记录,没有上传过
                if (tellCall == false)
                {
                    //如果挂机时间到现在超过了285秒就不在上传通话记录
                    TimeSpan timeDifference = DateTime.Now - dto.TrCallRecordDto.OverTime;
                    double secondsDifference = timeDifference.TotalSeconds;
                    if (secondsDifference > 285)
                        return;
                }

                var dataCall = _mapper.Map<SubmitCaseRecordInfo>(dto.TrCallRecordDto);
                dataCall.AreaCode = dto.Order.AreaCode.Length > 6 ? dto.Order.AreaCode.Substring(0, 6) : dto.Order.AreaCode;
                dataCall.CaseSerial = dto.Order.ProvinceNo;
                if (string.IsNullOrEmpty(dataCall.AccordUrl))
                    dataCall.AccordUrl = "";

                //处理通话记录时间
                SetCallTime(dataCall);

                var validator = new SubmitCaseRecordInfoValidator();
                var validResult = await validator.ValidateAsync(dataCall, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var requestCall = new ProvinceListRequest<SubmitCaseRecordInfo>(configProvince.ClientId, configProvince.ClientSecret);
                requestCall.SetData(new List<SubmitCaseRecordInfo>() { dataCall });
                var jsonDataCall = requestCall.ToString();
                jsonDataCall = jsonDataCall.Replace("0001-01-01 00:00:00", "");
                //将待推送数据写入待推送表
                var taskId = await _initPushDataService.InitDsSendTaskSubmitCaseRecord(dataCall.CaseSerial, dto.TrCallRecordDto.OtherAccept, dto.TrCallRecordDto.Id, jsonDataCall, dataCall, dto.TrCallRecordDto.OverTime, cancellationToken);
                //本地保存通话记录数据
                await InitTelCallData(dto.TrCallRecordDto, dto.Order.ProvinceNo, taskId, cancellationToken);
                #endregion
            }

        }

        /// <summary>
        /// 挂电话推送----电话记录--丰窝最新
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SubmitCaseRecordFwAsync(CallNativeDto dto, CancellationToken cancellationToken)
        {
            //如果是呼出，没有通话录音文件，直接过滤
            if (dto != null && dto.Direction == ECallDirection.Out && string.IsNullOrEmpty(dto.AudioFile))
            {
                return;
            }
            //验证是否需要推送未接数据
            if (dto != null && dto.AnsweredTime == null && dto.Direction == ECallDirection.In)
            {
                if (await IsPublishMissedCall(dto.EndTime, cancellationToken) == false)
                    return;
            }

            var data = _mapper.Map<SubmitCaseRecordInfo>(dto);

            data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (string.IsNullOrEmpty(data.CaseSerial))
                data.CaseSerial = "";

            if (string.IsNullOrEmpty(data.AccordUrl))
                data.AccordUrl = "";

            //处理通话记录时间
            SetCallTime(data);
            var validator = new SubmitCaseRecordInfoValidator();
            var validResult = await validator.ValidateAsync(data, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseRecordInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseRecordInfo>() { data });
            var jsonData = request.ToString();
            jsonData = jsonData.Replace("0001-01-01 00:00:00", "");
            #endregion

            //将待推送数据写入待推送表
            var taskId = await _initPushDataService.InitDsSendTaskSubmitCaseRecord(data.CaseSerial, dto.Id, dto.Id, jsonData, data, dto.EndTime, cancellationToken);

            //本地保存通话记录数据
            await InitTelFwCallData(dto, data.CaseSerial, taskId, cancellationToken);
        }

        /// <summary>
        /// 推送通话记录未关联工单数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task AssociateCallRecords(PublishCallRecrodDto dto, CancellationToken cancellationToken)
        {
            if (dto.TrCallRecordDto.OnState == EOnState.On && string.IsNullOrEmpty(dto.TrCallRecordDto.RecordingFileUrl))
                return;

            //如果推送工单的时候判断通话记录是否是未接，并且是否已经上传，如果没有咋补再次推送通话记录
            var tellCall = await _sendTaskSubmitCaseRecordRepository.AnyAsync(p => p.CallId == dto.TrCallRecordDto.OtherAccept, cancellationToken);
            if (dto.TrCallRecordDto.OnState == EOnState.NoOn && false == tellCall)
                return;

            //如果是正常通话记录,没有上传过
            if (tellCall == false)
            {
                //如果挂机时间到现在超过了285秒就不在上传通话记录
                TimeSpan timeDifference = DateTime.Now - dto.TrCallRecordDto.OverTime;
                double secondsDifference = timeDifference.TotalSeconds;
                if (secondsDifference > 285)
                    return;
            }

            var data = _mapper.Map<SubmitCaseRecordInfo>(dto.TrCallRecordDto);
            if (dto.Order != null)
            {
                if (string.IsNullOrEmpty(dto.Order.AreaCode))
                    data.AreaCode = _sharingConfigurationManager.GetCityCode();
                else
                    data.AreaCode = dto.Order.AreaCode;

                if (!string.IsNullOrEmpty(dto.Order.ProvinceNo))
                    data.CaseSerial = dto.Order.ProvinceNo;
            }
            else
                data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (data.AreaCode.Contains("519"))
                data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (data.AreaCode.Length > 6)
                data.AreaCode = data.AreaCode.Substring(0, 6);

            if (string.IsNullOrEmpty(data.CaseSerial))
                data.CaseSerial = "";

            if (string.IsNullOrEmpty(data.AccordUrl))
                data.AccordUrl = "";

            //处理通话记录时间
            SetCallTime(data);
            var validator = new SubmitCaseRecordInfoValidator();
            var validResult = await validator.ValidateAsync(data, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseRecordInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseRecordInfo>() { data });
            var jsonData = request.ToString();
            jsonData = jsonData.Replace("0001-01-01 00:00:00", "");
            #endregion

            var startTime = dto.TrCallRecordDto.OverTime;
            //将待推送数据写入待推送表
            var taskId = await _initPushDataService.InitDsSendTaskSubmitCaseRecord(data.CaseSerial, dto.TrCallRecordDto.OtherAccept, dto.TrCallRecordDto.Id, jsonData, data, startTime, cancellationToken);

        }

        /// <summary>
        /// 挂电话推送----电话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SubmitCaseRecordAsync(PublishCallRecrodDto dto, CancellationToken cancellationToken)
        {
            //验证是否需要推送未接数据
            if (dto != null && dto.TrCallRecordDto != null && dto.TrCallRecordDto.OnState == EOnState.NoOn && dto.Order == null)
            {
                if (await IsPublishMissedCall(dto.TrCallRecordDto.OverTime, cancellationToken) == false)
                    return;
            }

            var data = _mapper.Map<SubmitCaseRecordInfo>(dto.TrCallRecordDto);
            if (dto.Order != null)
            {
                if (string.IsNullOrEmpty(dto.Order.AreaCode))
                    data.AreaCode = _sharingConfigurationManager.GetCityCode();
                else
                    data.AreaCode = dto.Order.AreaCode;

                if (!string.IsNullOrEmpty(dto.Order.ProvinceNo))
                    data.CaseSerial = dto.Order.ProvinceNo;
            }
            else
                data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (data.AreaCode.Contains("519"))
                data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (data.AreaCode.Length > 6)
                data.AreaCode = data.AreaCode.Substring(0, 6);

            if (string.IsNullOrEmpty(data.CaseSerial))
                data.CaseSerial = "";

            if (string.IsNullOrEmpty(data.AccordUrl))
                data.AccordUrl = "";

            //处理通话记录时间
            SetCallTime(data);
            var validator = new SubmitCaseRecordInfoValidator();
            var validResult = await validator.ValidateAsync(data, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseRecordInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseRecordInfo>() { data });
            var jsonData = request.ToString();
            jsonData = jsonData.Replace("0001-01-01 00:00:00", "");
            #endregion

            var startTime = dto.TrCallRecordDto.OverTime;
            //将待推送数据写入待推送表
            var taskId = await _initPushDataService.InitDsSendTaskSubmitCaseRecord(data.CaseSerial, dto.TrCallRecordDto.OtherAccept, dto.TrCallRecordDto.Id, jsonData, data, startTime, cancellationToken);

            //本地保存通话记录数据
            await InitTelCallData(dto.TrCallRecordDto, data.CaseSerial, taskId, cancellationToken);
        }

        /// <summary>
        /// 关联工单了推送----电话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SubmitCaseRecordOrderAsync(PublishCallRecrodDto dto, CancellationToken cancellationToken)
        {
            if (dto.TrCallRecordDto.OnState == EOnState.On && string.IsNullOrEmpty(dto.TrCallRecordDto.RecordingFileUrl))
                return;

            //如果推送工单的时候判断通话记录是否是未接，并且是否已经上传，如果没有咋补再次推送通话记录
            var tellCall = await _sendTaskSubmitCaseRecordRepository.AnyAsync(p => p.CallId == dto.TrCallRecordDto.OtherAccept, cancellationToken);
            if (dto.TrCallRecordDto.OnState == EOnState.NoOn && false == tellCall)
                return;

            //如果是正常通话记录,没有上传过
            if (tellCall == false)
            {
                //如果挂机时间到现在超过了285秒就不在上传通话记录
                TimeSpan timeDifference = DateTime.Now - dto.TrCallRecordDto.OverTime;
                double secondsDifference = timeDifference.TotalSeconds;
                if (secondsDifference > 285)
                    return;
            }

            var data = _mapper.Map<SubmitCaseRecordInfo>(dto.TrCallRecordDto);
            if (dto.Order != null)
            {
                if (string.IsNullOrEmpty(dto.Order.AreaCode))
                    data.AreaCode = _sharingConfigurationManager.GetCityCode();
                else
                    data.AreaCode = dto.Order.AreaCode;

                if (!string.IsNullOrEmpty(dto.Order.ProvinceNo))
                    data.CaseSerial = dto.Order.ProvinceNo;
            }
            else
                data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (data.AreaCode.Contains("519"))
                data.AreaCode = _sharingConfigurationManager.GetCityCode();

            if (data.AreaCode.Length > 6)
                data.AreaCode = data.AreaCode.Substring(0, 6);

            if (string.IsNullOrEmpty(data.CaseSerial))
                data.CaseSerial = "";

            if (string.IsNullOrEmpty(data.AccordUrl))
                data.AccordUrl = "";

            //处理通话记录时间
            SetCallTime(data);
            var validator = new SubmitCaseRecordInfoValidator();
            var validResult = await validator.ValidateAsync(data, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseRecordInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseRecordInfo>() { data });
            var jsonData = request.ToString();
            jsonData = jsonData.Replace("0001-01-01 00:00:00", "");
            #endregion

            var startTime = dto.TrCallRecordDto.OverTime;
            //将待推送数据写入待推送表
            var taskId = await _initPushDataService.InitDsSendTaskSubmitCaseRecord(data.CaseSerial, dto.TrCallRecordDto.OtherAccept, dto.TrCallRecordDto.Id, jsonData, data, startTime, cancellationToken);

            //本地保存通话记录数据
            await InitTelCallData(dto.TrCallRecordDto, data.CaseSerial, taskId, cancellationToken);
        }

        /// <summary>
        /// 统计数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task SubmitCaseTotalAsync(SubmitCaseTotalInfo dto, CancellationToken cancellationToken)
        {
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseTotalInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseTotalInfo>() { dto });
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SubmitCaseTotal", "submit_case_total", "",
              jsonData, JsonSerializer.Serialize(dto, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu,
               cancellationToken: cancellationToken);
        }

        #endregion

        #region 协同-第三批次
        /// <summary>
        /// 上报补充诉求
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SupplyCaseInfoSendAsync(SupplyCaseInfoSendInfo dto, CancellationToken cancellationToken)
        {
            dto.AreaCode = _sharingConfigurationManager.GetCityCode();
            dto.CliengGuid = Guid.NewGuid().ToString();

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SupplyCaseInfoSend", "supply_case_info_send", dto.CaseSerial, jsonData,
                 JsonSerializer.Serialize(dto, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
                 cancellationToken: cancellationToken);

            //处理附件
            await FileDataAsync(null, dto.CaseSerial, dto.CliengGuid, EMaterialType.Process, dto.AreaCode, cancellationToken);
        }

        /// <summary>
        /// 撤单
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task RevokeOrderAsync(PublishSpecialDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();
            if (dto.Order.AreaCode.Length > 6)
                dto.Order.AreaCode = dto.Order.AreaCode.Substring(0, 6);

            var validator = new RevokeCaseInfoModelValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            //如果撤单将派单表中数据修改为办理完成
            var sendInfo = await _sendCaseInfoRepository.Queryable().Where(p => p.CaseSerial == dto.Order.ProvinceNo).ToListAsync();
            if (sendInfo is not null && sendInfo.Any())
            {
                foreach (var item in sendInfo)
                {
                    item.IsEnd = true;
                    item.State = "1";
                    await _sendCaseInfoRepository.UpdateAsync(item, cancellationToken);
                }
            }

            RevokeCaseInfoModel dsRevoke = new()
            {
                CaseSerial = dto.Order.ProvinceNo,
                AreaCode = dto.Order.AreaCode,
                RevokeTime = dto.Special.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                RevokeName = dto.Special.CreatorName,
                RevokeReasion = dto.Special.Reason,
                CliengGuid = dto.Special.Id
            };

            if (string.IsNullOrEmpty(dto.Special.Cause))
                dsRevoke.RevokeType = "other";
            else if (dto.Special.Cause.Contains("内容错误"))
                dsRevoke.RevokeType = "2";
            else if (dto.Special.Cause == "撤销工单")
                dsRevoke.RevokeType = "1";
            else
                dsRevoke.RevokeType = "other";

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SendRevokeCaseInfo", "revoke_case_info", dsRevoke.CaseSerial,
         jsonData, JsonSerializer.Serialize(dsRevoke, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
         generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);


            await FileDataAsync(dto.Special.FileJson, dsRevoke.CaseSerial, dsRevoke.CliengGuid, EMaterialType.Process, dto.Order.AreaCode, cancellationToken);
        }

        /// <summary>
        /// 服务工单催单
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task SendRemindCaseInfoAsync(PublishUrgeDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();
            if (dto.Order.AreaCode.Length > 6)
                dto.Order.AreaCode = dto.Order.AreaCode.Substring(0, 6);

            var validator = new RemindCaseInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<RemindCaseInfoModel>(dto);
            data.CliengGuid = dto.Urge.Id;

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

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SendRemindCaseInfo", "remind_case_info", data.CaseSerial,
       jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
       generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

            //处理附件
            await FileDataAsync(dto.Urge.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Process, dto.Order.AreaCode, cancellationToken);

        }

        /// <summary>
        /// 接收发布数据----推送服务工单交办结果
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task PublishOrderAsync(PublishPublishOrderDto dto, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(dto.Order.AreaCode) || dto.Order.Source == ESource.ProvinceStraight || dto.Order.AreaCode.Contains("519"))
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();
            if (dto.Order.AreaCode.Length > 6)
                dto.Order.AreaCode = dto.Order.AreaCode.Substring(0, 6);

            //推省上的交办结果
            if (dto.Order.Source == ESource.ProvinceStraight)
            {
                if (dto.Order.RealCommunicationMode == null)
                    dto.Order.RealCommunicationMode = ERealCommunicationMode.Phone;
                if (dto.Order.HandleDurationWorkday <= 0)
                    dto.Order.HandleDurationWorkday = 1;
                if (dto.Order.ActualHandleTime.HasValue == false)//如果时间办理时间为空，用归档时间
                    dto.Order.ActualHandleTime = dto.Order.FiledTime;

                var validator = new CaseResultReceiveValidator();
                var validResult = await validator.ValidateAsync(dto, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

                #region 服务工单交办处理结果
                //判断是否是热线中心
                if (!string.IsNullOrEmpty(dto.Order.ActualHandleOrgCode) && dto.Order.ActualHandleOrgCode == "001")
                    dto.Order.ActualHandleOrgName = "热线中心";

                ///如果是省上派下来的，直接将区域设置为系统市州
                if (dto.Order.Source == ESource.ProvinceStraight)
                    dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

                var data = _mapper.Map<GetCaseResultReceiveInfo>(dto.Order);
                //是否公开
                data.IsWebPublic = dto.PublishState == true ? "1" : "0";
                //如果不公开需要填写不公开原因
                if (dto.PublishState != true)
                    data.AreaNotPublicReason = dto.NoPubReason;
                //已开展保密审查
                if (dto.IsOpenReview == true)
                    data.OpenReview = "1";

                data.FinishNote = dto.ArrangeOpinion;
                data.FdBack = dto.ArrangeOpinion;
                data.ConcactType = "40";
                data.FinishType = "1";
                data.HandleTimeLong = (decimal)dto.Order.AllDuration;
                data.EndAreaName = string.IsNullOrEmpty(dto.Order.ActualHandleOrgAreaName) == false ? dto.Order.ActualHandleOrgAreaName : _sharingConfigurationManager.GetCityName();
                data.ConcactType = dto.Order.RealCommunicationMode switch
                {
                    ERealCommunicationMode.Phone => "10",
                    ERealCommunicationMode.Locale => "20",
                    _ => "40",
                };
                data.CliengGuid = dto.Id;

                //中国政府网的数据处理
                if (dto.Order.ReceiveProvinceNo.Contains("ZGZFW"))
                {
                    data.Notes = dto.Remark;
                    data.MsgOpenByArea = dto.ProPublishState == true ? "1" : "0";

                    data.FeedBackAnswerContent = dto.AnswerContent;
                    data.FeedBackTel = dto.FeedBackPhone;
                    data.EventType = "";
                    data.Eventname = "";
                    data.ContactFlag = dto.IsContact == true ? "1" : "0";
                    data.AssessFlag = dto.IsVisited == true ? "1" : "0";
                    data.AssessContent = dto.EvaluateContent;
                    if (dto.NetizenEvaluate != null)
                    {
                        data.AssessOpinion = dto.NetizenEvaluate.Value;
                    }
                }

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

                await _initPushDataService.InitDsSendTaskProvinceOther("GetCaseResultReceive", "get_case_result_receive", data.CaseSerial,
       jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
       generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

                //处理附件
                await FileDataAsync(dto.FileJsons, data.CaseSerial, data.CliengGuid, EMaterialType.Result, dto.Order.AreaCode, cancellationToken);
                #endregion
            }

        }

        /// <summary>
        /// 政民互动公开
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task PublicOrderProvinceZmhd(PublicOrderProvinceZmhdDto dto, CancellationToken cancellationToken)
        {
            //政民互动提交公开数据验证
            var validator = new ZmhdCaseInfoPublicInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            //政民互动提交公开
            var data = _mapper.Map<ZmhdCaseInfoPublicInfo>(dto);
            data.AreaCode = _sharingConfigurationManager.GetCityCode();
            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<ZmhdCaseInfoPublicInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
            request.SetData(data);
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("ZmhdCaseInfoPublic", "zmhd_case_info_public", data.CaseSerial,
               jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
               generationTime: dto.PublishDate, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 接收发布的时候生成的待回访部门数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task PublishVisitAllAsync(PublishVisitAllDto dto, CancellationToken cancellationToken)
        {
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong) && _sharingConfigurationManager.GetZiGongConfig().SmartCitySystem.IsSendPush == true)
            {
                try
                {
                    //智慧城市系统
                    if (dto.Order != null && !string.IsNullOrEmpty(dto.Order.OrderTagCode) &&
                        dto.Order.OrderTagCode.IndexOf("zgdh") > -1 && dto.Order.AcceptTypeCode == "35")
                    {
                        if (dto != null && dto.VisitState == EVisitState.Visited)
                        {
                            if (dto.OrderVisitDetails != null && dto.OrderVisitDetails.Count > 0)
                            {
                                SmartCitySystem smartCitySystem = new SmartCitySystem()
                                {
                                    No = dto.Order.No,
                                    AcceptType = dto.Order.AcceptType,
                                    Title = dto.Order.Title,
                                    CreationTime = dto.Order.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                    Status = dto.Order.StatusText,
                                    Content = dto.Order.Content,
                                    Visits = null
                                };
                                List<VisitInfo> visitInfos = new();
                                //组装回访数据
                                foreach (var item in dto.OrderVisitDetails)
                                {
                                    if (item.VisitTarget == EVisitTarget.Org)
                                    {
                                        visitInfos.Add(new VisitInfo()
                                        {
                                            org = item.VisitOrgName,
                                            visitResult = item.OrgProcessingResults.Value
                                        });
                                    }
                                }
                                smartCitySystem.Visits = visitInfos;
                                var request = JsonSerializer.Serialize(smartCitySystem, new JsonSerializerOptions
                                {
                                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                                });
                                ConfigurationSmartCitySystem config = _sharingConfigurationManager.GetZiGongConfig().SmartCitySystem;
                                await _initPushDataService.InitDsSendTaskOtherPlatforms("SmartCitySystem", config.PushDataUrl, dto.Order.No,
                                request, request, EPlatformSource.SmartCitySystem, cancellationToken: cancellationToken);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            if (dto != null)
            {
                List<DsOrderVisit> orderVisits = new List<DsOrderVisit>();
                //1、待回访和已回访要将接收的数据写入库
                //2、其他状态的时候需要将工单的回访状态改成不能回访

                //处理待回访和已回访的数据
                if (dto.VisitState == EVisitState.WaitForVisit || dto.VisitState == EVisitState.Visited)
                {
                    if (dto.OrderVisitDetails != null && dto.OrderVisitDetails.Count > 0)
                    {
                        //组装回访数据
                        foreach (var item in dto.OrderVisitDetails)
                        {
                            DsOrderVisit dsOrderVisit = new()
                            {
                                OrderId = dto.Order.Id,
                                VisitDetailId = item.Id,
                                VisitId = item.VisitId,
                                VoiceEvaluate = item.VoiceEvaluate.ToString(),
                                SeatEvaluate = item.SeatEvaluate.ToString(),
                                OrgProcessingResults = _mapper.Map<Kv>(item.OrgProcessingResults),
                                OrgNoSatisfiedReason = _mapper.Map<List<Kv>>(item.OrgNoSatisfiedReason),
                                OrgHandledAttitude = _mapper.Map<Kv>(item.OrgHandledAttitude),
                                VisitContent = item.VisitContent,
                                VisitOrgName = item.VisitOrgName,
                                VisitOrgCode = item.VisitOrgCode,
                                VisitTarget = item.VisitTarget.ToString(),
                                VisitType = dto.VisitType.ToString(),
                                VisitTime = dto.VisitTime,
                                IsEffective = true
                            };
                            orderVisits.Add(dsOrderVisit);
                        }

                        //// 方式一：  保留数据
                        //var tempList = await _dsOrderVisitRepository.Queryable().Where(p => p.OrderId == dto.Order.Id && p.IsEffective == true).ToListAsync();
                        //foreach (var item in tempList)
                        //{
                        //    item.IsEffective = false;
                        //    await _dsOrderVisitRepository.UpdateAsync(item, cancellationToken);
                        //}
                        //方式二：直接删除原始数据
                        await _dsOrderVisitRepository.RemoveAsync(p => p.OrderId == dto.Order.Id);

                        //写入新数据
                        await _dsOrderVisitRepository.AddRangeAsync(orderVisits, cancellationToken);
                    }
                }

                //处理是否可以评价，如果是
                var orderData = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Order.Id);
                if (orderData is not null)
                {
                    var tempState = orderData.VisitTypeState;
                    switch (dto.VisitState)
                    {
                        case EVisitState.WaitForVisit:
                            orderData.VisitTypeState = DataSharing.Share.Enums.EVisitTypeState.Visit;
                            break;
                        case EVisitState.Visited:
                            orderData.VisitTypeState = DataSharing.Share.Enums.EVisitTypeState.Reviewed;
                            break;
                        case EVisitState.Visiting:
                        case EVisitState.NoSatisfiedWaitForVisit:
                        case EVisitState.None:
                            orderData.VisitTypeState = DataSharing.Share.Enums.EVisitTypeState.UnVisit;
                            break;
                        default:
                            break;
                    }
                    if (tempState != orderData.VisitTypeState)
                        await _dsOrderRepository.UpdateAsync(orderData, cancellationToken);
                }

            }
        }

        /// <summary>
        /// 往省上派单
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendCaseInfoDataAsync(OrderDto dto, CancellationToken cancellationToken)
        {
            //在处理工单信息
            var sendCaseInfo = _mapper.Map<SendCaseInfo>(dto);

            if (dto.OrderExtension != null)
                sendCaseInfo.IsExtends = "1";
            else
                sendCaseInfo.IsExtends = "0";

            #region 处理数据
            //处理性别
            switch (dto.FromGender)
            {
                case EGender.Female:
                    sendCaseInfo.AppLicantSex = "0";
                    break;
                case EGender.Male:
                    sendCaseInfo.AppLicantSex = "1";
                    break;
                case EGender.Unknown:
                    sendCaseInfo.AppLicantSex = "2";
                    break;
                default:
                    sendCaseInfo.AppLicantSex = "2";
                    break;
            }

            //处理证件类型
            sendCaseInfo.CertifiCateType = dto.LicenceTypeCode switch
            {
                "10" => "10",
                "40" => "20",
                "55" => "30",
                "57" => "40",
                _ => "50",
            };

            //处理紧急程度
            sendCaseInfo.CaseIsUrgent = dto.EmergencyLevel switch
            {
                EEmergencyLevel.QuiteEmergency => "10",
                EEmergencyLevel.Emergency => "20",
                _ => "30",
            };

            //处理诉求类型
            switch (sendCaseInfo.CaseType)
            {
                case "10":
                case "15":
                case "20":
                case "25":
                case "30":
                case "35":
                    break;
                default:
                    sendCaseInfo.CaseType = "40";
                    break;
            }
            #endregion
            switch (dto.SourceChannelCode.ToUpper())
            {
                case "RGDH":
                case "WX":
                case "WB":
                case "AP":
                case "WZ":
                case "YJ":
                case "SCZWFWW":
                case "XCX":
                    break;
                default:
                    sendCaseInfo.CaseSource = "QT";
                    break;
            }
            sendCaseInfo.CaseSource = sendCaseInfo.CaseSource;
            if (sendCaseInfo.CaseAddress.Length > 30)
                sendCaseInfo.CaseAddress = sendCaseInfo.CaseAddress.Substring(0, 30);

            var sendCaseInfoData = _mapper.Map<DsSendCaseInfo>(sendCaseInfo);
            sendCaseInfoData.OrderID = dto.Id;
            sendCaseInfoData.No = dto.No;
            sendCaseInfoData.State = "0";
            if (sendCaseInfoData.AreaCode.Length > 6)
                sendCaseInfoData.AreaCode = sendCaseInfoData.AreaCode.Substring(0, 6);


            await _sendCaseInfoRepository.AddAsync(sendCaseInfoData, cancellationToken);

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<SendCaseInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
            request.SetData(sendCaseInfo);
            var jsonData = request.ToString();
            #endregion
            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SendCaseInfo", "send_case_info", sendCaseInfo.CaseSerial,
          jsonData, JsonSerializer.Serialize(sendCaseInfo, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
          generationTime: dto.StartTime, cancellationToken: cancellationToken);


            //处理附件
            await FileDataAsync(dto.FileJson, sendCaseInfo.CaseSerial, sendCaseInfoData.CliengGuid, EMaterialType.Acceptance, sendCaseInfoData.AreaCode, cancellationToken);

        }
        #endregion

        #region 汇聚-第四批次--已处理

        #region 知识库
        /// <summary>
        /// 知识库上报
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task GetKnowledgeInfoSendAsync(KnowledgeSendDto dto, CancellationToken cancellationToken)
        {
            var validator = new KnowledgeInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<KnowledgeInfoSendInfo>(dto);
            data.AreaCode = _sharingConfigurationManager.GetCityCode();
            data.CliengGuid = Guid.NewGuid().ToString();
            if (data.DisableDate == null)//如果没得有失效时间，默认在生效日期上面加10年
                data.DisableDate = data.BeginDate.Value.AddYears(10);

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<KnowledgeInfoSendInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(data);
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("GetKnowledgeInfoSend", "get_knowledge_info_send", data.UID,
            jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu,
            generationTime: dto.CreatDate, cancellationToken: cancellationToken);

            #region 处理知识库原始数据
            //查询原有数据，如果有修改原始数据，没有直接新增
            var dataRaw = await _knowledgeRawDataRepository.GetAsync(p => p.UID == data.UID);
            var raw = _mapper.Map<DsKnowledgeRawData>(data);
            if (dataRaw != null)
            {
                raw.Id = dataRaw.Id;
                await _knowledgeRawDataRepository.UpdateAsync(raw, cancellationToken: cancellationToken);
            }
            else
                await _knowledgeRawDataRepository.AddAsync(raw, cancellationToken: cancellationToken);
            #endregion

            //知识附件处理
            await FileDataAsync(dto.FileJson, dto.UID, data.CliengGuid, EMaterialType.Knowledge, data.AreaCode, cancellationToken);

        }

        /// <summary>
        /// 知识库变更
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task GetKnowledgeInfoUpdateAsync(KnowledgeSendDto dto, CancellationToken cancellationToken)
        {
            var validator = new KnowledgeInfoValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<GetKnowledgeInfoUpdateInfo>(dto);
            data.AreaCode = _sharingConfigurationManager.GetCityCode();
            data.CliengGuid = Guid.NewGuid().ToString();
            if (data.DisableDate == null)//如果没得有失效时间，默认在生效日期上面加10年
                data.DisableDate = data.BeginDate.Value.AddYears(10);

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<GetKnowledgeInfoUpdateInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(data);
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("GetKnowledgeInfoUpdate", "get_knowledge_info_update", data.UID,
        jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu,
        generationTime: dto.CreatDate, cancellationToken: cancellationToken);

            #region 处理知识库原始数据
            //查询原有数据，如果有修改原始数据，没有直接新增
            var dataRaw = await _knowledgeRawDataRepository.GetAsync(p => p.UID == data.UID);
            var raw = _mapper.Map<DsKnowledgeRawData>(data);
            if (dataRaw != null)
            {
                raw.Id = dataRaw.Id;
                await _knowledgeRawDataRepository.UpdateAsync(raw, cancellationToken: cancellationToken);
            }
            else
                await _knowledgeRawDataRepository.AddAsync(raw, cancellationToken: cancellationToken);
            #endregion

            //知识附件处理
            await FileDataAsync(dto.FileJson, dto.UID, data.CliengGuid, EMaterialType.Knowledge, data.AreaCode, cancellationToken);
        }

        /// <summary>
        /// 知识库下架
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task GetKnowledgeInfoAbandonAsync(KnowledgeSendDto dto, CancellationToken cancellationToken)
        {
            var validator = new KnowledgeInfoAbandonValidator();
            var validResult = await validator.ValidateAsync(dto, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            var data = _mapper.Map<GetKnowledgeInfoAbandonInfo>(dto);
            data.AreaCode = _sharingConfigurationManager.GetCityCode();

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<GetKnowledgeInfoAbandonInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(data);
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("GetKnowledgeInfoAbandon", "get_knowledge_info_abandon", data.UID,
       jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu,
       generationTime: dto.CreatDate, cancellationToken: cancellationToken);

            //知识下架删除原有原始数据
            await _knowledgeRawDataRepository.RemoveAsync(p => p.UID == data.UID, cancellationToken: cancellationToken);

        }
        #endregion

        /// <summary>
        /// 实时服务上报
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendRealTimeStatusAsync(SendRealTimeStatusInfo dto, CancellationToken cancellationToken)
        {
            dto.AreaCode = _sharingConfigurationManager.GetCityCode();

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<SendRealTimeStatusInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(dto);
            var jsonData = request.ToString();
            #endregion

            await _initPushDataService.InitDsSendTaskProvinceOther("SendRealTimeStatus", "sendrealtimestatus", "",
           jsonData, JsonSerializer.Serialize(dto, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu,
           cancellationToken: cancellationToken);

        }
        #endregion

        /// <summary>
        /// 服务工单拓展信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task SubmitCaseExtendsAsync(OrderDto dto, CancellationToken cancellationToken)
        {
            var orderExtension = dto.OrderExtension;
            if (orderExtension is null || string.IsNullOrEmpty(orderExtension.OrderTypeCode))
                return;

            //工单类型
            string formType = orderExtension.OrderTypeCode;

            //处理为统一的市场监管表单
            if (formType == "scjgjts" || formType == "scjgjjb")
                formType = "scjgj";

            DataSharing.Share.Dtos.Province.HuiJu.SubmitCaseExtendsInfo submitCaseExtendsInfo = new()
            {
                CaseSerial = dto.ProvinceNo,
                FormType = formType
            };

            //处理扩展信息
            switch (formType.ToLower())
            {
                case "yl"://医疗表单
                    //转换数据
                    submitCaseExtendsInfo.FormMedical = _mapper.Map<FormMedicalInfo>(orderExtension);
                    break;
                case "zwfw"://四川政务服务网技术工单
                    submitCaseExtendsInfo.FormNetWorktec = _mapper.Map<FormNetWorktecInfo>(orderExtension);
                    break;
                case "th"://电视购物及商铺购买退换货工单
                    submitCaseExtendsInfo.FormReturnexChange = _mapper.Map<FormReturnexChangeInfo>(orderExtension);
                    break;
                case "gsgl"://高速公路工单
                    submitCaseExtendsInfo.FormExpressWay = _mapper.Map<FormExpressWayInfo>(orderExtension);
                    break;
                case "xjgg"://电视台虚假广告工单
                    submitCaseExtendsInfo.FormShamPub = _mapper.Map<FormShamPubInfo>(orderExtension);
                    break;
                case "swfwsq"://12366热线诉求交办
                    submitCaseExtendsInfo.FormTaxationComplaint = _mapper.Map<FormTaxationComplaintInfo>(orderExtension);
                    break;
                case "swfwzx"://12366热线咨询交办
                    submitCaseExtendsInfo.FormTaxationConsulting = _mapper.Map<FormTaxationConsultingInfo>(orderExtension);
                    break;
                case "jtfwjd"://12328服务监督
                    submitCaseExtendsInfo.FormTraffic = _mapper.Map<FormTrafficInfo>(orderExtension);
                    break;
                case "yzxf"://邮政业消费者申诉
                    submitCaseExtendsInfo.FormPost = _mapper.Map<FormPostInfo>(orderExtension);
                    break;
                case "hbjb"://环保举报业务
                    submitCaseExtendsInfo.FormEnvironMent = _mapper.Map<FormEnvironMentInfo>(orderExtension);
                    break;
                case "scjgj"://12315个性化表单
                    var formMarket = _mapper.Map<FormMarketInfo>(orderExtension);
                    //企业所属行政区划代码
                    if (!string.IsNullOrEmpty(formMarket.ReqUnit))
                    {
                        if (formMarket.ReqUnit.Contains("519"))
                            formMarket.ReqUnit = _sharingConfigurationManager.GetCityCode();
                        if (formMarket.ReqUnit.Length > 6)
                            formMarket.ReqUnit = formMarket.ReqUnit.Substring(0, 6);
                    }
                    //实际经营地代码
                    if (!string.IsNullOrEmpty(formMarket.Accsce))
                    {
                        if (formMarket.Accsce.Contains("519"))
                            formMarket.Accsce = _sharingConfigurationManager.GetCityCode();
                        if (formMarket.Accsce.Length > 6)
                            formMarket.Accsce = formMarket.Accsce.Substring(0, 6);

                    }

                    //转换数据
                    switch (orderExtension.OrderTypeCode)
                    {
                        case "scjgjjb":
                            formMarket.Rqsttypy = "25";
                            formMarket.ApplBasQue = orderExtension.ReportClassifyCode;
                            formMarket.ApplBasQueName = orderExtension.ReportClassify;
                            formMarket.DsptType = orderExtension.ReportTargetCode;
                            break;
                        case "scjgjts":
                            formMarket.Rqsttypy = "20";
                            formMarket.ApplBasQue = orderExtension.ComplainClassifyCode;
                            formMarket.ApplBasQueName = orderExtension.ComplainClassify;
                            formMarket.DsptType = orderExtension.ComplainTargetCode;
                            foreach (var item in orderExtension.ComplainTypes)
                                formMarket.AppealContent += item.Value + ",";

                            if (!string.IsNullOrEmpty(formMarket.AppealContent))
                                formMarket.AppealContent = formMarket.AppealContent.TrimEnd(',');

                            break;
                        default:
                            break;
                    }
                    formMarket.HandDepCode = dto.AcceptorOrgCode;
                    formMarket.HandDep = dto.AcceptorOrgName;
                    formMarket.Zxgh = dto.AcceptorId;
                    formMarket.AccregperId = dto.AcceptorId;
                    formMarket.AccregperName = dto.AcceptorName;
                    formMarket.RegTime = Convert.ToDateTime(dto.CreationTime);
                    formMarket.CmTime = dto.StartTime;
                    submitCaseExtendsInfo.FormMarket = formMarket;
                    break;
                default:
                    break;
            }

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceRequest<DataSharing.Share.Dtos.Province.HuiJu.SubmitCaseExtendsInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(submitCaseExtendsInfo);
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskProvinceOther("SubmitCaseExtends", "submit_case_extends", submitCaseExtendsInfo.CaseSerial,
                jsonData, JsonSerializer.Serialize(submitCaseExtendsInfo, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.HuiJu, generationTime: dto.StartTime, cancellationToken: cancellationToken);


        }
        #region 私有方法

        #region 省数据处理

        /// <summary>
        /// 热线工单办理---服务工单处理/服务工单交办处理过程
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        private async Task SubmitCaseProcessFlowAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            //判断是否是热线中心
            if (!string.IsNullOrEmpty(dto.Order.ActualHandleOrgCode) && dto.Order.ActualHandleOrgCode == "001")
                dto.Order.ActualHandleOrgName = "热线中心";

            #region 写本地办理数据-用于查询办理流程
            //写本地办理数据-用于查询办理流程
            var orderWorkFlow = _mapper.Map<DsOrderWorkFlow>(dto.WorkflowTrace);
            orderWorkFlow.OrderId = dto.Order.Id;

            await _dataOrderWorkFlowRepository.AddAsync(orderWorkFlow, cancellationToken);
            #endregion

            var configProvince = _channelConfigurationManager.GetConfigurationProvince();

            ///如果是省上派下来的，直接将区域设置为系统市州
            if (dto.Order.Source == ESource.ProvinceStraight)
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            //省上下来的工单走协同的接口
            if (dto.Order.Source == ESource.ProvinceStraight)
            {
                var data = _mapper.Map<GetCaseProcessReceiveInfo>(dto);
                data.TacheName = "70:" + data.DeptName;
                data.EndAreaName = string.IsNullOrEmpty(dto.WorkflowTrace.HandlerOrgAreaName) == false ? dto.WorkflowTrace.HandlerOrgAreaName : _sharingConfigurationManager.GetCityName();
                var validator = new GetCaseProcessReceiveInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));
                #region 处理请求参数
                var request = new ProvinceRequest<GetCaseProcessReceiveInfo>(configProvince.ClientIdXieTong, configProvince.ClientSecretXieTong);
                request.SetData(data);
                var jsonData = request.ToString();
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskProvinceOther("GetCaseProcessReceive", "get_case_process_receive", data.CaseSerial,
       jsonData, JsonSerializer.Serialize(data, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.XieTong,
       generationTime: dto.Order.StartTime, cancellationToken: cancellationToken);

                //处理附件
                await FileDataAsync(dto.WorkflowTrace.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Process, dto.Order.AreaCode, cancellationToken);
            }

            //如果不是省上派下来的工单或者省上来的工单，但是是政民互动直派的工单，需要推送已汇聚数据
            if (dto.Order.Source != ESource.ProvinceStraight || (dto.Order.Source == ESource.ProvinceStraight && dto.Order.IsProvince == false))
            {
                //本地工单走市州接口
                var data = _mapper.Map<SubmitCaseProcessInfo>(dto);
                data.TacheName = "70:" + data.DeptName;
                data.EndAreaName = string.IsNullOrEmpty(dto.WorkflowTrace.HandlerOrgAreaName) == false ? dto.WorkflowTrace.HandlerOrgAreaName : _sharingConfigurationManager.GetCityName();

                var validator = new SubmitCaseProcessInfoValidator();
                var validResult = await validator.ValidateAsync(data, cancellationToken);
                if (!validResult.IsValid)
                    throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

                #region 处理请求参数
                var requestSubmitCaseProcessInfo = new ProvinceListRequest<SubmitCaseProcessInfo>(configProvince.ClientId, configProvince.ClientSecret);
                requestSubmitCaseProcessInfo.SetData(new List<SubmitCaseProcessInfo>() { data });
                var jsonDataSubmitCaseProcessInfo = requestSubmitCaseProcessInfo.ToString();
                #endregion

                //将待推送数据写入待推送表
                await _initPushDataService.InitDsSendTaskSubmitCaseProcess(data.CaseSerial, jsonDataSubmitCaseProcessInfo, data, dto.Order.StartTime, cancellationToken);
                //处理附件
                await FileDataAsync(dto.WorkflowTrace.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Process, dto.Order.AreaCode, cancellationToken);
            }

            ////这里判断是否需要往其他平台推送数据
            //await OrderDispatchAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 服务工单结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private async Task SubmitCaseResultAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            ///如果是省上派下来的，直接将区域设置为系统市州
            if (dto.Order.Source == ESource.ProvinceStraight)
                dto.Order.AreaCode = _sharingConfigurationManager.GetCityCode();

            var data = _mapper.Map<SubmitCaseResultInfo>(dto);
            data.ConcactType = "40";
            data.FinishType = "1";
            data.HandleTimeLong = (int)dto.Order.AllDuration;
            data.CliengGuid = dto.WorkflowTrace.Id;
            data.EndAreaName = string.IsNullOrEmpty(dto.Order.ActualHandleOrgAreaName) == false ? dto.Order.ActualHandleOrgAreaName : _sharingConfigurationManager.GetCityName();

            //宜宾工单不超期，如果在推送省上数据时，实际办理时间大于过期时间，则将办理时间改成过期时间减2个小时
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.YiBin))
            {
                if (dto.Order.ExpiredTime <= dto.Order.FiledTime)
                {
                    var finishTime = dto.Order.ExpiredTime.Value.AddHours(-2);
                    data.FinishTime = finishTime;
                    data.FdBackTime = finishTime;
                }
            }
            var validator = new SubmitCaseResultInfoValidator();
            var validResult = await validator.ValidateAsync(data, cancellationToken);
            if (!validResult.IsValid)
                throw new UserFriendlyException(string.Join(',', validResult.Errors.Select(d => d.ErrorMessage)));

            #region 处理请求参数
            var configProvince = _channelConfigurationManager.GetConfigurationProvince();
            var request = new ProvinceListRequest<SubmitCaseResultInfo>(configProvince.ClientId, configProvince.ClientSecret);
            request.SetData(new List<SubmitCaseResultInfo>() { data });
            var jsonData = request.ToString();
            #endregion

            //将待推送数据写入待推送表
            await _initPushDataService.InitDsSendTaskSubmitCaseResult(data.CaseSerial, jsonData, data, dto.Order.StartTime, cancellationToken);

            //处理附件
            if (dto.WorkflowTrace != null && dto.WorkflowTrace.FileJson != null && dto.WorkflowTrace.FileJson.Count > 0)
                await FileDataAsync(dto.WorkflowTrace.FileJson, data.CaseSerial, data.CliengGuid, EMaterialType.Result, dto.Order.AreaCode, cancellationToken);

        }

        /// <summary>
        /// 工单创建数据处理
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private SubmitCaseInfo InitDataAsync(OrderDto dto)
        {
            var submitCaseInfo = _mapper.Map<SubmitCaseInfo>(dto);

            //处理性别
            submitCaseInfo.AppLicantSex = dto.FromGender switch
            {
                EGender.Female => "0",
                EGender.Male => "1",
                EGender.Unknown => "2",
                _ => "2",
            };

            //处理证件类型
            submitCaseInfo.CertifiCateType = dto.LicenceTypeCode switch
            {
                "10" => "10",
                "40" => "20",
                "55" => "30",
                "57" => "40",
                _ => "50",
            };

            //处理紧急程度
            submitCaseInfo.CaseIsUrgent = dto.EmergencyLevel switch
            {
                EEmergencyLevel.QuiteEmergency => "10",
                EEmergencyLevel.Emergency => "20",
                _ => "30",
            };
            ////处理推送分类，如果存在多个只取第一个
            //if (dto.OrderPushTypes != null && dto.OrderPushTypes.Count > 0)
            //{
            //    var push = dto.OrderPushTypes[0];
            //    if (push != null)
            //        submitCaseInfo.PushType = push.PushTypeCode;
            //}
            submitCaseInfo.PushType = dto.PushTypeCode;
            //处理诉求类型
            switch (submitCaseInfo.CaseType)
            {
                case "10":
                case "15":
                case "20":
                case "25":
                case "30":
                case "35":
                    break;
                default:
                    submitCaseInfo.CaseType = "40";
                    break;
            }
            submitCaseInfo.CaseValid = "1";
            submitCaseInfo.CaseIsPublic = string.IsNullOrEmpty(submitCaseInfo.CaseIsPublic) == true ? "0" : submitCaseInfo.CaseIsPublic;
            submitCaseInfo.ThemeSerial = "20";

            if (dto.SourceChannelCode == "SZMHD" && dto.IsProvince == false && dto.Source == ESource.ProvinceStraight)
                submitCaseInfo.TrowGuid = "【政民互动直派】";

            switch (dto.SourceChannelCode.ToUpper())
            {
                case "RGDH":
                case "WX":
                case "WB":
                case "AP":
                case "WZ":
                case "YJ":
                case "SCZWFWW":
                case "XCX":
                    break;
                default:
                    submitCaseInfo.CaseSource = "QT";
                    break;
            }
            try
            {
                //获取系统配置
                var configurationInformation = _configurationInformationCache.GetOrSet(ConstantSettings.ConfigurationInformationCacheKey,
                    d => GetStandard().GetAwaiter().GetResult());
                if (configurationInformation != null && configurationInformation.IsUpdateExpiredTime == true)
                {
                    if (dto.Status < EOrderStatus.Filed && submitCaseInfo.TfdBackTimeBf < DateTime.Now)
                    {
                        submitCaseInfo.TfdBackTimeBf = DateTime.Now.AddDays(5);
                    }
                }
            }
            catch (Exception)
            {
                return submitCaseInfo;
            }
            return submitCaseInfo;
        }

        /// <summary>
        /// 附件处理
        /// </summary>
        /// <param name="fileJson">附件</param>
        /// <param name="caseSerial">工单编号</param>
        /// <param name="cliengGuid">附件ID</param>
        /// <param name="materialType">附件类型   10：受理材料，20：环节材料，30：结果材料，40：回访评价材料，50：督办材料，60：知识库材料</param>
        /// <param name="areaCode">区域ID</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task FileDataAsync(List<Hotline.Share.Dtos.File.FileJson> fileJson, string caseSerial, string cliengGuid, EMaterialType materialType, string areaCode, CancellationToken cancellationToken)
        {
            if (fileJson != null && fileJson.Count > 0)
            {
                //将受到的数据写入本地数据库
                GetCaseMaterialInfoModel materialInfo = new()
                {
                    CaseSerial = caseSerial,
                    CliengGuid = cliengGuid,
                    AreaCode = areaCode.Length > 6 ? areaCode.Substring(0, 6) : areaCode,
                    MaterialType = materialType switch
                    {
                        EMaterialType.Acceptance => "10",
                        EMaterialType.Process => "20",
                        EMaterialType.Result => "30",
                        EMaterialType.Visit => "40",
                        EMaterialType.Supervise => "50",
                        EMaterialType.Knowledge => "60",
                        _ => "20",
                    }
                };

                var configProvince = _channelConfigurationManager.GetConfigurationProvince();
                var request = new ProvinceRequest<GetCaseMaterialInfoModel>(configProvince.ClientId, configProvince.ClientSecret);
                request.SetData(materialInfo);
                var jsonData = request.ToString();

                foreach (var item in fileJson)
                {
                    // 新增文件到列表
                    var fileData = new DsGetCaseMaterialInfo()
                    {
                        CaseSerial = caseSerial,
                        MaterialType = materialInfo.MaterialType,
                        CliengGuid = materialInfo.CliengGuid,
                        AreaCode = materialInfo.AreaCode,
                        FileName = item.FileName,
                        Type = item.FileType,
                        Additions = item.Id,
                        Path = item.Path,
                        Direction = "1",
                        SyncState = "1"
                    };
                    await _getCaseMaterialInfoRepository.AddAsync(fileData, cancellationToken);

                    List<FileJson> fileJsons = new() { _mapper.Map<FileJson>(item) };
                    //待推送数据写入待推送表
                    await _initPushDataService.InitDsSendTaskProvinceOther("GetCaseMaterialInfo", "get_case_material_info", materialInfo.CaseSerial,
                         jsonData, JsonSerializer.Serialize(materialInfo, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions), pathType: EPathType.File,
                        fileJson: fileJsons, cancellationToken: cancellationToken);
                }
            }
        }

        /// <summary>
        /// 处理通话记录队列时间
        /// </summary>
        /// <param name="recordInfo"></param>
        /// <returns></returns>
        private void SetCallTime(SubmitCaseRecordInfo recordInfo)
        {
            // 电话进入顺序 进IVR时间→进队列时间→振铃时间→开始时间→结束时间

            //进入IVR时间为空
            if (recordInfo.InIvr == DateTime.MinValue)
            {
                if (recordInfo.InQueue == DateTime.MinValue)
                {
                    if (recordInfo.CallStart == DateTime.MinValue)
                    {
                        recordInfo.CallStart = recordInfo.CallEnd.AddSeconds(-2);
                    }
                    recordInfo.InQueue = recordInfo.CallStart.AddSeconds(-2);
                }
                recordInfo.InIvr = recordInfo.InQueue.AddSeconds(-2);
            }

            //进入队列时间为空
            if (recordInfo.InQueue == DateTime.MinValue)
            {
                if (recordInfo.InIvr == DateTime.MinValue)
                {
                    if (recordInfo.CallStart == DateTime.MinValue)
                    {
                        recordInfo.CallStart = recordInfo.CallEnd.AddSeconds(-2);
                    }
                    recordInfo.InQueue = recordInfo.CallStart.AddSeconds(-2);
                    recordInfo.InIvr = recordInfo.InQueue.AddSeconds(-2);
                }
                else
                    recordInfo.InQueue = recordInfo.InIvr.AddSeconds(2);
            }

            //振铃时间为空
            if (recordInfo.CallTime == DateTime.MinValue && recordInfo.CallStart != DateTime.MinValue)
                recordInfo.CallTime = recordInfo.CallStart.AddSeconds(-2);

        }

        /// <summary>
        /// 检查是否需要推送未接通话记录
        /// </summary>
        /// <param name="endTime"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<bool> IsPublishMissedCall(DateTime endTime, CancellationToken cancellationToken)
        {
            var key = MissedCallKey + DateTime.Now.ToString("yyyyMMdd");
            int missedCallCount = 0;
            //获取系统配置
            var configurationInformation = await _configurationInformationCache.GetOrSetAsync(ConstantSettings.ConfigurationInformationCacheKey,
                d => GetStandard().GetAwaiter().GetResult(), cancellationToken: cancellationToken);
            if (configurationInformation != null)
                missedCallCount = configurationInformation.MissedCallCount;

            //如果配置为空或者配置的数量为0
            if (configurationInformation == null || missedCallCount <= 0)
                return false;

            _logger.LogInformation("获取到的不上传的值：------------------------" + missedCallCount);

            var dataCache = await _missedCallModelCache.GetAsync(key, cancellationToken);
            _logger.LogInformation("获取到缓存的值：------------------------" + JsonSerializer.Serialize(dataCache));
            if (dataCache != null)
            {
                //如果存在值，检查是否已经达到推送最大值
                if (dataCache.IsMax == false && dataCache.DateTimeList.Count > 0)
                {
                    //没有达到最大值
                    //检查第一条数据是否匹配当前推送时间
                    var list = dataCache.DateTimeList;
                    if (list[0] < endTime)
                    {
                        _logger.LogInformation("匹配到需要上传的，原始数据：------------------------" + JsonSerializer.Serialize(list));
                        //处理数据
                        list.RemoveAt(0);

                        dataCache.DateTimeList = list;
                        //是否推送完成
                        if (list == null || list.Count == 0)
                            dataCache.IsMax = true;

                        _logger.LogInformation("处理后数据：------------------------" + JsonSerializer.Serialize(list));
                        //从新写入数据
                        await _missedCallModelCache.SetAsync(key, dataCache, TimeSpan.FromDays(1), cancellationToken);

                        return true;
                    }
                }
            }
            else
            {
                if (missedCallCount > 0)
                {
                    #region 生成时间
                    //生成时间
                    List<DateTime> timeLists = new();
                    Random random = new((int)(DateTime.Now.Ticks));
                    for (int i = 0; i < missedCallCount; i++)
                    {
                        int hour = random.Next(2, 23);
                        int minute = random.Next(0, 60);
                        int second = random.Next(0, 60);
                        string tempStr = string.Format("{0} {1}:{2}:{3}", DateTime.Now.ToString("yyyy-MM-dd"), hour, minute, second);
                        DateTime rTime = Convert.ToDateTime(tempStr);
                        timeLists.Add(rTime);
                    }
                    #endregion
                    if (timeLists != null && timeLists.Count > 0)
                    {
                        timeLists.Sort();

                        if (timeLists[0] < endTime)
                            //处理数据
                            timeLists.RemoveAt(0);

                        MissedCallModelDto missedCall = new()
                        {
                            DateTimeList = timeLists
                        };
                        if (timeLists == null || timeLists.Count == 0)
                            missedCall.IsMax = true;

                        await _missedCallModelCache.SetAsync(key, missedCall, TimeSpan.FromDays(1), cancellationToken);
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 获取系统配置
        /// </summary>
        /// <returns></returns>
        private async Task<ConfigurationInformationDto> GetStandard()
        {
            var sandard = await _configurationInformationRepository.Queryable().FirstAsync();
            if (sandard == null)
            {
                sandard = new()
                {
                    CrntSeatNum = 0,
                    CrntTelNum = 0,
                    SeatNum = 0,
                    SeatHwyNum = 0,
                    MissedCallCount = 1,
                    IsUpdateExpiredTime = false
                };
            }
            return _mapper.Map<ConfigurationInformationDto>(sandard);
        }

        /// <summary>
        /// 初始化上传通话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="ProvinceNo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task InitTelCallData(TrCallDto dto, string ProvinceNo, string taskId, CancellationToken cancellationToken)
        {
            var tellCall = await _dsTelCallRepository.GetAsync(p => p.CallId == dto.OtherAccept, cancellationToken);
            if (tellCall != null)
            {
                //修改
                _mapper.Map(dto, tellCall);
                tellCall.ProvinceNo = ProvinceNo;
                tellCall.CallId = dto.OtherAccept;
                tellCall.TaskId = taskId;
                await _dsTelCallRepository.UpdateAsync(tellCall, cancellationToken);
            }
            else
            {
                //新增
                tellCall = new DsTelCall();
                tellCall = _mapper.Map<DsTelCall>(dto);
                tellCall.ProvinceNo = ProvinceNo;
                tellCall.CallId = dto.OtherAccept;
                tellCall.TaskId = taskId;
                tellCall.Id = dto.OtherAccept;
                try
                {
                    await _dsTelCallRepository.AddAsync(tellCall, cancellationToken);
                }
                catch (Exception ex)
                {
                    var tellCallNew = await _dsTelCallRepository.GetAsync(p => p.CallId == dto.OtherAccept, cancellationToken);
                    if (tellCallNew != null)
                    {
                        //修改
                        _mapper.Map(dto, tellCallNew);
                        tellCallNew.ProvinceNo = ProvinceNo;
                        tellCallNew.CallId = dto.OtherAccept;
                        tellCallNew.TaskId = taskId;
                        await _dsTelCallRepository.UpdateAsync(tellCallNew, cancellationToken);
                    }
                }

            }
        }

        /// <summary>
        /// 初始化上传通话记录----丰窝
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="ProvinceNo"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task InitTelFwCallData(CallNativeDto dto, string ProvinceNo, string taskId, CancellationToken cancellationToken)
        {
            var tellCall = await _dsTelCallRepository.GetAsync(p => p.CallId == dto.Id, cancellationToken);
            if (tellCall != null)
            {
                //修改
                _mapper.Map(dto, tellCall);
                tellCall.ProvinceNo = ProvinceNo;
                tellCall.TaskId = taskId;
                await _dsTelCallRepository.UpdateAsync(tellCall, cancellationToken);
            }
            else
            {
                //新增
                tellCall = new DsTelCall();
                tellCall = _mapper.Map<DsTelCall>(dto);
                tellCall.ProvinceNo = ProvinceNo;
                tellCall.TaskId = taskId;
                tellCall.Id = dto.Id;
                try
                {
                    await _dsTelCallRepository.AddAsync(tellCall, cancellationToken);
                }
                catch (Exception ex)
                {
                    var tellCallNew = await _dsTelCallRepository.GetAsync(p => p.CallId == dto.Id, cancellationToken);
                    if (tellCallNew != null)
                    {
                        //修改
                        _mapper.Map(dto, tellCallNew);
                        tellCallNew.ProvinceNo = ProvinceNo;
                        tellCallNew.TaskId = taskId;
                        await _dsTelCallRepository.UpdateAsync(tellCallNew, cancellationToken);
                    }
                }

            }
        }
        #endregion

        #endregion
    }
}
