using DataSharing.FwDataExchange;
using DataSharing.Province;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.FwDataExchange;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.Province.XieTong.Receive;
using DataSharing.Share.Enums;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Dtos.File;
using Hotline.Share.Dtos.Order;
using MapsterMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using XF.Domain.Filters;
using XF.Domain.Repository;

namespace DataSharing.Host.Controllers
{
    /// <summary>
    /// 下行，省平台调用
    /// </summary>
    public class ProvinceController : BaseController
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly IMediator _mediator;
        private readonly ICapPublisher _capPublisher;
        private readonly IChannelConfigurationManager _channelConfigurationManager;
        private readonly IRepository<DsOrder> _dataOrderRepository;
        private readonly IRepository<DsReceiveProvinceData> _dsReceiveProvinceDataRepository;
        private readonly IRepository<DsGetCaseMaterialInfo> _getCaseMaterialInfoRepository;
        private readonly IRepository<DsGetCaseBackApply> _getCaseBackApplyRepository;
        private readonly IRepository<DsSendCaseInfo> _sendCaseInfoRepository;
        private readonly FwClient _fwClient;
        private readonly IRepository<SendFwErrorData> _sendFwErrorDataRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IRepository<SendHotlineErrorData> _sendHotlineErrorDataRepository;
        private readonly ILogger<ProvinceController> _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="mediator"></param>
        /// <param name="capPublisher"></param>
        /// <param name="channelConfigurationManager"></param>
        /// <param name="dataOrderRepository"></param>
        /// <param name="dsReceiveProvinceDataRepository"></param>
        /// <param name="getCaseMaterialInfoRepository"></param>
        /// <param name="getCaseBackApplyRepository"></param>
        /// <param name="sendCaseInfoRepository"></param>
        /// <param name="fwClient"></param>
        /// <param name="sendFwErrorDataRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="sendHotlineErrorDataRepository"></param>
        public ProvinceController(IMapper mapper,
             IMediator mediator,
             ICapPublisher capPublisher,
             IChannelConfigurationManager channelConfigurationManager,
             IRepository<DsOrder> dataOrderRepository,
             IRepository<DsReceiveProvinceData> dsReceiveProvinceDataRepository,
             IRepository<DsGetCaseMaterialInfo> getCaseMaterialInfoRepository,
             IRepository<DsGetCaseBackApply> getCaseBackApplyRepository,
             IRepository<DsSendCaseInfo> sendCaseInfoRepository,
             FwClient fwClient,
             IRepository<SendFwErrorData> sendFwErrorDataRepository,
             ISharingConfigurationManager sharingConfigurationManager,
             IRepository<SendHotlineErrorData> sendHotlineErrorDataRepository,
             ILogger<ProvinceController> logger)
        {
            _mapper = mapper;
            _mediator = mediator;
            _capPublisher = capPublisher;
            _channelConfigurationManager = channelConfigurationManager;
            _dataOrderRepository = dataOrderRepository;
            _dsReceiveProvinceDataRepository = dsReceiveProvinceDataRepository;
            _getCaseMaterialInfoRepository = getCaseMaterialInfoRepository;
            _getCaseBackApplyRepository = getCaseBackApplyRepository;
            _sendCaseInfoRepository = sendCaseInfoRepository;
            _fwClient = fwClient;
            _sendFwErrorDataRepository = sendFwErrorDataRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
            _sendHotlineErrorDataRepository = sendHotlineErrorDataRepository;
            _logger = logger;
        }
        #endregion

