using DataSharing.LuZhou;
using DataSharing.Police110;
using DataSharing.Province;
using DataSharing.RawData;
using DataSharing.SendTask;
using DataSharing.Share.Dtos.Province.HuiJu;
using DataSharing.Share.Dtos.Province.XieTong.Send;
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.Order;
using Hotline.Share.Mq;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace DataSharing.Application.Receivers
{
    public class ProvinceReceiver : ICapSubscribe, IScopeDependency
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly ILogger<ProvinceReceiver> _logger;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IProvinceService _provinceService;
        private readonly IRepository<DsOrderSend> _orderSendRepository;
        private readonly ISendTaskDataService _sendTaskDataService;
        private readonly IPoliceService _policeService;
        private readonly ILuZhou110Service _luZhou110Service;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="dsOrderRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="provinceService"></param>
        /// <param name="orderSendRepository"></param>
        /// <param name="sendTaskDataService"></param>
        /// <param name="policeService"></param>
        public ProvinceReceiver(IMapper mapper, ILogger<ProvinceReceiver> logger,
             IRepository<DsOrder> dsOrderRepository,
             ISharingConfigurationManager sharingConfigurationManager,
             IProvinceService provinceService,
              IRepository<DsOrderSend> orderSendRepository,
              ISendTaskDataService sendTaskDataService,
              IPoliceService policeService,
              ILuZhou110Service luZhou110Service)
        {
            _mapper = mapper;
            _logger = logger;
            _dsOrderRepository = dsOrderRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
            _provinceService = provinceService;
            _orderSendRepository = orderSendRepository;
            _sendTaskDataService = sendTaskDataService;
            _policeService = policeService;
            _luZhou110Service = luZhou110Service;
        }
        #endregion

        #region 协同-第一批次

        /// <summary>
        /// 退回申请
        /// </summary>
        /// <param name="dtos"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderFlowPrevious)]
        public async Task GetCaseBackApplyAsync(PublishOrderSendBackDto dtos, CancellationToken cancellationToken)
        {
            if (dtos != null && dtos.SendDatas != null)
            {
                //调用省退回申请
                await _provinceService.GetCaseBackApplyAsync(dtos, cancellationToken);
            }
        }

        /// <summary>
        /// 服务工单督办过程
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderSuperviseCourse)]
        public async Task SendSuperviseProcessInfoAsync(PublishSuperviseDto dto, CancellationToken cancellationToken)
        {
            //工单是省上派下来的，才能进行督办回复
            if (dto.Order.Source == ESource.ProvinceStraight)
            {
                //服务工单督办过程
                await _provinceService.SendSuperviseProcessInfoAsync(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 服务工单督办结果
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderSuperviseResult)]
        public async Task SendSuperviseResultInfoAsync(PublishSuperviseDto dto, CancellationToken cancellationToken)
        {
            //工单是省上派下来的，才能进行督办回复
            if (dto.Order.Source == ESource.ProvinceStraight)
            {
                //服务工单督办结果
                await _provinceService.SendSuperviseResultInfoAsync(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 工单发起甄别
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderScreenApply)]
        public async Task ScreenCaseInfoSendAsync(PublishScreenDto dto, CancellationToken cancellationToken)
        {
            //如果是省上派下来的工单，才能调发起甄别的接口
            if (dto.Order.Source == ESource.ProvinceStraight && dto.Order.IsProvince)
            {
                //工单发起甄别
                await _provinceService.ScreenCaseInfoSendAsync(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 服务工单申请延时
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderApplyDelay)]
        public async Task DelayCaseInfoSendAsync(PublishOrderDelayDto dto, CancellationToken cancellationToken)
        {
            //服务工单申请延时
            await _provinceService.DelayCaseInfoSendAsync(dto, cancellationToken);
        }

        #endregion

        #region 汇聚-第二批次

        /// <summary>
        /// 热线工单流程开启 --服务工单受理
        /// </summary>
        /// <param name="pushdto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderFlowStarted)]
        public async Task OrderFlowStartedAsync(PublishCallRecrodDto pushdto, CancellationToken cancellationToken)
        {
            var dto = pushdto.Order;

            #region 本地保存工单基础数据
            //本地保存工单基础数据---存在修改，不存在新增
            var dataOrder = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Id, cancellationToken);
            if (dataOrder == null)
            {
                dataOrder = new()
                {
                    Id = dto.Id,
                    OrderId = dto.Id,
                    OrderNo = dto.No,
                    ProvinceNo = dto.ProvinceNo,
                    WorkflowId = dto.WorkflowId,
                    Password = dto.Password,
                    Title = dto.Title,
                    FromName = dto.FromName,
                    Contact = dto.Contact,
                    Content = dto.Content,
                    CaseDate = Convert.ToDateTime(dto.CreationTime),
                    Source = dto.Source.ToString(),
                    CaseSource = dto.SourceChannel,
                    CaseSourceCode = dto.SourceChannelCode,
                    HotspotId = dto.HotspotId,
                    HotspotName = dto.HotspotName,
                    HotspotSpliceName = dto.HotspotSpliceName,
                    ExpiredTime = dto.ExpiredTime,
                    CaseType = dto.AcceptType,
                    CaseTypeCode = dto.AcceptTypeCode,
                    AllDuration = 0,
                    IsProvince = dto.IsProvince,
                    HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中",
                    StartTime = dto.StartTime,
                    CallId = dto.CallId,
                    FullAddress = dto.FullAddress,
                    AreaCode = dto.AreaCode,
                    FileJson = _mapper.Map<List<FileJson>>(dto.FileJson)
                };

                try
                {
                    await _dsOrderRepository.AddAsync(dataOrder, cancellationToken);
                }
                catch (Exception ex)
                {
                    //如果报错则直接在此查询，有就直接修改
                    var dataOrderNew = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Id, cancellationToken);
                    if (dataOrderNew != null)
                    {
                        dataOrderNew.ProvinceNo = dto.ProvinceNo;
                        dataOrderNew.WorkflowId = dto.WorkflowId;
                        dataOrderNew.Password = dto.Password;
                        dataOrderNew.Title = dto.Title;
                        dataOrderNew.FromName = dto.FromName;
                        dataOrderNew.Contact = dto.Contact;
                        dataOrderNew.Content = dto.Content;
                        dataOrderNew.CaseDate = Convert.ToDateTime(dto.CreationTime);
                        dataOrderNew.Source = dto.Source.ToString();
                        dataOrderNew.CaseSource = dto.SourceChannel;
                        dataOrderNew.CaseSourceCode = dto.SourceChannelCode;
                        dataOrderNew.HotspotId = dto.HotspotId;
                        dataOrderNew.HotspotName = dto.HotspotName;
                        dataOrderNew.HotspotSpliceName = dto.HotspotSpliceName;
                        dataOrderNew.ExpiredTime = dto.ExpiredTime;
                        dataOrderNew.CaseType = dto.AcceptType;
                        dataOrderNew.CaseTypeCode = dto.AcceptTypeCode;
                        dataOrderNew.AllDuration = 0;
                        dataOrderNew.IsProvince = dto.IsProvince;
                        dataOrderNew.HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                        dataOrderNew.StartTime = dto.StartTime;
                        dataOrderNew.CallId = dto.CallId;
                        dataOrderNew.ActualHandleTime = dto.ActualHandleTime;
                        dataOrderNew.FullAddress = dto.FullAddress;
                        dataOrderNew.AreaCode = dto.AreaCode;
                        dataOrderNew.FileJson = _mapper.Map<List<FileJson>>(dto.FileJson);
                        await _dsOrderRepository.UpdateAsync(dataOrderNew, cancellationToken);
                    }
                }
            }
            else
            {
                dataOrder.ProvinceNo = dto.ProvinceNo;
                dataOrder.WorkflowId = dto.WorkflowId;
                dataOrder.Password = dto.Password;
                dataOrder.Title = dto.Title;
                dataOrder.FromName = dto.FromName;
                dataOrder.Contact = dto.Contact;
                dataOrder.Content = dto.Content;
                dataOrder.CaseDate = Convert.ToDateTime(dto.CreationTime);
                dataOrder.Source = dto.Source.ToString();
                dataOrder.CaseSource = dto.SourceChannel;
                dataOrder.CaseSourceCode = dto.SourceChannelCode;
                dataOrder.HotspotId = dto.HotspotId;
                dataOrder.HotspotName = dto.HotspotName;
                dataOrder.HotspotSpliceName = dto.HotspotSpliceName;
                dataOrder.ExpiredTime = dto.ExpiredTime;
                dataOrder.CaseType = dto.AcceptType;
                dataOrder.CaseTypeCode = dto.AcceptTypeCode;
                dataOrder.AllDuration = 0;
                dataOrder.IsProvince = dto.IsProvince;
                dataOrder.HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                dataOrder.StartTime = dto.StartTime;
                dataOrder.CallId = dto.CallId;
                dataOrder.ActualHandleTime = dto.ActualHandleTime;
                dataOrder.FullAddress = dto.FullAddress;
                dataOrder.AreaCode = dto.AreaCode;
                dataOrder.FileJson = _mapper.Map<List<FileJson>>(dto.FileJson);

                await _dsOrderRepository.UpdateAsync(dataOrder, cancellationToken);
            }
            #endregion

            #region 工单推送数据处理
            var orderSend = await _orderSendRepository.GetAsync(p => p.OrderId == dto.Id, cancellationToken);
            if (orderSend != null)
            {
                orderSend.CaseDate = Convert.ToDateTime(dto.CreationTime);
                orderSend.StartTime = dto.StartTime;
                orderSend.CallId = dto.CallId;
                orderSend.Source = dto.Source.ToString();
                orderSend.CaseSource = dto.SourceChannel;
                orderSend.CaseSourceCode = dto.SourceChannelCode;
                orderSend.ExpiredTime = dto.ExpiredTime;
                orderSend.HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                orderSend.ActualHandleTime = dto.ActualHandleTime;
                orderSend.FiledTime = dto.FiledTime;
                await _orderSendRepository.UpdateAsync(orderSend, cancellationToken);
            }
            else
            {
                orderSend = new DsOrderSend()
                {
                    Id = dto.Id,
                    OrderId = dto.Id,
                    Title = dto.Title,
                    OrderNo = dto.No,
                    ProvinceNo = dto.ProvinceNo,
                    CaseDate = Convert.ToDateTime(dto.CreationTime),
                    StartTime = dto.StartTime,
                    CallId = dto.CallId,
                    Source = dto.Source.ToString(),
                    CaseSource = dto.SourceChannel,
                    CaseSourceCode = dto.SourceChannelCode,
                    ExpiredTime = dto.ExpiredTime,
                    HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中",
                };
                try
                {
                    await _orderSendRepository.AddAsync(orderSend, cancellationToken);
                }
                catch (Exception ex)
                {
                    var orderSendNew = await _orderSendRepository.GetAsync(p => p.OrderId == dto.Id, cancellationToken);
                    if (orderSendNew != null)
                    {
                        orderSendNew.CaseDate = Convert.ToDateTime(dto.CreationTime);
                        orderSendNew.StartTime = dto.StartTime;
                        orderSendNew.CallId = dto.CallId;
                        orderSendNew.Source = dto.Source.ToString();
                        orderSendNew.CaseSource = dto.SourceChannel;
                        orderSendNew.CaseSourceCode = dto.SourceChannelCode;
                        orderSendNew.ExpiredTime = dto.ExpiredTime;
                        orderSendNew.HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                        await _orderSendRepository.UpdateAsync(orderSendNew, cancellationToken);
                    }
                }
            }
            #endregion

            //热线工单流程开启 --服务工单受理
            await _provinceService.OrderFlowStartedAsync(pushdto, cancellationToken);

            #region 泸州110独有业务，如果是110派来的工单，流程开启后传签收状态
            try
            {
                if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                {
                    //泸州110独有业务，如果是110派来的工单，流程开启后传签收状态
                    if (dto.Source == ESource.Police110)
                    {
                        await _policeService.SingForPoliceAsync(dto, cancellationToken);
                    }
                }
            }
            catch (Exception)
            {
            }
            #endregion

            //自贡独有业务，符合要求的工单推送至智慧城市系统
            #region 自贡独有业务，符合要求的工单推送至智慧城市系统
            try
            {
                if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                {
                    //自贡110独有业务，如果是110派来的工单，流程开启后传签收状态
                    if (dto.Source == ESource.Police110)
                    {
                        await _policeService.SingForPoliceAsync(dto, cancellationToken);
                    }

                    if (_sharingConfigurationManager.GetZiGongConfig().SmartCitySystem.IsSendPush == true)
                    {
                        //自贡智慧城市系统
                        if (!string.IsNullOrEmpty(dto.OrderTagCode) && dto.OrderTagCode.IndexOf("zgdh") > -1)
                        {
                            //其他服务推送
                            await _sendTaskDataService.OtherSendTask("zgdh", dto, cancellationToken);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            #endregion

            //是否需要往第三方推送
            await OrderDispatchAsync(new OrderFlowDto { Order = pushdto.Order, WorkflowTrace = pushdto.WorkflowTrace, ExpiredTimeChanged = false }, cancellationToken);

        }

        /// <summary>
        /// 热线工单期满时间变更--推送服务工单受理
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderExpiredTimeUpdate)]
        public async Task HotlineOrderFlowRecalledAsync(OrderDto dto, CancellationToken cancellationToken)
        {
            //调用热线工单期满时间变更--推送服务工单受理
            await _provinceService.HotlineOrderFlowRecalledAsync(dto, cancellationToken);

            //修改工单的期满时间
            var dataOrder = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Id, cancellationToken);
            if (dataOrder != null)
            {
                dataOrder.ExpiredTime = dto.ExpiredTime;
                //dataOrder.Source = dto.Source.ToString();
                //dataOrder.CaseSource = dto.SourceChannel;
                //dataOrder.CaseSourceCode = dto.SourceChannelCode;
                dataOrder.HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                await _dsOrderRepository.UpdateAsync(dataOrder, cancellationToken);
            }

            //修改工单推送表期满时间
            var orderSend = await _orderSendRepository.GetAsync(p => p.OrderId == dto.Id, cancellationToken);
            if (orderSend != null)
            {
                orderSend.ExpiredTime = dto.ExpiredTime;
                orderSend.Source = dto.Source.ToString();
                orderSend.CaseSource = dto.SourceChannel;
                orderSend.CaseSourceCode = dto.SourceChannelCode;
                orderSend.HandleState = dto.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                await _orderSendRepository.UpdateAsync(orderSend, cancellationToken);
            }
        }

        /// <summary>
        /// 热线工单办理---服务工单处理/服务工单交办处理过程
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderFlowHandled)]
        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 _provinceService.SubmitCaseProcessAsync(dto, cancellationToken);

            //是否需要往第三方推送
            await OrderDispatchAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 补充流程节点附件
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderFlowFile)]
        public async Task SupplementFilesAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            await _provinceService.SupplementFilesAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 回访完成---服务工单回访评价/服务工单交办评价
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderVisited)]
        public async Task SubmitVisitInfoAsync(PublishVisitDto dto, CancellationToken cancellationToken)
        {
            await _provinceService.SubmitVisitInfoDataAsync(dto, cancellationToken);

            //组装处理110数据
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong) == false && dto.Order.Source == ESource.Police110)
                await _policeService.Visit(dto, cancellationToken);

            //自贡110处理回访数据
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
            {
                if (dto.Order.ActualHandleOrgCode == _sharingConfigurationManager.GetPoliceOrgCode()
                    || dto.Order.OrgLevelOneCode == _sharingConfigurationManager.GetPoliceOrgCode() || dto.Order.Source == ESource.Police110)
                    await _policeService.Visit(dto, cancellationToken);
            }

            //泸州110推送
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
            {
                await _luZhou110Service.InitVisitData(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 甄别通过---服务工单回访评价//服务工单交办评价
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderScreenApplyed)]
        public async Task SubmitOrderScreenSuccessAsync(PublishVisitDto dto, CancellationToken cancellationToken)
        {
            //推省上
            await _provinceService.SubmitVisitInfoDataAsync(dto, cancellationToken);

            //组装处理110数据
            if (dto.Order.Source == ESource.Police110)
            {
                await _policeService.Visit(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 热线工单归档---服务工单结果/服务工单交办处理结果
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderFiled)]
        public async Task OrderFiledAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            #region 工单推送数据处理
            //修改工单基础数据
            var dataOrder = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Order.Id, cancellationToken);
            if (dataOrder != null)
            {
                dataOrder.HandleState = "办理完成";
                dataOrder.ActualHandleOrgName = dto.Order.ActualHandleOrgName;
                dataOrder.ActualHandleOrgCode = dto.Order.ActualHandleOrgCode;
                dataOrder.ActualHandlerId = dto.Order.ActualHandlerId;
                dataOrder.ActualHandlerName = dto.Order.ActualHandlerName;
                dataOrder.ActualOpinion = string.IsNullOrEmpty(dto.Order.ActualOpinion) == false ? dto.Order.ActualOpinion : dto.WorkflowTrace.Opinion;
                dataOrder.ActualHandleTime = dto.Order.ActualHandleTime;
                dataOrder.AllDuration = dto.Order.AllDuration;
                dataOrder.ExpiredTime = dto.Order.ExpiredTime;
                dataOrder.Source = dto.Order.Source.ToString();
                dataOrder.CaseSource = dto.Order.SourceChannel;
                dataOrder.CaseSourceCode = dto.Order.SourceChannelCode;
                dataOrder.FullAddress = dto.Order.FullAddress;
                dataOrder.AreaCode = dto.Order.AreaCode;
                await _dsOrderRepository.UpdateAsync(dataOrder, cancellationToken);
            }
            else
            {
                var order = dto.Order;
                dataOrder = new()
                {
                    Id = order.Id,
                    OrderId = order.Id,
                    OrderNo = order.No,
                    ProvinceNo = order.ProvinceNo,
                    WorkflowId = order.WorkflowId,
                    Password = order.Password,
                    Title = order.Title,
                    FromName = order.FromName,
                    Contact = order.Contact,
                    Content = order.Content,
                    CaseDate = Convert.ToDateTime(order.CreationTime),
                    Source = order.Source.ToString(),
                    CaseSource = order.SourceChannel,
                    CaseSourceCode = order.SourceChannelCode,
                    HotspotId = order.HotspotId,
                    HotspotName = order.HotspotName,
                    HotspotSpliceName = order.HotspotSpliceName,
                    ExpiredTime = order.ExpiredTime,
                    CaseType = order.AcceptType,
                    CaseTypeCode = order.AcceptTypeCode,
                    AllDuration = dto.Order.AllDuration,
                    IsProvince = order.IsProvince,
                    HandleState = "办理完成",
                    ActualHandleOrgName = order.ActualHandleOrgName,
                    ActualHandleOrgCode = order.ActualHandleOrgCode,
                    ActualHandlerId = order.ActualHandlerId,
                    ActualHandlerName = order.ActualHandlerName,
                    ActualOpinion = string.IsNullOrEmpty(order.ActualOpinion) == false ? order.ActualOpinion : dto.WorkflowTrace.Opinion,
                    ActualHandleTime = order.ActualHandleTime,
                    StartTime = order.StartTime,
                    CallId = order.CallId,
                    AreaCode = order.AreaCode,
                    FullAddress = order.FullAddress,
                    FileJson = _mapper.Map<List<FileJson>>(order.FileJson)
                };

                try
                {
                    await _dsOrderRepository.AddAsync(dataOrder, cancellationToken);
                }
                catch (Exception ex)
                {
                    var dataOrderNew = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Order.Id, cancellationToken);
                    if (dataOrderNew != null)
                    {
                        dataOrderNew.HandleState = "办理完成";
                        dataOrderNew.ActualHandleOrgName = dto.Order.ActualHandleOrgName;
                        dataOrderNew.ActualHandleOrgCode = dto.Order.ActualHandleOrgCode;
                        dataOrderNew.ActualHandlerId = dto.Order.ActualHandlerId;
                        dataOrderNew.ActualHandlerName = dto.Order.ActualHandlerName;
                        dataOrderNew.ActualOpinion = string.IsNullOrEmpty(dto.Order.ActualOpinion) == false ? dto.Order.ActualOpinion : dto.WorkflowTrace.Opinion;
                        dataOrderNew.ActualHandleTime = dto.Order.ActualHandleTime;
                        dataOrderNew.AllDuration = dto.Order.AllDuration;
                        dataOrderNew.ExpiredTime = dto.Order.ExpiredTime;
                        dataOrderNew.FullAddress = dto.Order.FullAddress;
                        await _dsOrderRepository.UpdateAsync(dataOrderNew, cancellationToken);
                    }
                }

            }

            //工单推送数据处理
            var orderSend = await _orderSendRepository.GetAsync(p => p.OrderId == dto.Order.Id, cancellationToken);
            if (orderSend != null)
            {
                orderSend.HandleState = "办理完成";
                orderSend.ActualHandleTime = dto.Order.ActualHandleTime;
                orderSend.FiledTime = dto.Order.FiledTime;
                orderSend.CaseDate = Convert.ToDateTime(dto.Order.CreationTime);
                orderSend.StartTime = dto.Order.StartTime;
                orderSend.CallId = dto.Order.CallId;
                orderSend.Source = dto.Order.Source.ToString();
                orderSend.CaseSource = dto.Order.SourceChannel;
                orderSend.CaseSourceCode = dto.Order.SourceChannelCode;
                orderSend.ExpiredTime = dto.Order.ExpiredTime;
                await _orderSendRepository.UpdateAsync(orderSend, cancellationToken);
            }
            else
            {
                orderSend = new DsOrderSend()
                {
                    Id = dto.Order.Id,
                    OrderId = dto.Order.Id,
                    OrderNo = dto.Order.No,
                    Title = dto.Order.Title,
                    ProvinceNo = dto.Order.ProvinceNo,
                    CaseDate = Convert.ToDateTime(dto.Order.CreationTime),
                    StartTime = dto.Order.StartTime,
                    CallId = dto.Order.CallId,
                    Source = dto.Order.Source.ToString(),
                    CaseSource = dto.Order.SourceChannel,
                    CaseSourceCode = dto.Order.SourceChannelCode,
                    ExpiredTime = dto.Order.ExpiredTime,
                    HandleState = dto.Order.Status >= EOrderStatus.Filed ? "办理完成" : "办理中",
                    ActualHandleTime = dto.Order.ActualHandleTime,
                    FiledTime = dto.Order.FiledTime,
                };
                try
                {
                    await _orderSendRepository.AddAsync(orderSend, cancellationToken);
                }
                catch (Exception)
                {
                    var orderSendNew = await _orderSendRepository.GetAsync(p => p.OrderId == dto.Order.Id, cancellationToken);
                    if (orderSendNew != null)
                    {
                        orderSendNew.HandleState = dto.Order.Status >= EOrderStatus.Filed ? "办理完成" : "办理中";
                        orderSendNew.ActualHandleTime = dto.Order.ActualHandleTime;
                        orderSendNew.FiledTime = dto.Order.FiledTime;
                        orderSendNew.CaseDate = Convert.ToDateTime(dto.Order.CreationTime);
                        orderSendNew.StartTime = dto.Order.StartTime;
                        orderSendNew.CallId = dto.Order.CallId;
                        orderSendNew.Source = dto.Order.Source.ToString();
                        orderSendNew.CaseSource = dto.Order.SourceChannel;
                        orderSendNew.CaseSourceCode = dto.Order.SourceChannelCode;
                        orderSendNew.ExpiredTime = dto.Order.ExpiredTime;
                        orderSendNew.ActualHandleTime = dto.Order.ActualHandleTime;
                        orderSendNew.FiledTime = dto.Order.FiledTime;
                        await _orderSendRepository.UpdateAsync(orderSendNew, cancellationToken);
                    }
                }

            }
            #endregion

            //推省上
            await _provinceService.OrderFiledAsync(dto, cancellationToken);

            //如果是110来源工单，如果非警情退回未true,则退回110，否则就写入办理记录
            if (dto.Order.Source == ESource.Police110)
            {
                if (dto.IsNonPoliceReturn == true)
                    await _policeService.ReturnPoliceAsync(dto.Order, cancellationToken);
                else
                    await _policeService.InitPoliceSendChainDealAsync(dto, cancellationToken);
            }

            //市州其他业务推送办理结果
            await _sendTaskDataService.AddHandleOpinion(dto, cancellationToken);

            //自贡110独有业务，接收到110推送的办理结果，需要反馈结果签收
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
            {
                try
                {
                    if (dto.Order.ActualHandleOrgCode == _sharingConfigurationManager.GetPoliceOrgCode()
                         || dto.Order.OrgLevelOneCode == _sharingConfigurationManager.GetPoliceOrgCode())
                    {
                        //如果是12345的工单，并且办理部门是110，110办理完成之后将结果信息推送到12345后，12345反馈结果接收
                        await _policeService.FileEndPoliceAsync(dto.Order, cancellationToken);
                    }

                    //给110推送行政审批工单（自贡独有）
                    await InitPoliceAdministrativeApproval(dto.Order, cancellationToken);

                    if (_sharingConfigurationManager.GetZiGongConfig().SmartCitySystem.IsSendPush == true)
                    {
                        //自贡智慧城市系统
                        if (!string.IsNullOrEmpty(dto.Order.OrderTagCode) && dto.Order.OrderTagCode.IndexOf("zgdh") > -1)
                        {
                            //其他服务推送
                            await _sendTaskDataService.OtherSendTask("zgdh", dto.Order, cancellationToken);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            //泸州推送
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
            {
                try
                {
                    // 泸州110推送 来源12345的工单办结后推送基础信息给110
                    if (dto.Order.TransferPhone == "12345")
                        await _luZhou110Service.InitData(dto, cancellationToken);

                    // 泸州市政府门户网站 办结后推送办理结果给市门户
                    if (dto.Order.Source == ESource.LZCityPortalSite)
                    {
                        await _sendTaskDataService.AddHandleOpinionByCityPortal(dto, cancellationToken);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        /// <summary>
        /// 挂电话推送----电话记录--丰窝最新
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineCallAdd)]
        public async Task SubmitCaseRecordFwAsync(List<CallNativeDto> dto, CancellationToken cancellationToken)
        {
            if (!dto.Any())
                return;
            foreach (var item in dto)
            {
                await _provinceService.SubmitCaseRecordFwAsync(item, cancellationToken);
            }
        }

        /// <summary>
        /// 推送通话记录未关联工单数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.SharingOrderWithCallInfo)]
        public async Task AssociateCallRecords(PublishCallRecrodDto dto, CancellationToken cancellationToken)
        {
            if (dto.Order is null || dto.TrCallRecordDto is null || string.IsNullOrEmpty(dto.Order.ProvinceNo))
                return;

            await _provinceService.AssociateCallRecords(dto, cancellationToken);
        }

        /// <summary>
        /// 挂电话推送----电话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineCallBye)]
        public async Task SubmitCaseRecordAsync(PublishCallRecrodDto dto, CancellationToken cancellationToken)
        {
            await _provinceService.SubmitCaseRecordAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 关联工单了推送----电话记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineCallConnectWithOrder)]
        public async Task SubmitCaseRecordOrderAsync(PublishCallRecrodDto dto, CancellationToken cancellationToken)
        {
            await _provinceService.SubmitCaseRecordOrderAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 统计数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SubmitCaseTotalAsync(SubmitCaseTotalInfo dto, CancellationToken cancellationToken)
        {
            await _provinceService.SubmitCaseTotalAsync(dto, cancellationToken);
        }

        #endregion

        #region 协同-第三批次

        /// <summary>
        /// 上报补充诉求
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SupplyCaseInfoSendAsync(SupplyCaseInfoSendInfo dto, CancellationToken cancellationToken)
        {
            //调用上报补充诉求
            await _provinceService.SupplyCaseInfoSendAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 撤单
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderFlowRecalled)]
        public async Task RevokeOrderAsync(PublishSpecialDto dto, CancellationToken cancellationToken)
        {
            //市州业务撤单
            await _sendTaskDataService.RevokeOrderAsync(dto, cancellationToken);

            //省12345
            if (dto.Special.OrgId == _sharingConfigurationManager.GetProvinceOrgCode() ||
                dto.Special.OrgId == _sharingConfigurationManager.GetProvinceAssignmentOrgCode())
            {
                //调用省撤单
                await _provinceService.RevokeOrderAsync(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 服务工单催单
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderUrgeInform)]
        public async Task SendRemindCaseInfoAsync(PublishUrgeDto dto, CancellationToken cancellationToken)
        {
            //被催办部门为省上，才能调用接口
            if (dto.Urge.OrgId == _sharingConfigurationManager.GetProvinceOrgCode() ||
                dto.Urge.OrgId == _sharingConfigurationManager.GetProvinceAssignmentOrgCode())
            {
                //调用服务工单催单
                await _provinceService.SendRemindCaseInfoAsync(dto, cancellationToken);
            }
        }

        /// <summary>
        /// 接收发布数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderPublishOrder)]
        public async Task PublishOrderAsync(PublishPublishOrderDto dto, CancellationToken cancellationToken)
        {
            //修改工单基础数据
            var dataOrder = await _dsOrderRepository.GetAsync(p => p.OrderId == dto.Order.Id, cancellationToken);
            if (dataOrder != null)
            {
                dataOrder.IsPublish = dto.PublishState == true ? DataSharing.Share.Enums.EDsPublishState.Open : DataSharing.Share.Enums.EDsPublishState.NotPublic;
                dataOrder.PublishDate = dto.CreationTime;
                dataOrder.ArrangeTitle = dto.ArrangeTitle;
                dataOrder.ArrangeContent = dto.ArrangeContent;
                dataOrder.ArrangeOpinion = dto.ArrangeOpinion;
                await _dsOrderRepository.UpdateAsync(dataOrder, cancellationToken);
            }

            //调用接收发布数据
            await _provinceService.PublishOrderAsync(dto, cancellationToken);

        }

        /// <summary>
        /// 接收政民互动发布数据
        /// </summary>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderProvinceZmhd)]
        public async Task PublicOrderProvinceZmhd(PublicOrderProvinceZmhdDto dto, CancellationToken cancellationToken)
        {
            await _provinceService.PublicOrderProvinceZmhd(dto, cancellationToken);
        }

        /// <summary>
        /// 接收发布的时候生成的待回访部门数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderVisitedWeb)]
        public async Task PublishVisitAllAsync(PublishVisitAllDto dto, CancellationToken cancellationToken)
        {
            //调用接收发布的时候生成的待回访部门数据
            await _provinceService.PublishVisitAllAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 市州互转
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineOrderTranspondCity)]
        public async Task TranspondCityAsync(OrderDto dto, CancellationToken cancellationToken)
        {
            //泸州市州数据提交
            if (dto.Transpond == true)
            {
                //数据推送
                await _sendTaskDataService.TranspondCityAsync(dto, cancellationToken);
            }
        }
        #endregion

        #region 汇聚-第四批次

        #region 知识库
        /// <summary>
        /// 知识库上报
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineKnowledgeAdd)]
        public async Task GetKnowledgeInfoSendAsync(KnowledgeSendDto dto, CancellationToken cancellationToken)
        {
            //调用知识库上报
            await _provinceService.GetKnowledgeInfoSendAsync(dto, cancellationToken);

        }

        /// <summary>
        /// 知识库变更
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineKnowledgeUpdate)]
        public async Task GetKnowledgeInfoUpdateAsync(KnowledgeSendDto dto, CancellationToken cancellationToken)
        {
            //调用知识库变更
            await _provinceService.GetKnowledgeInfoUpdateAsync(dto, cancellationToken);
        }

        /// <summary>
        /// 知识库下架
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        [CapSubscribe(Hotline.Share.Mq.EventNames.HotlineKnowledgeRemove)]
        public async Task GetKnowledgeInfoAbandonAsync(KnowledgeSendDto dto, CancellationToken cancellationToken)
        {
            //调用知识库下架
            await _provinceService.GetKnowledgeInfoAbandonAsync(dto, cancellationToken);
        }
        #endregion

        /// <summary>
        /// 实时服务上报
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendRealTimeStatusAsync(SendRealTimeStatusInfo dto, CancellationToken cancellationToken)
        {
            //调用实时服务上报
            await _provinceService.SendRealTimeStatusAsync(dto, cancellationToken);
        }
        #endregion

        #region 派单是判断需要往第三方推送数据

        /// <summary>
        /// 派单是判断需要往第三方推送数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private async Task OrderDispatchAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            if (dto != null && dto.WorkflowTrace != null && dto.WorkflowTrace.NextHandlers != null && dto.WorkflowTrace.NextHandlers.Count > 0)
            {
                try
                {
                    foreach (var item in dto.WorkflowTrace.NextHandlers)
                    {
                        if (!string.IsNullOrEmpty(item.Key))
                        {
                            //是否向省上派单，不用区分市州，根据部门Code上传
                            if (item.Key == _sharingConfigurationManager.GetProvinceOrgCode() || item.Key == _sharingConfigurationManager.GetProvinceAssignmentOrgCode())
                            {
                                //先上传拓展信息
                                if (dto.Order.OrderExtension != null)
                                    await _provinceService.SubmitCaseExtendsAsync(dto.Order, cancellationToken);

                                await _provinceService.SendCaseInfoDataAsync(dto.Order, cancellationToken);
                            }


                            //需要判断是否需要往110推送
                            if (item.Key == _sharingConfigurationManager.GetPoliceOrgCode())
                                //写入110本地数据库
                                await _policeService.InitPoliceSendChainAlarmAsync(dto.Order, cancellationToken);

                            //其他服务推送
                            await _sendTaskDataService.OtherSendTask(item.Key, dto.Order, cancellationToken);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        #endregion

        #region 给110推送行政审批工单（自贡独有）

        /// <summary>
        /// 给110推送行政审批工单（自贡独有）
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task InitPoliceAdministrativeApproval(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            try
            {
                string arrTypeName = $@"'交通管理-车驾管业务-驾驶证业务-考试'
                                       ,'交通管理-车驾管业务-驾驶证业务-补、换证'
                                       ,'交通管理-车驾管业务-驾驶证业务-登记'
                                       ,'交通管理-车驾管业务-非机动车业务-驾驶证业务'
                                       ,'政务服务-行政效能-工作作风'
                                       ,'政务服务-行政效能-工作效率'
                                       ,'政务服务-行政效能-服务态度'
                                       ,'政务服务-行政效能-其他行政效能投诉'
                                       ,'政务服务-行政效能-服务质量'
                                       ,'政务服务-审批信息-审批信息'
                                       ,'城市管理-户籍管理-户口登记项目变更更正-变更更正民族'
                                       ,'城市管理-户籍管理-户口登记项目变更更正-更正籍贯'
                                       ,'城市管理-户籍管理-户口登记项目变更更正-变更更正姓名'
                                       ,'城市管理-户籍管理-户口登记项目变更更正-更正出生日期'
                                       ,'城市管理-户籍管理-户口登记项目变更更正-变更服务处所'
                                       ,'城市管理-户籍管理-户口登记项目变更更正-变更婚姻状况'
                                       ,'城市管理-户籍管理-户口登记-出生登记'
                                       ,'城市管理-户籍管理-户口登记-集体户口'
                                       ,'城市管理-户籍管理-户口登记-分户登记'
                                       ,'城市管理-户籍管理-户口登记-非婚生子女户口申报'
                                       ,'城市管理-户籍管理-居住证-首次申领'
                                       ,'城市管理-户籍管理-居住证-居住登记'
                                       ,'城市管理-户籍管理-身份证-身份证申领'
                                       ,'城市管理-户籍管理-身份证-身份证丢失补办'
                                       ,'城市管理-户籍管理-身份证-临时身份证申领'
                                       ,'城市管理-户籍管理-户口注销-服兵役户口注销'
                                       ,'城市管理-户籍管理-户口注销-死亡人口户口注销'
                                       ,'城市管理-户籍管理-出入境管理-往来港澳通行证办理'
                                       ,'城市管理-户籍管理-出入境管理-护照办理'
                                       ,'城市管理-户籍管理-出入境管理-往来港澳通行证'
                                       ,'城市管理-户籍管理-户口注销-出国或赴港、澳、台定居注销户口'";

                string typenameFull = orderDto.HotspotSpliceName;
                if (!string.IsNullOrEmpty(typenameFull))
                {
                    if (arrTypeName.IndexOf("'" + typenameFull + "'") > -1)
                    {
                        await _policeService.InitPoliceAdministrativeApproval(orderDto, cancellationToken);
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        #endregion
    }
}
