using DotNetCore.CAP;
using FluentValidation;
using Hotline.Application.CallCenter;
using Hotline.Application.FlowEngine;
using Hotline.Application.OrderApp;
using Hotline.Authentications;
using Hotline.Caching.Interfaces;
using Hotline.Caching.Services;
using Hotline.CallCenter.Calls;
using Hotline.Configurations;
using Hotline.ContingencyManagement;
using Hotline.File;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.FlowEngine.Workflows;
using Hotline.Orders;
using Hotline.OrderTranspond;
using Hotline.Settings;
using Hotline.Settings.TimeLimitDomain;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.ContingencyManagement;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.FlowEngine;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.OrderTranspond;
using Hotline.Share.Dtos.Settings;
using Hotline.Share.Dtos.TrCallCenter;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Order;
using Hotline.Share.Mq;
using Hotline.Validators.FlowEngine;
using Mapster;
using MapsterMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Application.Subscribers
{
    /// <summary>
    /// 订阅来自DataSharing的消息
    /// </summary>
    public class DataSharingSubscriber : ICapSubscribe, ITransientDependency
    {
        private readonly IRepository<OrderVisit> _orderVisitRepository;
        private readonly IMapper _mapper;
        private readonly IOrderRepository _orderRepository;
        private readonly IOrderDomainService _orderDomainService;
        private readonly ICapPublisher _capPublisher;
        private readonly IRepository<OrderDelay> _orderDelayRepository;
        private readonly IRepository<OrderSendBack> _orderSendBackRepository;
        private readonly IWorkflowApplication _workflowApplication;
        private readonly IWorkflowDomainService _workflowDomainService;
        private readonly IRepository<WorkflowTrace> _workflowTraceRepository;
        private readonly IFileRepository _fileRepository;
        private readonly IRepository<OrderUrge> _orderUrgeRepository;
        private readonly IRepository<OrderSupervise> _orderSuperviseRepository;
        private readonly IRepository<OrderVisitDetail> _orderVisitedDetailRepository;
        private readonly IOrderScreenRepository _orderScreenRepository;
        private readonly IRepository<OrderExtension> _orderExtensionRepository;
        private readonly IRepository<SystemDicData> _systemDicDataRepository;
        private readonly ISystemOrganizeRepository _systemOrganizeRepository;
        private readonly IRepository<TranspondCityRawData> _transpondCityRawDataRepository;
        private readonly IRepository<OrderComplement> _orderComplementRepository;
        private readonly IOrderApplication _orderApplication;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
        private readonly IRepository<OrderWarning> _orderWarningRepository;
        private readonly IRepository<OrderRevoke> _orderRevokeRepository;
        private readonly IRepository<ContingencyManagementOrders> _contingencyManagementOrdersRepository;
        private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
        private readonly ICallApplication _callApplication;
        private readonly IRepository<OrderPublish> _orderPublishRepository;
        private readonly ISystemDicDataCacheManager _sysDicDataCacheManager;
        private readonly ICalcExpireTime _expireTime;
        private readonly ISessionContextManager _sessionContextManager;
        private readonly ILogger<DataSharingSubscriber> _logger;

        public DataSharingSubscriber(
            IRepository<OrderVisit> orderVisitRepository,
            IMapper mapper,
            IOrderRepository orderRepository,
            IOrderDomainService orderDomainService,
            ICapPublisher capPublisher,
            IRepository<OrderDelay> orderDelayRepository,
            IRepository<OrderSendBack> orderSendBackRepository,
            IWorkflowApplication workflowApplication,
            IWorkflowDomainService workflowDomainService,
            IRepository<WorkflowTrace> workflowTraceRepository,
            IRepository<OrderUrge> orderUrgeRepository,
            IRepository<OrderSupervise> orderSuperviseRepository,
            IRepository<OrderVisitDetail> orderVisitedDetailRepository,
            IOrderScreenRepository orderScreenRepository,
            IRepository<OrderExtension> orderExtensionRepository,
            IFileRepository fileRepository,
            IRepository<SystemDicData> systemDicDataRepository,
            ISystemOrganizeRepository systemOrganizeRepository,
            IRepository<TranspondCityRawData> transpondCityRawDataRepository,
            IRepository<OrderComplement> orderComplementRepository,
            IOrderApplication orderApplication,
            ISystemSettingCacheManager systemSettingCacheManager,
            IRepository<OrderWarning> orderWarningRepository,
            IRepository<OrderRevoke> orderRevokeRepository,
            IRepository<ContingencyManagementOrders> contingencyManagementOrdersRepository,
            IOptionsSnapshot<AppConfiguration> appOptions,
            ICallApplication callApplication,
            IRepository<OrderPublish> orderPublishRepository,
            ISystemDicDataCacheManager sysDicDataCacheManager,
            ICalcExpireTime expireTime,
            ISessionContextManager sessionContextManager,
            ILogger<DataSharingSubscriber> logger)
        {
            _orderSendBackRepository = orderSendBackRepository;
            _workflowApplication = workflowApplication;
            _workflowDomainService = workflowDomainService;
            _workflowTraceRepository = workflowTraceRepository;
            _orderUrgeRepository = orderUrgeRepository;
            _orderSuperviseRepository = orderSuperviseRepository;
            _orderScreenRepository = orderScreenRepository;
            _orderExtensionRepository = orderExtensionRepository;
            _orderVisitedDetailRepository = orderVisitedDetailRepository;
            _orderRepository = orderRepository;
            _orderDomainService = orderDomainService;
            _fileRepository = fileRepository;
            _orderVisitRepository = orderVisitRepository;
            _mapper = mapper;
            _capPublisher = capPublisher;
            _orderDelayRepository = orderDelayRepository;
            _systemDicDataRepository = systemDicDataRepository;
            _systemOrganizeRepository = systemOrganizeRepository;
            _transpondCityRawDataRepository = transpondCityRawDataRepository;
            _orderComplementRepository = orderComplementRepository;
            _orderApplication = orderApplication;
            _systemSettingCacheManager = systemSettingCacheManager;
            _orderWarningRepository = orderWarningRepository;
            _orderRevokeRepository = orderRevokeRepository;
            _contingencyManagementOrdersRepository = contingencyManagementOrdersRepository;
            _appOptions = appOptions;
            _callApplication = callApplication;
            _orderPublishRepository = orderPublishRepository;
            _sysDicDataCacheManager = sysDicDataCacheManager;
            _expireTime = expireTime;
            _sessionContextManager = sessionContextManager;
            _logger = logger;
        }

        /// <summary>
        /// 接收工单退回结果
        /// </summary>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderReturnFeedback)]
        public async Task RecOrderReturnAsync(OrderSendBackResultDto dto, CancellationToken cancellationToken)
        {
            var sendBack = await _orderSendBackRepository.GetAsync(p => p.Id == dto.Id && p.State == 0, cancellationToken);
            if (sendBack != null)
            {
                sendBack.Result = dto.Result;
                sendBack.Reason = dto.Reason;
                sendBack.AuditName = dto.AuditName;
                sendBack.AuditOrgName = dto.AuditOrgName;
                sendBack.AuditTime = dto.AuditTime;
                if (dto.Result == 0)
                    sendBack.State = 2;
                else if (dto.Result == 1)
                    sendBack.State = 1;

                if (dto.Files != null && dto.Files.Any())
                {
                    sendBack.FileJson = await _fileRepository.AddFileAsync(dto.Files, sendBack.Id, string.Empty, cancellationToken);
                }

                var order = await _orderRepository.GetAsync(sendBack.OrderId, cancellationToken);
                if (order is null)
                    throw new UserFriendlyException("无效工单编号");

                if (!string.IsNullOrEmpty(order.WorkflowId))
                {
                    order.Status = EOrderStatus.Handling;
                }
                else
                {
                    order.Status = EOrderStatus.WaitForAccept;
                }

                if (dto.Result is 1)
                    order.ProvinceSendBack = true;
                else
                    order.ProvinceSendBack = false;
                await _orderRepository.UpdateAsync(order, cancellationToken);

                //if (dto.Result is 1)
                //{
                //var now = DateTime.Now;
                //var handleDuration = order.StartTime.HasValue
                //    ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value,
                //        now, order.ProcessType is EProcessType.Zhiban)
                //    : 0;
                //var fileDuration = order.CenterToOrgTime.HasValue
                //    ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
                //        now, order.ProcessType is EProcessType.Zhiban)
                //    : 0;
                //var allDuration = order.StartTime.HasValue
                //    ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value, now,
                //        order.ProcessType is EProcessType.Zhiban)
                //    : 0;
                //order.File(now, handleDuration, fileDuration, allDuration);
                //await _orderRepository.UpdateAsync(order, cancellationToken);

                //var current = SessionContextCreator.CreateSessionContext(dto.Source, _cityBaseConfiguration.Value);
                //if (string.IsNullOrEmpty(order.WorkflowId))
                //{
                //    var startDto = new StartWorkflowDto
                //    {
                //        DefinitionModuleCode = WorkflowModuleConsts.OrderHandle,
                //        Title = order.Title,
                //        Opinion = dto.Reason ?? "省工单同意退回",
                //    };
                //    await _workflowApplication.StartToEndAsync(startDto, current, order.Id, order.ExpiredTime,
                //        cancellationToken);
                //}
                //else
                //{
                //    //await _workflowApplication.HandleToEndAsync(current, order.WorkflowId, "省工单同意退回", null,
                //    //    EReviewResult.Approval, cancellationToken);
                //    await _workflowApplication.JumpToEndAsync(current, order.WorkflowId, dto.Reason ?? "省工单同意退回",
                //        null, order.ExpiredTime, cancellationToken: cancellationToken);
                //}


                //TODO 工单终止
                //}
                //else
                //{

                //}
                await _orderSendBackRepository.UpdateAsync(sendBack, cancellationToken);
            }
        }

        /// <summary>
        /// 服务工单撤单（省工单下派后撤单）
        /// </summary>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderRevoke)]
        public async Task RecCancelOrderAsync(CancelOrderDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.Queryable().Includes(d => d.Workflow).FirstAsync(p => p.ReceiveProvinceNo == dto.ProvinceNo);
            if (order is null)
                throw new UserFriendlyException("未查询到工单");

            //SessionContextCreator.CreateSessionContext(_sessionContextProvider, dto.Source);
            // await _sessionContextCreator.CreateSessionContextAsync(dto.Source, cancellationToken);
            _sessionContextManager.ChangeSessionContext(dto.Source);

            OrderRevoke orderRevoke = new()
            {
                OrderId = order.Id,
                RevokeTime = DateTime.Parse(dto.RevokeTime),
                RevokeType = dto.RevokeType,
                RevokeName = dto.RevokeName,
                RevokeReasion = dto.Opinion,
                CliengGuid = dto.CliengGuid,
                IsProRevoke = true,
                RevokeTypeName = dto.RevokeType switch
                {
                    "1" => "诉求人已私下解决",
                    "2" => "诉求内容有误",
                    "3" => "诉求人信息有误",
                    "other" => "其它",
                    _ => "其它",
                }
            };
            await _orderRevokeRepository.AddAsync(orderRevoke, cancellationToken);
            //var setting = _systemSettingCacheManager.GetSetting(SettingConstants.CityBaseConfiguration)?.SettingValue[0];
            //CityBaseConfiguration cityBase = JsonConvert.DeserializeObject<CityBaseConfiguration>(setting);

            //计算order 期满时间
            ExpiredTimeWithConfig expiredTimeConfig;
            if (_appOptions.Value.IsZiGong)
            {
                //expiredTimeConfig = await _expireTime.CalcExpiredTime(DateTime.Now, order.StartTime.Value, EFlowDirection.CenterToCenter, order.Adapt<OrderTimeClacInfo>());
                expiredTimeConfig = await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToCenter,
                    order.Adapt<OrderTimeClacInfo>());
            }
            else
            {
                //期满时间
                //expiredTimeConfig = _timeLimitDomainService.CalcExpiredTime(DateTime.Now, EFlowDirection.CenterToOrg, order.AcceptTypeCode);
                //expiredTimeConfig = await _expireTime.CalcExpiredTime(DateTime.Now, order.CenterToOrgTime.Value, EFlowDirection.CenterToOrg, order.Adapt<OrderTimeClacInfo>());
                expiredTimeConfig =
                    await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToOrg, order.Adapt<OrderTimeClacInfo>());
            }

            _mapper.Map(expiredTimeConfig, order);
            await _orderRepository.UpdateAsync(order, cancellationToken);

            //宜宾需求：特提至中心（优先派单组无派单组节点就特提至坐席），由派单员归档
            if (string.IsNullOrEmpty(order?.WorkflowId))
            {
                var startDto = new StartWorkflowDto
                {
                    DefinitionModuleCode = WorkflowModuleConsts.OrderHandle,
                    Title = order.Title,
                    Opinion = dto.Opinion,
                };
                await _workflowApplication.StartWorkflowToStartStepAsync(startDto, order.Id, order.ExpiredTime, cancellationToken);
            }
            else
            {
                // FlowStepHandler? handler = null;
                // var nextHandler = new List<FlowStepHandler>();
                // if (_appOptions.Value.IsZiGong)
                // {
                //     // 平均派单
                //     var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
                //     if (averageSendOrder)
                //     {
                //         handler = await _orderDomainService.AverageOrder(cancellationToken);
                //         nextHandler = new List<FlowStepHandler> { handler };
                //     }
                // }
                //
                // StepAssignInfo? stepAssignInfo = null;
                // if (handler is not null)
                // {
                //     stepAssignInfo = _mapper.Map<StepAssignInfo>(handler);
                //     stepAssignInfo.FlowAssignType = EFlowAssignType.User;
                // }
                //
                // var reverseFlowStepAssignInfo = stepAssignInfo is null
                //     ? new ReverseFlowStepAssignInfo(EReverseFlowStepCreationPolicy.OriginStep)
                //     : new ReverseFlowStepAssignInfo(EReverseFlowStepCreationPolicy.OriginStepUser, stepAssignInfo);

                //var (isPaiDan, workflow) = await _workflowDomainService.RecallToCenterFirstToSendAsync(order.WorkflowId, 
                //    dto.Opinion, order.Status >= EOrderStatus.Filed, order.ExpiredTime, nextHandler, EHandleMode.Recall, cancellationToken);
                var (isPaiDan, workflow) = await _workflowDomainService.RecallToCenterFirstToSendAsync(order.WorkflowId, dto.Opinion,
                    order.Status >= EOrderStatus.Filed, order.ExpiredTime, EHandleMode.Recall, cancellationToken: cancellationToken);

                order.FiledTime = null;
                order.Status = isPaiDan ? EOrderStatus.Special : EOrderStatus.WaitForAccept;

                order.CurrentStepName = workflow.CurrentStepName;
                order.CurrentStepCode = workflow.CurrentStepCode;
                order.CurrentStepId = workflow.CurrentStepId;
                order.CurrentStepCreateTime = workflow.CurrentStepCreateTime;
                order.CurrentHandleTime = workflow.CurrentHandleTime;
                order.CurrentHandlerId = workflow.CurrentHandlerId;
                order.CurrentHandlerName = workflow.CurrentHandlerName;
                order.CurrentHandleOrgName = workflow.CurrentHandleOrgName;
                order.CurrentHandleOrgId = workflow.CurrentHandleOrgId;
                order.CurrentHandleOrgLevel = workflow.CurrentHandleOrgLevel;
                order.CurrentHandleOrgAreaCode = workflow.CurrentHandleOrgAreaCode;
                order.CurrentHandleOrgAreaName = workflow.CurrentHandleOrgAreaName;

                await _orderRepository.UpdateAsync(order, cancellationToken);
            }

            //删除甄别、延期、二次办理等数据
            await _orderApplication.SpecialNewVerify(order, cancellationToken);
        }

        /// <summary>
        /// 服务工单催单
        /// </summary>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderRemind)]
        public async Task RecOrderUrgeAsync(ProvinceOrderUrgeDto dto, CancellationToken cancellationToken)
        {
            var exists = await _orderUrgeRepository.Queryable()
                .AnyAsync(d => d.DsBisId == dto.DsBisId, cancellationToken);
            if (exists)
                throw new UserFriendlyException($"收到重复催办编号: {dto.DsBisId}");

            var centerOrgName = _systemSettingCacheManager.GetSetting(SettingConstants.CenterOrgName)?.SettingValue[0];
            var order = await _orderRepository.Queryable().Where(x => x.ReceiveProvinceNo == dto.CaseSerial).FirstAsync(cancellationToken);
            var model = new OrderUrge();
            model.InitId();
            model.State = 0;
            model.CreatorOrgName = "省12345";
            model.CrUser = dto.RemindName;
            model.ApplyContent = dto.RemindReasion;
            model.OrderId = order.Id;
            model.OrgId = "001";
            model.OrgName = centerOrgName;
            model.RemindTime = dto.RemindTime;
            model.DsBisId = dto.DsBisId;

            //if (!string.IsNullOrEmpty(order.WorkflowId))
            //{
            //    var org = await _workflowDomainService.FindActualHandlerAsync(order.WorkflowId, cancellationToken);
            //    if (org != null)
            //    {
            //        model.OrgId = org.Key;
            //        model.OrgName = org.Value;
            //    }
            //}
            if (!string.IsNullOrEmpty(order.CurrentHandleOrgId) && !string.IsNullOrEmpty(order.CurrentHandleOrgName))
            {
                model.OrgId = order.CurrentHandleOrgId;
                model.OrgName = order.CurrentHandleOrgName;
            }


            if (dto.Files.Any())
                model.FileJson =
                    await _fileRepository.AddFileAsync(dto.Files, model.Id, "", cancellationToken);
            await _orderUrgeRepository.AddAsync(model, cancellationToken);
        }

        /// <summary>
        /// 服务工单预警---收到预警给当前办理部门发催办，如果没有办理部门直接催办中心
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderWarning)]
        public async Task RecWarnInfoAsync(WarningDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.Queryable().Where(x => x.ReceiveProvinceNo == dto.CaseSerial).FirstAsync(cancellationToken);
            if (order != null)
            {
                var centerOrgName = _systemSettingCacheManager.GetSetting(SettingConstants.CenterOrgName)?.SettingValue[0];
                var model = new OrderUrge();
                model.InitId();
                model.State = 0;
                model.CreatorOrgName = "省12345";
                model.CrUser = "省12345";
                model.ApplyContent = dto.WarnRulename + "    " + dto.WarnDescribe;
                model.OrderId = order.Id;
                model.ReplyLimitTime = dto.WarnTimebf;
                model.OrgId = "001";
                model.OrgName = centerOrgName;

                //if (!string.IsNullOrEmpty(order.WorkflowId))
                //{
                //    var org = await _workflowDomainService.FindActualHandlerAsync(order.WorkflowId, cancellationToken);
                //    if (org != null)
                //    {
                //        model.OrgId = org.Key;
                //        model.OrgName = org.Value;
                //    }
                //}
                //model.OrgId = order.CurrentHandleOrgId;
                //model.OrgName = order.CurrentHandleOrgName;
                if (!string.IsNullOrEmpty(order.CurrentHandleOrgId) && !string.IsNullOrEmpty(order.CurrentHandleOrgName))
                {
                    model.OrgId = order.CurrentHandleOrgId;
                    model.OrgName = order.CurrentHandleOrgName;
                }

                await _orderUrgeRepository.AddAsync(model, cancellationToken);

                //写入预警
                var warning = new OrderWarning()
                {
                    OrderId = order.Id,
                    WarnRulename = dto.WarnRulename,
                    WarnDescribe = dto.WarnDescribe,
                    WarnTimebf = dto.WarnTimebf,
                    WarnDegree = dto.WarnDegree,
                    WarnType = dto.WarnType,
                    WarnDate = dto.WarnDate,
                    IsProWarn = true
                };
                await _orderWarningRepository.AddAsync(warning, cancellationToken);
            }
        }

        /// <summary>
        /// 督办工单派发接口
        /// </summary>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderSupervise)]
        public async Task RecOrderSuperviseAsync(ProvinceSendOrderSuperviseDto dto, CancellationToken cancellationToken)
        {
            var exists = await _orderSuperviseRepository.Queryable()
                .AnyAsync(d => d.SuperviseSerial == dto.ProvinceOrderSuperviseDto.SuperviseSerial, cancellationToken);
            if (exists)
                throw new UserFriendlyException($"收到重复督办编号: {dto.ProvinceOrderSuperviseDto.SuperviseSerial}");

            var order = await _orderRepository.Queryable().Where(x => x.ReceiveProvinceNo == dto.ProvinceOrderSuperviseDto!.CaseSerial)
                .FirstAsync(cancellationToken);
            var org = await _systemOrganizeRepository.GetAsync(x => x.Id == order.ActualHandleOrgCode, cancellationToken);
            var model = new OrderSupervise();
            model.InitId();
            model.OrderId = order.Id;
            model.ReplyLimitTime = dto.ProvinceOrderSuperviseDto.SuperviseReturnDate;
            model.OrgName = org.Name;
            model.OrgId = org.Id;
            model.LaunchOrgName = dto.ProvinceOrderSuperviseDto.SuperviseSendDept;
            model.CrUser = dto.ProvinceOrderSuperviseDto.SupervisePerson;
            model.State = 0;
            model.Province = true;
            model.ApplyContent = dto.ProvinceOrderSuperviseDto.SuperviseContent;
            model.SuperviseSerial = dto.ProvinceOrderSuperviseDto.SuperviseSerial;
            model.SuperviseTitle = dto.ProvinceOrderSuperviseDto.SuperviseTitle;
            model.SuperviseTime = dto.ProvinceOrderSuperviseDto.SuperviseTime;
            model.SuperviseType = dto.ProvinceOrderSuperviseDto.SuperviseType;
            if (dto.Files.Any())
                model.FileJson =
                    await _fileRepository.AddFileAsync(dto.Files, model.Id, "", cancellationToken);
            await _orderSuperviseRepository.AddAsync(model, cancellationToken);
        }

        /// <summary>
        /// 服务工单甄别结果
        /// </summary>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderScreen)]
        public async Task RecOrderScreenResultAsync(ProvinceSendScreenResultDto dto, CancellationToken cancellationToken)
        {
            var orderScreen = await _orderScreenRepository.Queryable()
                .FirstAsync(x => x.Order.ReceiveProvinceNo == dto.ProvinceScreenResult.CaseSerial &&
                                 x.Status == EScreenStatus.Approval, cancellationToken);
            if (orderScreen is null)
                throw new UserFriendlyException($"收到ds推送：{EventNames.SharingOrderScreen}, 未查询到甄别数据, 省交办编号：{dto.ProvinceScreenResult.CaseSerial}");

            //SessionContextCreator.CreateSessionContext(_sessionContextProvider, dto.Source);
            // await _sessionContextCreator.CreateSessionContextAsync(dto.Source, cancellationToken);
            _sessionContextManager.ChangeSessionContext(dto.Source);


            if (int.Parse(dto.ProvinceScreenResult.AuditResult) == 0)
            {
                PreviousWorkflowDto previous = new PreviousWorkflowDto();
                previous.Opinion = dto.ProvinceScreenResult.AuditOpinion;
                previous.WorkflowId = orderScreen.WorkflowId;
                await _workflowDomainService.PreviousAsync(previous, cancellationToken: cancellationToken);
            }

            if (int.Parse(dto.ProvinceScreenResult.AuditResult) > 0)
            {
                await _workflowApplication.HandleToEndAsync(orderScreen.WorkflowId, dto.ProvinceScreenResult.AuditOpinion, null,
                    reviewResult: int.Parse(dto.ProvinceScreenResult.AuditResult) == 1
                        ? Share.Enums.FlowEngine.EReviewResult.Approval
                        : Share.Enums.FlowEngine.EReviewResult.Failed, cancellationToken: cancellationToken);
                orderScreen.Status = int.Parse(dto.ProvinceScreenResult.AuditResult) == 1
                    ? Share.Enums.Order.EScreenStatus.End
                    : Share.Enums.Order.EScreenStatus.Refuse;
                //if (orderScreen.Status == Share.Enums.Order.EScreenStatus.End)
                //{
                //    var visitDetail = await _orderVisitedDetailRepository.GetAsync(orderScreen.VisitDetailId, cancellationToken);
                //    if (visitDetail != null)
                //    {
                //        var screenSatisfy = new Kv() { Key = "-1", Value = "视为满意" };
                //        visitDetail.OrgProcessingResults = screenSatisfy;
                //        visitDetail.OrgHandledAttitude = screenSatisfy;
                //        await _orderVisitedDetailRepository.UpdateAsync(visitDetail, cancellationToken);
                //    }
                //}
                orderScreen.ReplyContent = dto.ProvinceScreenResult.AuditOpinion;
                orderScreen.AuditName = dto.ProvinceScreenResult.AuditPerson;
                orderScreen.AuditOrgName = dto.ProvinceScreenResult.AuditOuname;
                orderScreen.AuditTime = dto.ProvinceScreenResult.AuditTime;

                if (dto.Files.Any())
                    orderScreen.FileJson =
                        await _fileRepository.AddFileAsync(dto.Files, orderScreen.Id, "", cancellationToken);
                await _orderScreenRepository.UpdateAsync(orderScreen, cancellationToken);
                //多部门甄别回访 省上结果处理
                if (orderScreen.Status == Share.Enums.Order.EScreenStatus.End)
                {
                    var visitDetails = await _orderVisitedDetailRepository.Queryable().Where(x => x.OrderVisit.OrderId == orderScreen.OrderId &&
                                                                                                  x.VisitTarget == EVisitTarget.Org && (
                                                                                                      SqlFunc.JsonField(x.OrgProcessingResults,
                                                                                                          "Key") ==
                                                                                                      "1" ||
                                                                                                      SqlFunc.JsonField(x.OrgProcessingResults,
                                                                                                          "Key") ==
                                                                                                      "2" ||
                                                                                                      SqlFunc.JsonField(x.OrgHandledAttitude,
                                                                                                          "Key") ==
                                                                                                      "1" ||
                                                                                                      SqlFunc.JsonField(x.OrgHandledAttitude,
                                                                                                          "Key") ==
                                                                                                      "2"
                                                                                                  ) && x.Id != orderScreen.VisitDetailId)
                        .ToListAsync();
                    foreach (var visitDetail in visitDetails)
                    {
                        if (visitDetail != null)
                        {
                            var screenSatisfy = new Kv() { Key = "-1", Value = "视为满意" };
                            visitDetail.OrgProcessingResults = screenSatisfy;
                            visitDetail.OrgHandledAttitude = screenSatisfy;
                            await _orderVisitedDetailRepository.UpdateAsync(visitDetail, cancellationToken);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 更新工单受理附件
        /// </summary>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderUpdataFiles)]
        public async Task RecOrderUpdateFilesAsync(OrderUpdataFiles dto, CancellationToken cancellationToken)
        {
            if (dto == null && dto.Files.Any())
            {
                var order = await _orderRepository.GetAsync(dto.OrderId, cancellationToken);
                order.FileJson = await _fileRepository.AddFileAsync(dto.Files, dto.OrderId, "", cancellationToken);
            }
        }

        /// <summary>
        /// 省下行回访
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderEvlResult)]
        public async Task OrderVisitProvince(ProvinceOrderVisitDto dto, CancellationToken cancellationToken)
        {
            var orderVisit = await _orderVisitRepository.Queryable()
                .Includes(x => x.Order)
                .Includes(x => x.OrderVisitDetails)
                .Where(x => x.Order.ReceiveProvinceNo == dto.ProvinceNo &&
                            x.VisitState == Share.Enums.Order.EVisitState.WaitForVisit).FirstAsync(cancellationToken);

            if (orderVisit != null)
            {
                //处理评价结果
                var processingResult = dto.OrgProcessingResults;
                Kv orgProcessingResults = null;
                if (!string.IsNullOrEmpty(processingResult))
                {
                    var dicData = await _systemDicDataRepository.GetAsync(x => x.DicTypeCode == SysDicTypeConsts.VisitSatisfaction &&
                                                                               x.DicDataValue == processingResult, cancellationToken);
                    if (dicData != null)
                    {
                        orgProcessingResults = new Kv();
                        orgProcessingResults.Key = dicData.DicDataValue;
                        orgProcessingResults.Value = dicData.DicDataName;
                    }

                    if (orgProcessingResults != null)
                    {
                        //主表
                        orderVisit.VisitState = Share.Enums.Order.EVisitState.Visited;
                        orderVisit.VisitTime = dto.VisitTime;
                        orderVisit.VisitType = dto.VisitType;
                        orderVisit.IsCanHandle = orgProcessingResults.Key == "2";
                        orderVisit.IsCanAiVisit = false;
                        orderVisit.NowEvaluate = orgProcessingResults;
                        if (_appOptions.Value.IsZiGong)
                        {
                            orderVisit.EmployeeId = _systemSettingCacheManager.DefaultVisitEmployeeId;
                        }

                        await _orderVisitRepository.UpdateAsync(orderVisit, cancellationToken);
                        //子表
                        for (int i = 0; i < orderVisit.OrderVisitDetails.Count; i++)
                        {
                            if (orderVisit.OrderVisitDetails[i].VisitTarget == EVisitTarget.Seat)
                            {
                                orderVisit.OrderVisitDetails[i].VoiceEvaluate = (EVoiceEvaluate)int.Parse(orgProcessingResults.Key);
                                orderVisit.OrderVisitDetails[i].SeatEvaluate = (ESeatEvaluate)int.Parse(orgProcessingResults.Key);
                            }
                            else
                            {
                                orderVisit.OrderVisitDetails[i].OrgProcessingResults = orgProcessingResults;
                            }

                            orderVisit.OrderVisitDetails[i].VisitContent = dto.VisitContent;
							orderVisit.OrderVisitDetails[i].ScreenByEndTime = await _orderDomainService.GetScreenByEndTime();
						}

                        await _orderVisitedDetailRepository.UpdateRangeAsync(orderVisit.OrderVisitDetails, cancellationToken);
                        //工单
                        orderVisit.Order.Visited(orgProcessingResults.Key, orgProcessingResults.Value);
                        await _orderRepository.UpdateAsync(orderVisit.Order);

                        ////处理网站通知差评数据
                        //if (orderVisit.Order.Source == ESource.Hotline && orderVisit.OrderVisitDetails.Any(x => x.OrgHandledAttitude?.Key == "1" || x.OrgHandledAttitude?.Key == "2" || x.OrgProcessingResults?.Key == "1" || x.OrgProcessingResults?.Key == "2"))
                        //{
                        //    //包含不满意数据，重新生成新的回访
                        //    var newOrderVisit = _mapper.Map<OrderVisit>(orderVisit);
                        //    newOrderVisit.InitId();
                        //    newOrderVisit.VisitState = EVisitState.NoSatisfiedWaitForVisit;
                        //    newOrderVisit.VisitTime = null;
                        //    newOrderVisit.IsCanHandle = false;
                        //    newOrderVisit.IsCanAiVisit = false;
                        //    newOrderVisit.AiVisitCount = 0;
                        //    await _orderVisitRepository.AddAsync(newOrderVisit, cancellationToken);
                        //    var list = _mapper.Map<List<OrderVisitDetail>>(orderVisit.OrderVisitDetails);
                        //    list.ForEach(x =>
                        //    {
                        //        x.VisitId = newOrderVisit.Id;
                        //        x.VoiceEvaluate = null;
                        //        x.VoiceEvaluate = null;
                        //        x.OrgHandledAttitude = null;
                        //        x.OrgNoSatisfiedReason = null;
                        //        x.OrgProcessingResults = null;
                        //        x.VisitContent = "";
                        //    });
                        //    await _orderVisitedDetailRepository.AddRangeAsync(list, cancellationToken);
                        //}
                    }
                }
            }
            else
            {
                //处理省下行回访
                var order = await _orderRepository.Queryable().Where(x => x.ReceiveProvinceNo == dto.ProvinceNo).FirstAsync();
                if (order != null && order.Status <= EOrderStatus.Filed)
                {
                    //判断是否有发布数据
                    var orderPublish = await _orderPublishRepository.Queryable()
                        .Includes(x => x.Order).Where(x => x.Order.ReceiveProvinceNo == dto.ProvinceNo).FirstAsync(cancellationToken);
                    if (orderPublish == null)
                    {
                        orderPublish = new OrderPublish();
                        orderPublish.OrderId = order.Id;
                        orderPublish.No = order.No;
                        orderPublish.PublishState = false;
                        orderPublish.ArrangeTitle = order.Title;
                        orderPublish.ArrangeContent = order.Content;
                        orderPublish.ArrangeOpinion = order.FileOpinion;
                        orderPublish.ProPublishState = false;
                        orderPublish.FeedBackPhone = order.Contact;
                        orderPublish.CreatorName = order.CenterToOrgHandlerId;
                        await _orderPublishRepository.AddAsync(orderPublish);
                        order.Publish(orderPublish.PublishState);
                    }

                    orderVisit = new OrderVisit();
                    orderVisit.No = order.No;
                    orderVisit.OrderId = order.Id;
                    orderVisit.PublishTime = DateTime.Now;
                    orderVisit.IsCanHandle = true;
                    orderVisit.EmployeeId = order.CenterToOrgHandlerId;
                    orderVisit.VisitState = EVisitState.None;
                    orderVisit.VisitTime = dto.VisitTime;
                    orderVisit.VisitType = dto.VisitType;
                    orderVisit.IsCanAiVisit = false;
                    var VisitSatisfaction = _sysDicDataCacheManager.GetSysDicDataCache(SysDicTypeConsts.VisitSatisfaction)
                        .Where(x => x.DicDataValue == dto.OrgProcessingResults).Select(m => new Kv { Key = m.DicDataValue, Value = m.DicDataName })
                        .FirstOrDefault();
                    var satisfy = VisitSatisfaction;
                    orderVisit.NowEvaluate = satisfy;
                    string visitId = await _orderVisitRepository.AddAsync(orderVisit);

                    //新增回访信息
                    var visitedDetail = new List<OrderVisitDetail>();

                    //新增坐席回访
                    var seatDetail = new OrderVisitDetail();
                    seatDetail.VisitId = visitId;
                    seatDetail.VisitTarget = EVisitTarget.Seat;
                    seatDetail.VoiceEvaluate = EVoiceEvaluate.Satisfied;
                    seatDetail.SeatEvaluate = ESeatEvaluate.Satisfied;
                    visitedDetail.Add(seatDetail);

                    //新增部门回访
                    var orgDetail = new OrderVisitDetail();
                    orgDetail.VisitId = visitId;
                    orgDetail.VisitOrgCode = order.ActualHandleOrgCode;
                    orgDetail.VisitOrgName = order.ActualHandleOrgName;
                    orgDetail.VisitTarget = EVisitTarget.Org;
					orgDetail.ScreenByEndTime = await _orderDomainService.GetScreenByEndTime();

					orgDetail.OrgProcessingResults = satisfy;

                    visitedDetail.Add(orgDetail);
                    //TODO 自贡办件态度


                    await _orderVisitedDetailRepository.AddRangeAsync(visitedDetail, cancellationToken);
                    //order.Visited(satisfy.Key, satisfy.Value);
                    //order.Status = EOrderStatus.Visited;
                    //await _orderRepository.UpdateAsync(order, cancellationToken);
                }
            }
        }

        /// <summary>
        /// 工单回访
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderVisitAllOther)]
        public async Task OrderVisitWeb(OrderVisitWebDto dto, CancellationToken cancellationToken)
        {
            await _orderApplication.OrderVisitWeb(dto, cancellationToken);
        }

        /// <summary>
        /// 订阅省工单延期消息
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.SharingOrderDelayResult)]
        public async Task OrderDelayWeb(ProvinceSendDelayResultDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.GetAsync(x => x.ReceiveProvinceNo == dto.No, cancellationToken);
            if (order != null)
            {
                //SessionContextCreator.CreateSessionContext(_sessionContextProvider, dto.Source);
                // await _sessionContextCreator.CreateSessionContextAsync(dto.Source, cancellationToken);
                _sessionContextManager.ChangeSessionContext(dto.Source);

                //查询延期
                var orderDelay = await _orderDelayRepository
                    .GetAsync(x => x.OrderId == order.Id && x.DelayState == EDelayState.Examining, cancellationToken);
                if (orderDelay != null)
                {
                    orderDelay.AuditName = dto.AuditName;
                    orderDelay.AuditOrgName = dto.AuditOrgName;
                    orderDelay.AuditTime = dto.AuditTime;
                    orderDelay.AuditOpinion = dto.Opinion;

                    if (dto.Files != null && dto.Files.Any())
                        orderDelay.FileJson = await _fileRepository.AddFileAsync(dto.Files, orderDelay.Id, orderDelay.WorkflowId, cancellationToken);
                    await _orderDelayRepository.UpdateAsync(orderDelay, cancellationToken);

                    await _workflowApplication.HandleToEndAsync(orderDelay.WorkflowId, dto.Opinion, dto.Files,
                        reviewResult: dto.IsPass ? EReviewResult.Approval : EReviewResult.Failed, cancellationToken: cancellationToken);
                }
            }
        }

        /// <summary>
        /// 接收工单处理结果
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderReultSend)]
        public async Task RecOrderResultAsync(OrderResultDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.Queryable().Includes(x => x.OrderExtension).FirstAsync(x => x.Id == dto.OrderId, cancellationToken);
            if (order is null)
                throw new UserFriendlyException($"无效工单编号, orderId: {dto.OrderId}");
            if (string.IsNullOrEmpty(order.WorkflowId))
                throw new UserFriendlyException($"该工单未开启流程，orderId: {dto.OrderId}");

            //if (dto.Files != null && dto.Files.Any())
            //{
            //    order.FileJson = await _fileRepository.AddFileAsync(dto.Files, order.Id, order.WorkflowId,
            //        cancellationToken);
            //    await _orderRepository.FileAsync(order, cancellationToken);
            //}
            //var setting = _systemSettingCacheManager.GetSetting(SettingConstants.CityBaseConfiguration)?.SettingValue[0];
            //CityBaseConfiguration cityBase = JsonConvert.DeserializeObject<CityBaseConfiguration>(setting);

            //SessionContextCreator.CreateSessionContext(_sessionContextProvider, dto.Source);
            //await _sessionContextCreator.CreateSessionContextAsync(dto.Source, cancellationToken);
            _sessionContextManager.ChangeSessionContext(dto.Source);

            switch (dto.FinishType)
            {
                case "0":
                    //退回
                    //计算order 期满时间
                    ExpiredTimeWithConfig expiredTimeConfig;
                    if (_appOptions.Value.IsZiGong)
                    {
                        expiredTimeConfig =
                            await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToCenter,
                                order.Adapt<OrderTimeClacInfo>());
                    }
                    else
                    {
                        //期满时间
                        //expiredTimeConfig = _timeLimitDomainService.CalcExpiredTime(DateTime.Now, EFlowDirection.CenterToOrg, order.AcceptTypeCode);
                        expiredTimeConfig =
                            await _expireTime.CalcExpiredTime(DateTime.Now, DateTime.Now, EFlowDirection.CenterToOrg,
                                order.Adapt<OrderTimeClacInfo>());
                    }

                    _mapper.Map(expiredTimeConfig, order);
                    //退回:撤回至发起人
                    //await _workflowDomainService.RecallToStartStepAsync(order.WorkflowId, dto.Opinion, order.Status >= EOrderStatus.Filed,
                    //    order.ExpiredTime, cancellationToken); //todo think是否需要保存附件至省平台办理节点?

                    //var (isPaiDan, workflow) = await _workflowDomainService.RecallToCenterFirstToSendAsync(
                    //    order.WorkflowId, dto.Opinion, order.Status >= EOrderStatus.Filed, 
                    //    order.ExpiredTime, null, EHandleMode.Recall, cancellationToken);

                    // var reverseFlowStepAssignInfo = new ReverseFlowStepAssignInfo(EReverseFlowStepCreationPolicy.OriginStep);

                    var handleMode = order.OrderExtension is null ? EHandleMode.Recall : EHandleMode.ProvinceHandlePrevious;

                    var (isPaiDan, workflow) = await _workflowDomainService.RecallToCenterFirstToSendAsync(order.WorkflowId, dto.Opinion,
                        order.Status >= EOrderStatus.Filed, order.ExpiredTime, EHandleMode.ProvinceHandlePrevious,
                        cancellationToken: cancellationToken);

                    order.Status = isPaiDan ? EOrderStatus.Special : EOrderStatus.WaitForAccept;
                    order.CurrentStepName = workflow.CurrentStepName;
                    order.CurrentStepCode = workflow.CurrentStepCode;
                    order.CurrentStepId = workflow.CurrentStepId;
                    order.CurrentStepCreateTime = workflow.CurrentStepCreateTime;
                    order.CurrentHandleTime = workflow.CurrentHandleTime;
                    order.CurrentHandlerId = workflow.CurrentHandlerId;
                    order.CurrentHandlerName = workflow.CurrentHandlerName;
                    order.CurrentHandleOrgName = workflow.CurrentHandleOrgName;
                    order.CurrentHandleOrgId = workflow.CurrentHandleOrgId;
                    order.CurrentHandleOrgLevel = workflow.CurrentHandleOrgLevel;
                    order.CurrentHandleOrgAreaCode = workflow.CurrentHandleOrgAreaCode;
                    order.CurrentHandleOrgAreaName = workflow.CurrentHandleOrgAreaName;

                    await _orderRepository.UpdateAsync(order, cancellationToken);

                    break;
                case "1":
                    //办结:归档
                    //自贡需求：省12345平台向本地系统第一次推送办理意见时，工单即归档，承办意见取该办理意见；第二次推送办理意见时，工单承办意见需更新为第二次推送的办理意见
                    if (order.Status >= EOrderStatus.Filed)
                    {
                        if (_appOptions.Value.IsZiGong)
                        {
                            order.ActualOpinion = dto.Opinion;
                        }
                        else
                        {
                            order.ActualOpinion += dto.Opinion;
                        }

                        order.FileOpinion = order.ActualOpinion;
                        await _orderRepository.Updateable(order).UpdateColumns(d => d.ActualOpinion).UpdateColumns(d => d.FileOpinion)
                            .ExecuteCommandAsync(cancellationToken);
                        await _workflowDomainService.AppendFileOpinionAsync(order.WorkflowId, dto.Opinion, dto.Files, cancellationToken);
                    }
                    else
                    {
                        await _workflowApplication.HandleToEndAsync(order.WorkflowId, dto.Opinion, dto.Files, expiredTime: order.ExpiredTime,
                            cancellationToken: cancellationToken);
                    }

                    break;
            }

            //var now = DateTime.Now;
            //var handleDuration = order.StartTime.HasValue
            //    ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value,
            //        now, order.ProcessType is EProcessType.Zhiban)
            //    : 0;
            //var fileDuration = order.CenterToOrgTime.HasValue
            //    ? _timeLimitDomainService.CalcWorkTime(order.CenterToOrgTime.Value,
            //        now, order.ProcessType is EProcessType.Zhiban)
            //    : 0;
            //var allDuration = order.StartTime.HasValue
            //    ? _timeLimitDomainService.CalcWorkTime(order.StartTime.Value, now,
            //        order.ProcessType is EProcessType.Zhiban)
            //    : 0;
            //order.File(now, handleDuration, fileDuration, allDuration);
            //await _orderRepository.UpdateAsync(order, cancellationToken);
        }

        /// <summary>
        /// 接收工单扩展信息
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderExtends)]
        public async Task RecOrderExtensionAsync(OrderExtensionDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.Queryable()
                .FirstAsync(d => d.ReceiveProvinceNo == dto.ProvinceNo, cancellationToken);

            var orderExtension = await _orderDomainService.GetOrderExtensionsAsync(dto.ProvinceNo, cancellationToken);
            if (orderExtension is null)
            {
                orderExtension = _mapper.Map<OrderExtension>(dto);
                if (order != null)
                    orderExtension.Id = order.Id;
                await _orderExtensionRepository.AddAsync(orderExtension, cancellationToken);
            }
            else
            {
                _mapper.Map(dto, orderExtension);
                if (order != null)
                    orderExtension.Id = order.Id;
                await _orderExtensionRepository.UpdateAsync(orderExtension, cancellationToken);
            }
        }

        /// <summary>
        /// 接收工单办理流程
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderAddTraces)]
        public async Task RecOrderTracesAsync(AddOrderTracesDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.GetAsync(dto.OrderId, cancellationToken);
            if (order is null)
                throw new UserFriendlyException($"未查询到对应工单，orderId: {dto.OrderId}");
            if (string.IsNullOrEmpty(order.WorkflowId))
                throw new UserFriendlyException($"该工单未开启流程，orderId: {dto.OrderId}");

            var steps = dto.Traces.Select(d =>
            {
                var step = _mapper.Map<WorkflowStep>(d);
                step.WorkflowId = order.WorkflowId;
                step.WorkflowTrace = _mapper.Map<WorkflowTrace>(step);
                return step;
            }).ToList();

            await _workflowDomainService.AddStepsAsync(order.WorkflowId, steps, cancellationToken);
        }

        /// <summary>
        /// 接收工单补充内容
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderSupplements)]
        public async Task RecOrderSupplementsAsync(AddOrderComplementDto dto, CancellationToken cancellationToken)
        {
            var order = await _orderRepository.GetAsync(d => d.ReceiveProvinceNo == dto.CaseSerial, cancellationToken);
            if (order is null)
                throw new UserFriendlyException("无效省工单编号");
            dto.OrderId = order.Id;
            dto.IsProComplement = true;
            await _orderDomainService.AddOrderComplementAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 接收省上上传附件
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        [CapSubscribe(EventNames.SharingFileInfo)]
        public async Task RecFilesAsync(ReceiveFilesFromDsDto dto, CancellationToken cancellationToken)
        {
            if (dto.Files == null || !dto.Files.Any())
                throw new UserFriendlyException("未收到任何附件");

            switch (dto.DsBisType)
            {
                case EDsBisType.AcceptOrder:
                    var order = await _orderRepository.GetAsync(d => d.ReceiveProvinceNo == dto.ProvinceNo, cancellationToken);
                    if (order is null)
                        throw new UserFriendlyException("无效省工单编号");

                    order.FileJson = await _fileRepository.AddFileAsync(dto.Files, order.Id, "", cancellationToken);
                    await _orderRepository.UpdateAsync(order, cancellationToken);
                    break;
                case EDsBisType.OrderPreviousResult:
                    var sendBack = await _orderSendBackRepository.Queryable()
                        .Where(d => d.Order.ReceiveProvinceNo == dto.ProvinceNo)
                        .FirstAsync(cancellationToken);
                    if (sendBack is null)
                        throw new UserFriendlyException("无效省工单退回编号");

                    sendBack.FileJson = await _fileRepository.AddFileAsync(dto.Files, sendBack.Id, string.Empty, cancellationToken);
                    await _orderSendBackRepository.UpdateAsync(sendBack, cancellationToken);
                    break;
                case EDsBisType.SendOrderSupervise:
                    var orderSupervise = await _orderSuperviseRepository
                        .GetAsync(d => d.SuperviseSerial == dto.SuperviseId, cancellationToken);
                    if (orderSupervise is null)
                        throw new UserFriendlyException("无效省工单督办编号");

                    orderSupervise.FileJson = await _fileRepository.AddFileAsync(dto.Files, orderSupervise.Id, "", cancellationToken);
                    await _orderSuperviseRepository.AddAsync(orderSupervise, cancellationToken);
                    break;
                case EDsBisType.SendOrderUrge:
                    var orderUrge = await _orderUrgeRepository
                        .GetAsync(d => d.DsBisId == dto.DsBisId, cancellationToken);
                    if (orderUrge is null)
                        throw new UserFriendlyException("无效省工单催办业务编号");

                    orderUrge.FileJson = await _fileRepository.AddFileAsync(dto.Files, orderUrge.Id, "", cancellationToken);
                    await _orderUrgeRepository.UpdateAsync(orderUrge, cancellationToken);
                    break;
                case EDsBisType.OrderScreenResult:
                    var orderScreen = await _orderScreenRepository.Queryable()
                        .Where(x => x.Order.ReceiveProvinceNo == dto.ProvinceNo && x.Status == Share.Enums.Order.EScreenStatus.Approval)
                        .FirstAsync(cancellationToken);
                    if (orderScreen is null)
                        throw new UserFriendlyException("未查询到对应省工单甄别数据");

                    orderScreen.FileJson = await _fileRepository.AddFileAsync(dto.Files, orderScreen.Id, "", cancellationToken);
                    await _orderScreenRepository.UpdateAsync(orderScreen, cancellationToken);
                    break;
                case EDsBisType.OrderDelayResult:
                    var orderDelay = await _orderDelayRepository.Queryable()
                        .Where(d => d.Order.ReceiveProvinceNo == dto.ProvinceNo && d.DelayState == EDelayState.Examining)
                        .FirstAsync(cancellationToken);
                    if (orderDelay is null)
                        throw new UserFriendlyException($"未查询到延期数据, ProvinceNo: {dto.ProvinceNo}");

                    if (dto.Files != null && dto.Files.Any())
                        orderDelay.FileJson = await _fileRepository.AddFileAsync(dto.Files, orderDelay.Id, orderDelay.WorkflowId, cancellationToken);
                    await _orderDelayRepository.UpdateAsync(orderDelay, cancellationToken);
                    break;
                case EDsBisType.SendOrderComplement:
                    var complement = await _orderComplementRepository
                        .GetAsync(d => d.DsBisId == dto.DsBisId, cancellationToken);
                    if (complement is null)
                        throw new UserFriendlyException(
                            $"未查询到补充信息, ProvinceNo: {dto.ProvinceNo}, DsBisIs: {dto.DsBisId}");

                    if (dto.Files.Any()) complement.FileJson = await _fileRepository.AddFileAsync(dto.Files, complement.Id, "", cancellationToken);
                    await _orderComplementRepository.UpdateAsync(complement, cancellationToken);
                    break;
                case EDsBisType.OrderHandleResult:
                    var order1 = await _orderRepository.GetAsync(d => d.ProvinceNo == dto.ProvinceNo, cancellationToken);
                    if (order1 is null)
                        throw new UserFriendlyException($"无效工单编号, ProvinceNo: {dto.ProvinceNo}");
                    if (string.IsNullOrEmpty(order1.WorkflowId))
                        throw new UserFriendlyException($"该工单未开启流程，ProvinceNo: {dto.ProvinceNo}");
                    await _workflowApplication.UpdateProvinceHandleResultFilesAsync(order1.WorkflowId, dto.Files, cancellationToken);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        /// <summary>
        /// 接收市州互转返回数据
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderTranspondCity)]
        public async Task RecTranspondCityRawDataAsync(TranspondCityRawDataDto dto, CancellationToken cancellationToken)
        {
            var data = await _transpondCityRawDataRepository.GetAsync(p => p.OrderCode == dto.OrderCode && p.Direction == ETranspondDirection.Out,
                cancellationToken);
            if (data != null)
            {
                data.IsSuccess = dto.IsSuccess;
                data.SendTimes = dto.SendTimes;
                data.Result = dto.Result;
                data.NewCode = dto.NewCode;
                await _transpondCityRawDataRepository.UpdateAsync(data, cancellationToken);
            }
        }

        /// <summary>
        /// 接收市州互转接收原始数据
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderReceiveTranspondCity)]
        public async Task RecTranspondCityReceiveRawDataAsync(TranspondCityRawDataDto dto, CancellationToken cancellationToken)
        {
            await _transpondCityRawDataRepository.AddAsync(_mapper.Map<TranspondCityRawData>(dto), cancellationToken);
        }

        /// <summary>
        /// 接收市州互转办理结果
        /// </summary>
        [CapSubscribe(EventNames.SharingOrderReceiveHandleOpinionTranspondCity)]
        public async Task RecTranspondCityReceiveResultAsync(TranspondCityOrderResultDto dto, CancellationToken cancellationToken)
        {
            var cityDataUndertakAdvice = _systemSettingCacheManager.GetSetting(SettingConstants.CityDataUndertakAdvice)?.SettingValue[0];
            if (cityDataUndertakAdvice == "true")
            {
                var order = await _orderRepository.GetAsync(p => p.No == dto.No, cancellationToken);
                if (order != null)
                {
                    order.ActualOpinion = dto.Opinion;
                    await _orderRepository.UpdateAsync(order, cancellationToken);
                    //后面还需要处理流程中的意见
                }
            }

            //修改推送数据办理结果
            var data = await _transpondCityRawDataRepository.GetAsync(p => p.OrderCode == dto.No && p.Direction == ETranspondDirection.Out,
                cancellationToken);
            if (data != null)
            {
                data.ActualOpinion = dto.Opinion;
                await _transpondCityRawDataRepository.UpdateAsync(data, cancellationToken);
            }
        }

        /// <summary>
        /// 应急管理局推送回调
        /// </summary>
        /// <returns></returns>
        [CapSubscribe(EventNames.HotlineOrderContingencyManagementState)]
        public async Task RecHotlineOrderContingencyManagementState(RecOrderStateDto dto, CancellationToken cancellationToken)
        {
            var data = await _contingencyManagementOrdersRepository.GetAsync(p => p.Id == dto.Id, cancellationToken);
            if (data != null && dto.State != data.PushState)
            {
                data.PushState = dto.State;
                await _contingencyManagementOrdersRepository.UpdateAsync(data, cancellationToken);
            }
        }

        /// <summary>
        /// 处理每天办理完成未及时推送办理结果的数据
        /// </summary>
        /// <param name="provinceNos"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.HotlineFiledOrdersRepublish)]
        public async Task RepublishFiledOrders(List<string> provinceNos, CancellationToken cancellationToken)
        {
            var unpublishOrders = await _orderRepository.Queryable()
                .Where(d => provinceNos.Contains(d.ProvinceNo) &&
                            !string.IsNullOrEmpty(d.ProvinceNo) &&
                            d.Status >= EOrderStatus.Filed)
                .ToListAsync(cancellationToken);

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

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

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

        /// <summary>
        ///  随手拍网格员、回复办理结果
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.TianQueReceiverOpinion)]
        public async Task TianQueReceiverOpinion(TianQueReceiverOpinionDto dto, CancellationToken cancellationToken)
        {
            //todo
        }

        /// <summary>
        ///  天阙推送工单，返回信息
        /// </summary>
        /// <returns></returns>
        [CapSubscribe(EventNames.TianQuePushOrderReceiver)]
        public async Task TianQuePushOrderReceiver(TianQuePushOrderReceiverDto dto, CancellationToken cancellationToken)
        {
            //todo
        }

        /// <summary>
        /// 收到shangring提供未关联callIds
        /// </summary>
        [CapSubscribe(EventNames.RecUnrelationCalls)]
        public async Task RecUnRelationCallIds(List<string> callIds, CancellationToken cancellationToken)
        {
            if (_appOptions.Value.GetDefaultAppScopeConfiguration().CallCenterType == AppDefaults.CallCenterType.XingTang)
            {
                try
                {
                    var query = await _orderRepository.Queryable()
                        .LeftJoin<CallNative>((o, c) => o.CallId == c.Id)
                        .Where((o, c) => !SqlFunc.IsNullOrEmpty(o.CallId) && callIds.Contains(o.CallId))
                        .Select((o, c) => new { Order = o, Call = c })
                        .ToListAsync(cancellationToken);
                    if (!query.Any()) return;
                    var orderCalls = query
                        .Where(d => !string.IsNullOrEmpty(d.Call.Id))
                        .Select(d => new PublishCallRecrodDto
                        {
                            Order = _mapper.Map<OrderDto>(d.Order),
                            TrCallRecordDto = _mapper.Map<TrCallDto>(d.Call)
                        }).ToList();

                    foreach (var orderCall in orderCalls)
                    {
                        await _capPublisher.PublishAsync(EventNames.SharingOrderWithCallInfo, orderCall,
                            cancellationToken: cancellationToken);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e.Message);
                }
            }
        }

        /// <summary>
        /// 将未匹配到通话记录的工单处理为QT
        /// </summary>
        /// <param name="orderIds"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.RecUpdateOrderSourceChannel)]
        public async Task UpdateOrderSourceChannel(List<string> orderIds, CancellationToken cancellationToken)
        {
            if (orderIds != null && orderIds.Any())
            {
                foreach (var item in orderIds)
                {
                    var orderData = await _orderRepository.GetAsync(p => p.Id == item || p.ProvinceNo == item, cancellationToken);

                    if (orderData != null)
                    {
                        orderData.SourceChannel = "其他";
                        orderData.SourceChannelCode = "QT";

                        var orderDto = _mapper.Map<OrderDto>(orderData);
                        await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlineOrderExpiredTimeUpdate, orderDto,
                            cancellationToken: cancellationToken);
                    }
                }
            }
        }
    }
}