        /// <summary>
        /// 服务工单交办接口--已完成-----1
        /// </summary>
        /// <param name="receiveCaseInfo"></param>
        /// <returns></returns>
        [HttpPost("rest/receive_case_info")]
        public async Task<OpenResponse> ReceiveCaseInfo([FromBody] ReceiveCaseInfoRequest receiveCaseInfo)
        {
            // 验证
            if (receiveCaseInfo is null || receiveCaseInfo.paras is null)
            {
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));
            }
            //转换数据
            var dto = receiveCaseInfo.paras;
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "receive_case_info", System.Text.Json.JsonSerializer.Serialize(dto));

            //验证接收的数据是否正确
            string strResult = receiveCaseInfo.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //处理组装数据，推送数据
            var data = _mapper.Map<Hotline.Share.Dtos.Order.AddOrderDto>(dto);
            data.CaseProcessType = dto.CaseProcessType;
            data.IsProvince = true;
            data.IsPublic = dto.CaseIsPublic == "1";
            if (dto.TrowGuid == "【政民互动直派】")
            {
                data.SourceChannel = "省政民互动";
                data.SourceChannelCode = "SZMHD";
                data.IsProvince = false;
            }
            else
            {
                if (dto.CaseSource.Trim().ToLower() == "zmhd".ToLower() || dto.CaseSource.Trim().ToLower() == "tftb".ToLower())
                {
                    data.SourceChannel = "省政民互动";
                    data.SourceChannelCode = "SZMHD";
                }
                else
                {
                    data.SourceChannel = "省12345平台";
                    data.SourceChannelCode = "S12345";
                }
            }

            //if (dto.CaseSource.ToLower() == "zmhd".ToLower())
            //{
            //    data.SourceChannel = "省政民互动";
            //    data.SourceChannelCode = "SZMHD";
            //    if (dto.TrowGuid == "【政民互动直派】")
            //        data.IsProvince = false;
            //}
            //else
            //{
            //    data.SourceChannel = "省12345平台";
            //    data.SourceChannelCode = "S12345";
            //}

            data.Source = Hotline.Share.Enums.Order.ESource.ProvinceStraight;

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

            //处理证件类型
            switch (dto.CertifiCateType)
            {
                case "10":
                    data.LicenceTypeCode = "10";
                    break;
                case "20":
                    data.LicenceTypeCode = "40";
                    break;
                case "30":
                    data.LicenceTypeCode = "55";
                    break;
                case "40":
                    data.LicenceTypeCode = "57";
                    break;
            }

            data.AcceptTypeCode = dto.CaseType;

            //处理紧急程度
            data.IsUrgent = dto.CaseIsUrgent switch
            {
                "10" => true,
                "20" => true,
                "30" => false,
                _ => false,
            };

            //经纬度处理
            var lngLat = dto.CaseLngLat.Split(',');
            if (lngLat != null && lngLat.Length == 2)
            {
                data.Longitude = Convert.ToDouble(lngLat[0]);
                data.Latitude = Convert.ToDouble(lngLat[1]);
            }

            data.City = _sharingConfigurationManager.GetCityName();

            //处理热点
            if (!string.IsNullOrEmpty(dto.CaseAccord))
            {
                data.HotspotExternal = dto.CaseAccord;
                string hotspotExternal = "";
                var length = dto.CaseAccord.Length - 2;
                if (dto.CaseAccord.Length - 2 > 0)
                {
                    for (int i = length; i > 0; i = i - 2)
                    {
                        hotspotExternal += dto.CaseAccord.Substring(0, i) + ",";
                    }
                }
                if (!string.IsNullOrEmpty(hotspotExternal))
                {
                    data.HotspotExternal = hotspotExternal.Substring(0, hotspotExternal.Length - 1);
                }
            }

            data.IdentityType = Hotline.Share.Enums.Order.EIdentityType.Citizen;
            data.Transpond = false;
            data.IsEnforcementOrder = false;

            if (!string.IsNullOrEmpty(id))
            {
                data.Files = await GetFileData(dto.CliengGuid, dto.CaseSerial, "受理上传");

                bool isSuccess = true;
                string error = "";
                try
                {
                    var result = await _fwClient.RequestNoTokenAsync<HotlineClientResponse>("api/v1/Order/add-anonymous", "Post", System.Text.Json.JsonSerializer.Serialize(data));
                    if (result == null || result.code != 0)
                    {
                        isSuccess = false;
                        error = result?.message;
                    }

                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    error = ex.Message;
                }

                //推送失败添加
                if (!isSuccess)
                {
                    SendHotlineErrorData errorData = new SendHotlineErrorData()
                    {
                        DataId = id,
                        PlatformSource = EPlatformSource.Province,
                        ReceiveServiceInterface = "rest/receive_case_info",
                        RawData = System.Text.Json.JsonSerializer.Serialize(dto),
                        RequestData = System.Text.Json.JsonSerializer.Serialize(data),
                        Path = "api/v1/Order/add-anonymous",
                        SendTimes = 0,
                        HttpMethod = "Post",
                        ErrorMessage = error
                    };
                    await _sendHotlineErrorDataRepository.AddAsync(errorData, HttpContext.RequestAborted);
                }

                var recData = await _dsReceiveProvinceDataRepository.GetAsync(p => p.Id == id, HttpContext.RequestAborted);
                if (recData != null)
                {
                    recData.CaseProcessType = dto.CaseProcessType;
                    await _dsReceiveProvinceDataRepository.UpdateAsync(recData, HttpContext.RequestAborted);
                }

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单退回反馈接口--已完成-----1
        /// </summary>
        /// <param name="receiveBackResult">退回反馈</param>
        /// <returns></returns>
        [HttpPost("get_case_back_result")]
        public async Task<OpenResponse> GetCaseBackResult([FromBody] GetCaseBackResultRequest receiveBackResult)
        {
            // 验证
            if (receiveBackResult is null || receiveBackResult.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveBackResult.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "get_case_back_result", System.Text.Json.JsonSerializer.Serialize(dto));

            //验证接收的数据是否正确
            string strResult = receiveBackResult.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveBackResult.paras.CaseSerial, "api/receive/get_case_back_result", System.Text.Json.JsonSerializer.Serialize(receiveBackResult), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            var data = await _getCaseBackApplyRepository.GetAsync(p => p.CaseSerial == dto.CaseSerial && p.IsFeedBack == false, HttpContext.RequestAborted);
            if (data == null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));

            if (!string.IsNullOrEmpty(id))
            {
                var dataBack = new OrderSendBackResultDto()
                {
                    Id = data.OrderSendBackId,
                    Reason = dto.BackReason,
                    Result = dto.Result == "1" ? 1 : 0,
                    Source = "province",
                    AuditName = dto.DealName,
                    AuditOrgName = dto.DealDept,
                    AuditTime = Convert.ToDateTime(dto.ApplyTime),
                    Files = await GetFileData(dto.CliengGuid, dto.CaseSerial, "工单退回审核")
                };
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReturnFeedback, dataBack, cancellationToken: HttpContext.RequestAborted);

                data.IsFeedBack = true;
                await _getCaseBackApplyRepository.UpdateAsync(data, HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 督办工单派发接口--已完成-----1
        /// </summary>
        /// <param name="receiveSendSuperviseInfo">督办工单对象</param>
        /// <returns></returns>
        [HttpPost("send_supervise_info")]
        public async Task<OpenResponse> SendSuperviseInfo([FromBody] SendSuperviseInfoRequest receiveSendSuperviseInfo)
        {
            // 验证
            if (receiveSendSuperviseInfo is null || receiveSendSuperviseInfo.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveSendSuperviseInfo.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "send_supervise_info", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveSendSuperviseInfo.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveSendSuperviseInfo.paras.CaseSerial, "api/receive/send_supervise_info", System.Text.Json.JsonSerializer.Serialize(receiveSendSuperviseInfo), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                ProvinceSendOrderSuperviseDto orderSuperviseDto = new ProvinceSendOrderSuperviseDto()
                {
                    ProvinceOrderSuperviseDto = _mapper.Map<ProvinceOrderSuperviseDto>(dto),
                    Files = await GetFileData(dto.CliengGuid, dto.CaseSerial, "督办工单派发")
                };

                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderSupervise, orderSuperviseDto, cancellationToken: HttpContext.RequestAborted);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));

            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单催单接口--已完成-----1
        /// </summary>
        /// <param name="receiveRemindCaseInfo">催单对象</param>
        /// <returns></returns>
        [HttpPost("remind_case_info")]
        public async Task<OpenResponse> RemindCaseInfo([FromBody] RemindCaseInfoRequest receiveRemindCaseInfo)
        {
            // 验证
            if (receiveRemindCaseInfo is null || receiveRemindCaseInfo.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveRemindCaseInfo.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "remind_case_info", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveRemindCaseInfo.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveRemindCaseInfo.paras.CaseSerial, "api/receive/remind_case_info", System.Text.Json.JsonSerializer.Serialize(receiveRemindCaseInfo), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                var data = _mapper.Map<ProvinceOrderUrgeDto>(dto);
                data.DsBisId = dto.CliengGuid;
                data.Files = await GetFileData(dto.CliengGuid, dto.CaseSerial, "工单催单");

                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderRemind, data, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单甄别结果接口--已完成-----1
        /// </summary>
        /// <param name="receiveScreenCaseResultReceive">服务工单甄别结果对象</param>
        /// <returns></returns>
        [HttpPost("screen_case_result_receive")]
        public async Task<OpenResponse> ScreenCaseResultReceive([FromBody] ScreenCaseResultReceiveRequest receiveScreenCaseResultReceive)
        {
            // 验证
            if (receiveScreenCaseResultReceive is null || receiveScreenCaseResultReceive.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveScreenCaseResultReceive.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "screen_case_result_receive", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveScreenCaseResultReceive.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveScreenCaseResultReceive.paras.CaseSerial, "api/receive/screen_case_result_receive", System.Text.Json.JsonSerializer.Serialize(receiveScreenCaseResultReceive), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                ProvinceSendScreenResultDto screenResultDto = new ProvinceSendScreenResultDto()
                {
                    ProvinceScreenResult = _mapper.Map<ProvinceScreenResult>(dto),
                    Source = "province",
                    Files = await GetFileData(dto.CliengGuid, dto.CaseSerial, "工单甄别结果")
                };

                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderScreen, screenResultDto, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单延时审核结果接口---已完成-----1
        /// </summary>
        /// <param name="receiveDelayCaseResult">延时审核结果对象</param>
        /// <returns></returns>
        [HttpPost("delay_case_result_receive")]
        public async Task<OpenResponse> DelayCaseResultReceive([FromBody] DelayCaseResultRequest receiveDelayCaseResult)
        {
            // 验证
            if (receiveDelayCaseResult is null || receiveDelayCaseResult.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveDelayCaseResult.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "delay_case_result_receive", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveDelayCaseResult.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveDelayCaseResult.paras.CaseSerial, "api/receive/delay_case_result_receive", System.Text.Json.JsonSerializer.Serialize(receiveDelayCaseResult), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                var listFiles = await GetFileData(dto.CliengGuid, dto.CaseSerial, "工单延期审核结果");
                ProvinceSendDelayResultDto delayResultDto = new()
                {
                    IsPass = dto.AuditResult == "1",
                    Opinion = dto.AuditOpinion,
                    No = dto.CaseSerial,
                    Files = listFiles,
                    Source = "province",
                    AuditName = dto.AuditPerson,
                    AuditOrgName = dto.AuditOuname,
                    AuditTime = Convert.ToDateTime(dto.AuditTime),
                };
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderDelayResult, delayResultDto, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单交办补充诉求接口---已完成-----1
        /// </summary>
        /// <param name="receiveSupplyCaseInfo">交办补充诉求对象</param>
        /// <returns></returns>
        [HttpPost("supply_case_info_receive")]
        public async Task<OpenResponse> SupplyCaseInfoReceive([FromBody] SupplyCaseInfoRequest receiveSupplyCaseInfo)
        {
            // 验证
            if (receiveSupplyCaseInfo is null || receiveSupplyCaseInfo.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveSupplyCaseInfo.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "supply_case_info_receive", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveSupplyCaseInfo.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveSupplyCaseInfo.paras.CaseSerial, "api/receive/supply_case_info_receive", System.Text.Json.JsonSerializer.Serialize(receiveSupplyCaseInfo), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                var listFiles = await GetFileData(dto.CliengGuid, dto.CaseSerial, "工单补充");
                AddOrderComplementDto complementDto = new()
                {
                    CaseSerial = dto.CaseSerial,
                    Opinion = dto.SupplyContent,
                    DsBisId = dto.CliengGuid,
                    SupplyName = dto.SupplyName,
                    SupplyTime = dto.SupplyTime,
                    Files = listFiles
                };
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderSupplements, complementDto, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));

            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单撤单接口---已完成-----1
        /// </summary>
        /// <param name="receiveRevokeCaseInfo">撤单对象</param>
        /// <returns></returns>
        [HttpPost("revoke_case_info")]
        public async Task<OpenResponse> RevokeCaseInfo([FromBody] RevokeCaseInfoRequest receiveRevokeCaseInfo)
        {
            // 验证
            if (receiveRevokeCaseInfo is null || receiveRevokeCaseInfo.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveRevokeCaseInfo.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "revoke_case_info", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveRevokeCaseInfo.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveRevokeCaseInfo.paras.CaseSerial, "api/receive/revoke_case_info", System.Text.Json.JsonSerializer.Serialize(receiveRevokeCaseInfo), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                CancelOrderDto cancelOrder = new()
                {
                    RevokeTime = dto.RevokeTime,
                    RevokeType = dto.RevokeType,
                    RevokeName = dto.RevokeName,
                    Opinion = dto.RevokeReasion,
                    ProvinceNo = dto.CaseSerial,
                    CliengGuid = dto.CliengGuid,
                    Source = "province"
                };
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderRevoke, cancelOrder, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单预警接口
        /// </summary>
        /// <param name="receiveSendWarnInfo">预警对象</param>
        /// <returns></returns>
        [HttpPost("send_warn_info")]
        public async Task<OpenResponse> SendWarnInfo([FromBody] SendWarnInfoRequest receiveSendWarnInfo)
        {
            // 验证
            if (receiveSendWarnInfo is null || receiveSendWarnInfo.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveSendWarnInfo.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, null, "send_warn_info", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveSendWarnInfo.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveSendWarnInfo.paras.CaseSerial, "api/receive/send_warn_info", System.Text.Json.JsonSerializer.Serialize(receiveSendWarnInfo), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderWarning, _mapper.Map<WarningDto>(dto), cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 交办工单满意度接收接口---已完成-----1
        /// </summary>
        /// <param name="receiveSendCaseEvlResult">交办工单满意度对象</param>
        /// <returns></returns>
        [HttpPost("send_case_evl_result")]
        public async Task<OpenResponse> SendCaseEvlResult([FromBody] SendCaseEvlResultRequest receiveSendCaseEvlResult)
        {
            // 验证
            if (receiveSendCaseEvlResult is null || receiveSendCaseEvlResult.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveSendCaseEvlResult.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, null, "send_case_evl_result", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveSendCaseEvlResult.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveSendCaseEvlResult.paras.CaseSerial, "api/receive/send_case_evl_result", System.Text.Json.JsonSerializer.Serialize(receiveSendCaseEvlResult), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {

                ProvinceOrderVisitDto orderVisitDto = new()
                {
                    ProvinceNo = dto.CaseSerial,
                    VisitTime = Convert.ToDateTime(dto.ReplyTime),
                    VisitContent = dto.ReplyContent,
                    OrgProcessingResults = dto.ResultEvl,
                    VisitType = Hotline.Share.Enums.Order.EVisitType.ArtificialVisit
                };
                switch (orderVisitDto.OrgProcessingResults)
                {
                    case "5":
                    case "4":
                    case "2":
                        break;
                    case "3":
                        orderVisitDto.OrgProcessingResults = "4";
                        break;
                    case "1":
                        orderVisitDto.OrgProcessingResults = "2";
                        break;
                    default:
                        orderVisitDto.OrgProcessingResults = "4";
                        break;
                }
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderEvlResult, orderVisitDto, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 上报工单处理结果/退回接口---已完成-----1
        /// </summary>
        /// <param name="receiveGetCaseReultSend">上报工单处理结果/退回对象</param>
        /// <returns></returns>
        [HttpPost("get_case_result_send")]
        public async Task<OpenResponse> GetCaseReultSend([FromBody] GetCaseReultSendRequest receiveGetCaseReultSend)
        {
            // 验证
            if (receiveGetCaseReultSend is null || receiveGetCaseReultSend.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveGetCaseReultSend.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "get_case_result_send", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveGetCaseReultSend.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveGetCaseReultSend.paras.CaseSerial, "api/send/get_case_result_send", System.Text.Json.JsonSerializer.Serialize(receiveGetCaseReultSend), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                //查询此工单
                var tempData = await _sendCaseInfoRepository.GetAsync(p => p.CaseSerial == dto.CaseSerial, HttpContext.RequestAborted);
                if (tempData != null)
                {
                    //将工单的办理状态改为办理完成，终止拉取办理信息
                    tempData.IsEnd = true;
                    tempData.State = "1";
                    await _sendCaseInfoRepository.UpdateAsync(tempData, HttpContext.RequestAborted);

                    var sendInfo = await _sendCaseInfoRepository.Queryable().Where(p => p.CaseSerial == dto.CaseSerial && p.IsEnd == false).ToListAsync();
                    if (sendInfo is not null && sendInfo.Any())
                    {
                        foreach (var item in sendInfo)
                        {
                            item.IsEnd = true;
                            item.State = "1";
                            await _sendCaseInfoRepository.UpdateAsync(item, HttpContext.RequestAborted);
                        }
                    }

                    var listFiles = await GetFileData(dto.CliengGuid, dto.CaseSerial, "办理上传");

                    OrderResultDto orderResult = new()
                    {
                        OrderId = tempData.OrderID,
                        FinishType = dto.FinishType,
                        Opinion = dto.FdBack,
                        Files = listFiles,
                        Source = "province"
                    };

                    //向业务系统推送消息
                    await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResult, cancellationToken: HttpContext.RequestAborted);
                }

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 上报工单评价接口
        /// </summary>
        /// <param name="receiveGetVisitInfoSend">上报工单评价对象</param>
        /// <returns></returns>
        [HttpPost("get_visit_info_send")]
        public async Task<OpenResponse> GetVisitInfoSend([FromBody] GetVisitInfoSendRequest receiveGetVisitInfoSend)
        {
            // 验证
            if (receiveGetVisitInfoSend is null || receiveGetVisitInfoSend.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            //转换数据
            var dto = receiveGetVisitInfoSend.paras;
            //添加数据
            var id = await InitReceiveProvinceData(dto.CaseSerial, dto.CliengGuid, "get_visit_info_send", System.Text.Json.JsonSerializer.Serialize(dto));

            string strResult = receiveGetVisitInfoSend.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveGetVisitInfoSend.paras.CaseSerial, "api/send/get_visit_info_send", System.Text.Json.JsonSerializer.Serialize(receiveGetVisitInfoSend), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            if (!string.IsNullOrEmpty(id))
            {
                ProvinceOrderVisitDto orderVisitDto = new()
                {
                    ProvinceNo = dto.CaseSerial,
                    VisitTime = Convert.ToDateTime(dto.VisitTime),
                    VisitContent = dto.VisitRemark,
                    OrgProcessingResults = dto.SubjectResultSatify,
                    VisitType = dto.VisitType switch
                    {
                        "DH" => Hotline.Share.Enums.Order.EVisitType.ArtificialVisit,
                        "DX" => Hotline.Share.Enums.Order.EVisitType.SmsVisit,
                        "WZ" => Hotline.Share.Enums.Order.EVisitType.WebVisit,
                        "WX" => Hotline.Share.Enums.Order.EVisitType.WeChatVisit,
                        "AP" => Hotline.Share.Enums.Order.EVisitType.AppVisit,
                        _ => Hotline.Share.Enums.Order.EVisitType.OtherVisit,
                    }
                };
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderEvlResult, orderVisitDto, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单拓展信息交办---已完成-----1
        /// </summary>
        /// <param name="receiveCaseExtendsRequest">服务工单拓展信息交办</param>
        /// <returns></returns>
        [HttpPost("rest/receive_case_extends")]
        public async Task<OpenResponse> ReceiveCaseExtends([FromBody] ReceiveCaseExtendsRequest receiveCaseExtendsRequest)
        {
            // 验证
            if (receiveCaseExtendsRequest is null || receiveCaseExtendsRequest.paras is null)
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));

            var data = receiveCaseExtendsRequest.paras;
            //添加数据
            var id = await InitReceiveProvinceData(data.CaseSerial, null, "receive_case_extends", System.Text.Json.JsonSerializer.Serialize(data));

            string strResult = receiveCaseExtendsRequest.paras.Validate();
            if (!string.IsNullOrEmpty(strResult))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));

            //推送老系统数据
            var isCheck = await SendDataFw(receiveCaseExtendsRequest.paras.CaseSerial, "api/receive/receive_case_extends", System.Text.Json.JsonSerializer.Serialize(receiveCaseExtendsRequest), "Post");
            if (isCheck)
            {
                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
            }

            OrderExtensionDto orderExtension = new();
            //扩展信息写入
            switch (data.FormType.ToLower())
            {
                case "yl"://医疗表单
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormMedical);
                    orderExtension.OrderType = "医疗服务中心受理单";
                    break;
                case "zwfw"://四川政务服务网技术工单
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormNetWorktec);
                    orderExtension.OrderType = "四川政务服务网技术中心受理单";
                    break;
                case "th"://电视购物及商铺购买退换货工单
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormReturnexChange);
                    orderExtension.OrderType = "电视购物及商铺购买退换货中心受理单";
                    break;
                case "gsgl"://高速公路工单
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormExpressWay);
                    orderExtension.OrderType = "高速公路投诉中心受理单";
                    break;
                case "xjgg"://电视台虚假广告工单
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormShamPub);
                    orderExtension.OrderType = "电视台虚假广告中心受理单";
                    break;
                case "swfwsq"://12366热线诉求交办
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormTaxationComplaint);
                    orderExtension.OrderType = "四川省12366热线诉求交办单";
                    break;
                case "swfwzx"://12366热线咨询交办
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormTaxationConsulting);
                    orderExtension.OrderType = "四川省12366热线咨询交办单";
                    break;
                case "jtfwjd"://12328服务监督
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormTraffic);
                    orderExtension.OrderType = "12328服务监督中心受理单";
                    break;
                case "yzxf"://邮政业消费者申诉
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormPost);
                    orderExtension.OrderType = "邮政业消费者申诉受理单";
                    break;
                case "hbjb"://环保举报业务
                    //转换数据
                    orderExtension = _mapper.Map<OrderExtensionDto>(data.FormEnvironMent);
                    orderExtension.OrderType = "环保举报业务受理单";
                    break;
                case "scjgj"://12315个性化表单
                    break;
                default:
                    break;
            }

            orderExtension.ProvinceNo = data.CaseSerial;
            orderExtension.OrderTypeCode = data.FormType.ToLower();

            if (!string.IsNullOrEmpty(id))
            {
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderExtends, orderExtension, cancellationToken: HttpContext.RequestAborted);

                //修改接收数据状态
                await UpdateReceiveData(id);

                return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));

            }
            else
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("接口调用失败！"));
        }

        /// <summary>
        /// 服务工单材料接口
        /// </summary>
        /// <param name="params">工单材料信息</param>
        /// <param name="files">材料文件</param>
        /// <returns></returns>
        [HttpPost("get_case_material_info")]
        public async Task<OpenResponse> GetCaseMaterialInfo(/* [FromForm] GetCaseMaterialInfoRequest vmCaseMaterialInfo, [FromForm] List<IFormFile> files*/)
        {
            var paramsData = Request.Form["params"];
            _logger.LogInformation($"收到服务工单材料接口参数：{paramsData}");

            _logger.LogInformation($"收到服务工单材料接口参数：{System.Text.Json.JsonSerializer.Serialize(Request.Form.Files)}");

            if (string.IsNullOrEmpty(paramsData))
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("params参数为必须"));

            IFormFileCollection files = Request.Form.Files;
            // 上传文件为必须
            if (files is null || !files.Any())
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("上传文件为必须"));

            //  @params = "{ \"token\": \"\", \"paras\":{ \"CaseSerial\":\"RGDH99511500240304000100\", \"MaterialType\":\"10\", \"CliengGuid\":\"91541fea-e1a5-4798-bc43-b25cc77ec6b7\", \"AreaCode\":\"511500\"} }";
            //// 解析附件信息
            var vmCaseMaterialInfo = System.Text.Json.JsonSerializer.Deserialize<GetCaseMaterialInfoRequest>(paramsData);
            if (vmCaseMaterialInfo is null || vmCaseMaterialInfo.paras is null)
            {
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed("数据解析失败"));
            }
            GetCaseMaterialInfoModel tmpCaseMaterialInfo = vmCaseMaterialInfo.paras;

            // 验证
            string strResult = tmpCaseMaterialInfo.Validate();
            if (false == string.IsNullOrEmpty(strResult))
            {
                return OpenResponse.Ok(GetDataBaseReponse<string>.Failed(strResult));
            }
            List<IFormFile> fileList = [.. files];
            //是否推送旧系统
            //受理附件不推送旧系统
            if (vmCaseMaterialInfo.paras.MaterialType != "10")
            {
                var isCheck = await SendFileDataFw(vmCaseMaterialInfo.paras.CaseSerial, paramsData, fileList);
                if (isCheck)
                {
                    return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
                }
            }

            List<DsGetCaseMaterialInfo> listData = new();
            // 文件列表
            foreach (var file in files)
            {
                //这里需要上文件服务器上传
                var businessFileDto = await SendFileData(file);

                string strFileName = file.FileName;
                string strSuffix = strFileName.LastIndexOf(".") > 0 ? strFileName.Substring(strFileName.LastIndexOf(".") + 1) : "";
                string strSubFileName = strFileName.LastIndexOf(".") > 0 ? strFileName.Substring(0, strFileName.LastIndexOf(".")) : strFileName;
                // 新增文件到列表
                var materialInfo = new DsGetCaseMaterialInfo()
                {
                    CaseSerial = tmpCaseMaterialInfo.CaseSerial,
                    MaterialType = tmpCaseMaterialInfo.MaterialType,
                    CliengGuid = tmpCaseMaterialInfo.CliengGuid,
                    AreaCode = tmpCaseMaterialInfo.AreaCode,
                    FileName = strSubFileName,
                    Type = strSuffix.Trim('.'),
                    Additions = businessFileDto.id,
                    Path = businessFileDto.path,
                    Direction = "2",
                    SyncState = "1"
                };
                listData.Add(materialInfo);
                await _getCaseMaterialInfoRepository.AddAsync(materialInfo, HttpContext.RequestAborted);

            }

            if (listData != null && listData.Count > 0)
            {
                //处理附件数据
                var receiveData = await _dsReceiveProvinceDataRepository.GetAsync(p => p.CliengGuid == tmpCaseMaterialInfo.CliengGuid && p.CaseSerial == tmpCaseMaterialInfo.CaseSerial, HttpContext.RequestAborted);
                if (receiveData != null)
                {
                    List<FileDto> listFiles = new();

                    ReceiveFilesFromDsDto receiveFilesFromDsDto = new ReceiveFilesFromDsDto()
                    {
                        DsBisId = tmpCaseMaterialInfo.CliengGuid,
                        ProvinceNo = tmpCaseMaterialInfo.CaseSerial
                    };

                    //根据接口处理数据
                    switch (receiveData.ServiceInterface)
                    {
                        case "receive_case_info":
                            listFiles = await InitFileData(listData, "工单受理");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.AcceptOrder;

                            break;
                        case "get_case_back_result":
                            listFiles = await InitFileData(listData, "工单退回审核");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.OrderPreviousResult;

                            break;
                        case "send_supervise_info":
                            listFiles = await InitFileData(listData, "督办申请");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.SendOrderSupervise;
                            receiveFilesFromDsDto.SuperviseId = tmpCaseMaterialInfo.CaseSerial;

                            break;
                        case "remind_case_info":
                            listFiles = await InitFileData(listData, "催办申请");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.SendOrderUrge;

                            break;
                        case "screen_case_result_receive":
                            listFiles = await InitFileData(listData, "甄别上传");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.OrderScreenResult;
                            break;
                        case "delay_case_result_receive":
                            listFiles = await InitFileData(listData, "延期上传");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.OrderDelayResult;

                            break;
                        case "supply_case_info_receive":
                            listFiles = await InitFileData(listData, "补充上传");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.SendOrderComplement;

                            break;
                        case "revoke_case_info":
                            // listFiles = await InitFileData(listData, "工单撤单");//暂无附件
                            break;
                        case "send_warn_info":
                            // listFiles = await InitFileData(listData, "工单预警");

                            break;
                        case "send_case_evl_result":
                            // listFiles = await InitFileData(listData, "工单满意度");

                            break;
                        case "get_case_result_send":
                            listFiles = await InitFileData(listData, "办理上传");
                            receiveFilesFromDsDto.DsBisType = EDsBisType.OrderHandleResult;

                            break;
                        case "get_visit_info_send":
                            // listFiles = await InitFileData(listData, "上报工单评价");
                            break;
                        default:
                            break;
                    }
                    receiveFilesFromDsDto.Files = listFiles;
                    //推送数据
                    if (receiveFilesFromDsDto.Files != null && receiveFilesFromDsDto.Files.Count > 0)
                        await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingFileInfo, receiveFilesFromDsDto, cancellationToken: HttpContext.RequestAborted);
                }
            }
            return OpenResponse.Ok(GetDataBaseReponse<string>.Success("您已成功提交数据！"));
        }

        #region 私有方法

        /// <summary>
        /// 修改工单接收数据状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task UpdateReceiveData(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var recData = await _dsReceiveProvinceDataRepository.GetAsync(p => p.Id == id, HttpContext.RequestAborted);
                if (recData != null)
                {
                    recData.CaseProcessType = "0";
                    await _dsReceiveProvinceDataRepository.UpdateAsync(recData, HttpContext.RequestAborted);
                }
            }
        }

        /// <summary>
        /// 组装附件参数
        /// </summary>
        /// <param name="listData"></param>
        /// <param name="Classify"></param>
        /// <returns></returns>
        private async Task<List<FileDto>> InitFileData(List<DsGetCaseMaterialInfo> listData, string Classify)
        {
            List<FileDto> fileDtos = new();
            foreach (var item in listData)
            {
                string strSubFileName = item.FileName.LastIndexOf(".") > 0 ? item.FileName.Substring(0, item.FileName.LastIndexOf(".")) : item.FileName;
                fileDtos.Add(new FileDto()
                {
                    FileName = item.FileName + "." + item.Type,
                    Name = strSubFileName,
                    Type = item.Type,
                    Classify = Classify,
                    Additions = item.Additions,
                    Path = item.Path,
                    AllPath = item.Path
                });
            }
            return fileDtos;
        }

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

            List<FileDto> fileDtos = new();
            if (list == null || list.Count == 0)
                return fileDtos;
            foreach (var item in list)
            {
                string strSubFileName = item.FileName.LastIndexOf(".") > 0 ? item.FileName.Substring(0, item.FileName.LastIndexOf(".")) : item.FileName;
                fileDtos.Add(new FileDto()
                {
                    FileName = item.FileName + "." + item.Type,
                    Name = strSubFileName,
                    Type = item.Type,
                    Classify = Classify,
                    Additions = item.Additions,
                    Path = item.Path,
                    AllPath = item.Path
                });
            }
            return fileDtos;
        }

        /// <summary>
        /// 将数据写入本地
        /// </summary>
        /// <param name="CaseSerial">工单编号</param>
        /// <param name="CliengGuid">材料标识</param>
        /// <param name="ServiceInterface">接口名称</param>
        /// <param name="ReceiveData">数据</param>
        /// <returns></returns>
        private async Task<string> InitReceiveProvinceData(string CaseSerial, string CliengGuid, string ServiceInterface, string ReceiveData)
        {
            DsReceiveProvinceData dsReceive = new()
            {
                CaseSerial = CaseSerial,
                CliengGuid = CliengGuid,
                ServiceInterface = ServiceInterface,
                ReceiveData = ReceiveData
            };
            return await _dsReceiveProvinceDataRepository.AddAsync(dsReceive, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 将文件流上传到附件服务器
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task<BusinessFileDto> SendFileData(IFormFile file)
        {
            var businessFile = _channelConfigurationManager.GetConfigurationBusinessFile();
            // 文件名称
            string fileName = file.FileName;

            // 文件内容字节数据
            using var memoryStream = new MemoryStream();
            await file.CopyToAsync(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            byte[] fileContentBytes = memoryStream.ToArray();

            // 构造字典文件数据
            // 接口参数名称为files
            CFormUpload.FileParameter fileParameter = new CFormUpload.FileParameter("fileData", fileContentBytes, fileName, "multipart/form-data");

            Dictionary<string, object> dicParam = new()
            {
                { fileName, fileParameter }
            };
            string url = string.Format("{0}{1}?source={2}", businessFile.BaseUrl, businessFile.UploadUrlAddress, businessFile.Source);
            var result = CFormUpload.MultipartFormDataPost(url, null, dicParam, "");
            if (!string.IsNullOrEmpty(result))
            {
                var resultData = Newtonsoft.Json.JsonConvert.DeserializeObject<BusinessFileResponse>(result);
                if (resultData != null && resultData.code == 0)
                {
                    return resultData.result;
                }
            }
            return new BusinessFileDto();

        }

        /// <summary>
        /// 下行数据推送到旧系统中
        /// </summary>
        /// <param name="CaseSerial">省工单编号</param>
        /// <param name="api">接口名称</param>
        /// <param name="jsonData">请求参数</param>
        /// <param name="httpMethod">请求方式</param>
        /// <returns></returns>
        private async Task<bool> SendDataFw(string CaseSerial, string api, string jsonData, string httpMethod = "Post")
        {
            ConfigurationSendDataOld configSendDataOld = new();
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.YiBin))
                configSendDataOld = _sharingConfigurationManager.GetYiBinConfig().SendDataOld;
            else if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configSendDataOld = _sharingConfigurationManager.GetZiGongConfig().SendDataOld;
            else if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                configSendDataOld = _sharingConfigurationManager.GetLuZhouConfig().SendDataOld;

            //先验证是否开启推送
            if (configSendDataOld == null || !configSendDataOld.IsSend)
                return false;

            //查询是否是本地工单，如果是本地工单不需要推送，如果是旧系统数据则推送
            bool isResult = false;
            string error = "";
            var isCheck = await _dsReceiveProvinceDataRepository.AnyAsync(p => p.CaseSerial == CaseSerial && p.ServiceInterface == "receive_case_info", HttpContext.RequestAborted);
            if (isCheck == false)
                isCheck = await _sendCaseInfoRepository.AnyAsync(p => p.CaseSerial == CaseSerial, HttpContext.RequestAborted);
            if (isCheck == false)
            {
                var url = configSendDataOld.AddressUrl + api;
                try
                {
                    var response = await _fwClient.RequestAsync<FwResponse>(url, httpMethod, jsonData, HttpContext.RequestAborted);
                    if (response != null && response.code == 1)
                    {
                        isResult = true;
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    error = ex.Message;
                }
                if (!isResult)
                {
                    //写入推送失败表
                    SendFwErrorData sendFwError = new()
                    {
                        HttpMethod = httpMethod,
                        ServiceInterface = url,
                        SendData = jsonData
                    };
                    var id = await _sendFwErrorDataRepository.AddAsync(sendFwError, HttpContext.RequestAborted);

                    SendHotlineErrorData errorData = new SendHotlineErrorData()
                    {
                        DataId = id,
                        PlatformSource = EPlatformSource.Province,
                        ReceiveServiceInterface = "SendOldHotlineData",
                        RawData = jsonData,
                        RequestData = jsonData,
                        Path = api,
                        SendTimes = 0,
                        HttpMethod = "Post",
                        ErrorMessage = error
                    };
                    await _sendHotlineErrorDataRepository.AddAsync(errorData, HttpContext.RequestAborted);
                }
            }
            return false;
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="CaseSerial"></param>
        /// <param name="strParams"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        private async Task<bool> SendFileDataFw(string CaseSerial, string strParams, List<IFormFile> files)
        {
            ConfigurationSendDataOld configSendDataOld = new();
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.YiBin))
                configSendDataOld = _sharingConfigurationManager.GetYiBinConfig().SendDataOld;
            else if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configSendDataOld = _sharingConfigurationManager.GetZiGongConfig().SendDataOld;
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                configSendDataOld = _sharingConfigurationManager.GetLuZhouConfig().SendDataOld;

            //先验证是否开启推送
            if (configSendDataOld == null || !configSendDataOld.IsSend)
                return false;

            var isCheck = await _dsReceiveProvinceDataRepository.AnyAsync(p => p.CaseSerial == CaseSerial, HttpContext.RequestAborted); // await _dataOrderRepository.AnyAsync(p => p.ProvinceNo == CaseSerial, HttpContext.RequestAborted);
            if (isCheck == false)
                isCheck = await _sendCaseInfoRepository.AnyAsync(p => p.CaseSerial == CaseSerial, HttpContext.RequestAborted);
            if (!isCheck)
            {
                foreach (var file in files)
                {
                    // 文件名称
                    string fileName = file.FileName;

                    // 文件内容字节数据
                    using var memoryStream = new MemoryStream();
                    await file.CopyToAsync(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    byte[] fileContentBytes = memoryStream.ToArray();

                    // 构造字典文件数据
                    // 接口参数名称为files
                    CFormUpload.FileParameter fileParameter = new CFormUpload.FileParameter("files", fileContentBytes, fileName, null);

                    // strParams = "{ \"token\": \"\", \"paras\":{ \"MATERIAL_SERIAL\":\"RGDH99511500240304000100\", \"MATERIAL_TYPE\":\"10\", \"CLIENG_GUID\":\"91541fea-e1a5-4798-bc43-b25cc77ec6b7\", \"AREA_CODE\":\"511500\"} }";
                    Dictionary<string, object> dicParam = new()
                     {
                        { "params",  strParams } // 第一个接口参数，json格式字符串
                    };
                    dicParam.Add(fileName, fileParameter);

                    var token = await _fwClient.GetFileToken(HttpContext.RequestAborted);
                    string strUrl = configSendDataOld.AddressUrl + "api/receive/get_case_material_info";
                    // 上传附件
                    string strResult = CFormUpload.MultipartFormDataPost(strUrl, null, dicParam, token?.Token);

                }
                return true;
            }
            return false;
        }
        #endregion
    }

}
