using DataSharing.FwDataExchange;
using DataSharing.Police110.DaoShu110;
using DataSharing.Police110.Encryption;
using DataSharing.Police110.HaiNengDa110;
using DataSharing.Province;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.Police110.HaiNengDa110;
using DataSharing.Share.Enums;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Text;
using XF.Domain.Filters;
using XF.Domain.Repository;

namespace DataSharing.Host.Controllers.Police110
{
    /// <summary>
    /// 110工单交互
    /// 公司：海能达
    /// 市州：泸州、资阳、凉山、达州、巴中
    /// </summary>
    public class PoliceHNDController : BaseOkController
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly ICapPublisher _capPublisher;
        private readonly IRepository<DsReceivePoliceData> _dsReceivePoliceDataRepository;
        private readonly FwClient _fwClient;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IRepository<SendHotlineErrorData> _sendHotlineErrorDataRepository;
        private readonly IRepository<DsReceiveHandleData> _dsReceiveHandleDataRepository;
        private readonly ILogger<PoliceHNDController> _logger;
        private readonly IRepository<DsPoliceSendChainAlarmHnd> _dsPoliceSendChainAlarmHndRepository;
        private readonly IRepository<DsPoliceSendChainDealHnd> _dsPoliceSendChainDealHndRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="capPublisher"></param>
        /// <param name="dsReceivePoliceDataRepository"></param>
        /// <param name="fwClient"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="sendHotlineErrorDataRepository"></param>
        /// <param name="dsReceiveHandleDataRepository"></param>
        /// <param name="logger"></param>
        /// <param name="dsPoliceSendChainAlarmHndRepository"></param>
        /// <param name="dsPoliceSendChainDealHndRepository"></param>
        public PoliceHNDController(IMapper mapper,
            ICapPublisher capPublisher,
            IRepository<DsReceivePoliceData> dsReceivePoliceDataRepository,
            FwClient fwClient,
            ISharingConfigurationManager sharingConfigurationManager,
            IRepository<SendHotlineErrorData> sendHotlineErrorDataRepository,
            IRepository<DsReceiveHandleData> dsReceiveHandleDataRepository,
            ILogger<PoliceHNDController> logger,
            IRepository<DsPoliceSendChainAlarmHnd> dsPoliceSendChainAlarmHndRepository,
            IRepository<DsPoliceSendChainDealHnd> dsPoliceSendChainDealHndRepository)
        {
            _mapper = mapper;
            _capPublisher = capPublisher;
            _dsReceivePoliceDataRepository = dsReceivePoliceDataRepository;
            _fwClient = fwClient;
            _sharingConfigurationManager = sharingConfigurationManager;
            _sendHotlineErrorDataRepository = sendHotlineErrorDataRepository;
            _dsReceiveHandleDataRepository = dsReceiveHandleDataRepository;
            _logger = logger;
            _dsPoliceSendChainAlarmHndRepository = dsPoliceSendChainAlarmHndRepository;
            _dsPoliceSendChainDealHndRepository = dsPoliceSendChainDealHndRepository;
        }
        #endregion

        #region receive-工单受理-已完成---110推送受理工单给12345

        /// <summary>
        /// 工单受理
        /// </summary>
        /// <returns></returns>
        [HttpPost("receive/lz12345/orderAccept")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainAlarm_Receive()
        {
            ConfigurationPoliceHND configurationPoliceHND = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                configurationPoliceHND = _sharingConfigurationManager.GetLuZhouConfig().PoliceHND;
            _logger.LogInformation("收到数据---------");
            var sm4 = configurationPoliceHND.token1_sm4_mw;
            var apiR = new HaiNengDaDeResponse<string>();
            try
            {
                _logger.LogInformation("dcsm---------" + Request.Headers["dcsm"].ToString());
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceHND.token1_dcsm);

                _logger.LogInformation("验证dcsm---------" + dcsmMsg);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = HaiNengDaDeResponse<string>.Failed(null, dcsmMsg);
                }
                else
                {
                    string id = "";
                    string base64String = await GetStreamBase64(HttpContext.Request);
                    _logger.LogInformation("base64String---------" + base64String);
                    ChainAlarm_HND chainAlarm = new();
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        _logger.LogInformation("jsonRes---------" + jsonRes);
                        // json 转 实体类
                        if (!string.IsNullOrEmpty(jsonRes))
                            chainAlarm = System.Text.Json.JsonSerializer.Deserialize<ChainAlarm_HND>(jsonRes);

                        id = await InitRawData("\"api/police/receive/lz12345/orderAccept", base64String, jsonRes, chainAlarm?.AlarmReceiptNumber);

                        _logger.LogInformation("添加数据---------" + id);
                    }

                    #region 数据验证
                    //数据验证
                    string strResult = chainAlarm.Validate();
                    if (chainAlarm.IsSecret != "0" && chainAlarm.IsSecret != "1")
                        strResult = "【是否保密】不在字典项内";
                    if (chainAlarm.FromGender != "0" && chainAlarm.FromGender != "1" && chainAlarm.FromGender != "2")
                        strResult = "【报警人性别代码】不在字典项内";
                    if (!IsDate(chainAlarm.CallPoliceTime.ToString()))
                        strResult = "【报警时间】不是日期格式 yyyy-MM-dd HH:mm:ss";
                    if (!IsDate(chainAlarm.PushTime.ToString()))
                        strResult = "【推送时间】不是日期格式 yyyy-MM-dd HH:mm:ss";

                    #endregion

                    if (string.IsNullOrEmpty(strResult))
                    {

                        //组装业务系统工单数据
                        Hotline.Share.Dtos.Order.AddOrderDto orderDto = new()
                        {
                            ExternalId = chainAlarm.AlarmReceiptNumber,
                            //   AcceptorStaffNo = policeReceive.RegisterNo,
                            FromPhone = chainAlarm.CallPoliceNumber,
                            FromName = chainAlarm.CallPoliceName,
                            Contact = chainAlarm.PhoneNumber,
                            Content = chainAlarm.CallPoliceContent,
                            IncidentTime = Convert.ToDateTime(chainAlarm.CallPoliceTime),
                            AreaCode = chainAlarm.AreaCode,
                            FullAddress = chainAlarm.CallPoliceAddress,
                            SourceChannel = "110推送",
                            SourceChannelCode = "110TS",
                            Source = ESource.Police110,
                            IdentityType = EIdentityType.Citizen,
                            Transpond = false,
                            IsEnforcementOrder = false,
                            Title = chainAlarm.Title,
                            AcceptType = "咨询",
                            AcceptTypeCode = "10",
                            IsSecret = chainAlarm.IsSecret == "1",
                        };
                        orderDto.FromGender = chainAlarm.FromGender switch
                        {
                            "1" => EGender.Male,
                            "2" => EGender.Female,
                            _ => EGender.Unknown,
                        };
                        bool isSuccess = true;
                        string error = "";
                        //调用工单创建接口
                        try
                        {
                            var result = await _fwClient.RequestNoTokenAsync<HotlineClientResponse>("api/v1/Order/add-anonymous", "Post", System.Text.Json.JsonSerializer.Serialize(orderDto));
                            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.Police110,
                                ReceiveServiceInterface = "service/api/ds/110To12345/chainAlarm",
                                RawData = base64String,
                                RequestData = System.Text.Json.JsonSerializer.Serialize(orderDto),
                                Path = "api/v1/Order/add-anonymous",
                                SendTimes = 0,
                                HttpMethod = "Post",
                                ErrorMessage = error
                            };
                            await _sendHotlineErrorDataRepository.AddAsync(errorData, HttpContext.RequestAborted);
                        }

                        apiR = HaiNengDaDeResponse<string>.Succeed(null, "调用成功");

                    }
                    else
                        apiR = HaiNengDaDeResponse<string>.Failed(null, strResult);
                }
            }
            catch (Exception)
            {
                apiR = HaiNengDaDeResponse<string>.Failed(null, "接口异常");
            }

            #region 处理返回数据
            // 返回数据转Json
            string jsonResult = ModelToJson(apiR);
            // 加密：json通过sm4加密转base64
            string base64 = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResult);
            _logger.LogInformation($"输出：" + $"\r\n\r\nbase64：{base64}\r\nJson：{jsonResult}");
            #endregion

            return OpenResponse.Ok(base64);
        }

        #endregion

        #region receive-工单办结---110推送办理结果给12345

        /// <summary>
        /// 工单办结
        /// </summary>
        /// <returns></returns>
        [HttpPost("receive/lz12345/orderEnd")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainDeal_Receive()
        {
            ConfigurationPoliceHND configurationPoliceHND = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                configurationPoliceHND = _sharingConfigurationManager.GetLuZhouConfig().PoliceHND;

            string sm4 = configurationPoliceHND.token2_sm4_mw;
            var apiR = new HaiNengDaDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceHND.token2_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = HaiNengDaDeResponse<string>.Failed(null, dcsmMsg);
                }
                else
                {
                    ChainDeal_HND chainDeal = new();

                    string base64String = await GetStreamBase64(HttpContext.Request);
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        if (!string.IsNullOrEmpty(jsonRes))
                            // json 转 实体类
                            chainDeal = System.Text.Json.JsonSerializer.Deserialize<ChainDeal_HND>(jsonRes);

                        await InitRawData("api/police/receive/lz12345/orderEnd", base64String, jsonRes, chainDeal?.AlarmReceiptNumber);
                    }

                    #region 数据验证
                    string strResult = chainDeal.Validate();
                    if (chainDeal.FeedbackTime == "")
                        chainDeal.FeedbackTime = null;
                    if (chainDeal.ReturnTime == "")
                        chainDeal.ReturnTime = null;
                    if (chainDeal.RevisitTime == "")
                        chainDeal.RevisitTime = null;
                    #endregion

                    if (string.IsNullOrEmpty(strResult))
                    {
                        //这里组装数据推送到业务系统
                        await InitChainDeal(chainDeal);
                        apiR = HaiNengDaDeResponse<string>.Succeed(null, "调用成功");
                    }
                    else
                        apiR = HaiNengDaDeResponse<string>.Failed(null, strResult);

                }
            }
            catch (Exception)
            {
                apiR = HaiNengDaDeResponse<string>.Failed(null, "接口异常");
            }

            // 返回数据转Json
            string jsonResult = ModelToJson(apiR);
            // 加密：json通过sm4加密转base64
            string base64 = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResult);

            _logger.LogInformation($"输出：" + $"\r\n\r\nbase64：{base64}\r\nJson：{jsonResult}");

            return OpenResponse.Ok(base64);
        }

        #endregion

        #region send-工单受理-已完成---12345将警情工单推送给110

        /// <summary>
        /// 工单受理
        /// </summary>
        /// <returns></returns>
        [HttpPost("send/lz12345/orderAccept")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainAlarm_Send()
        {
            //{"startDate":"2023-04-01 10:43:17","endDate":"2023-04-17 10:43:17"}
            //gzWXSn3A2ZW9u3k9yrHdEqE5zRzto/Rud6LZ6JRJ1k59ou5nWABc8t8fR/sWU89lGweFQMsZkefowEBYzArADnSXjbKwfQj19UoF5RN/0mI=
            ConfigurationPoliceHND configurationPoliceHND = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                configurationPoliceHND = _sharingConfigurationManager.GetLuZhouConfig().PoliceHND;

            string sm4 = configurationPoliceHND.token3_sm4_mw;
            var apiR = new HaiNengDaDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceHND.token3_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = HaiNengDaDeResponse<string>.Failed(dcsmMsg);
                }
                else
                {
                    OpenData openData = new();
                    string base64String = await GetStreamBase64(HttpContext.Request);
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        if (!string.IsNullOrEmpty(jsonRes))
                            // json 转 实体类
                            openData = System.Text.Json.JsonSerializer.Deserialize<OpenData>(jsonRes);

                        //await InitRawData("api/police/send/lz12345/orderAccept", base64String, jsonRes, openData?.AlarmReceiptNumber);
                    }

                    var listData = await _dsPoliceSendChainAlarmHndRepository.Queryable()
                         .WhereIF(!string.IsNullOrEmpty(openData.FlowID), p => Convert.ToInt64(p.No) > Convert.ToInt64(openData.FlowID))
                         .Select(p => new ChainAlarm_HNDNewDto
                         {
                             FLOWID = p.No,
                             LSH = p.SerialNumber,
                             JJYBH = p.RegisterNo,
                             JJDBH = p.AlarmReceiptNumber,
                             BJDH = p.CallPoliceNumber,
                             BJDHYHM = p.CallPoliceName,
                             LXDH = p.PhoneNumber,
                             BJDZ = p.CallPoliceAddress,
                             JQLBDM = p.PoliceTypeCode,
                             JQLBMC = p.PoliceTypeName,
                             BJNR = p.CallPoliceContent,
                             GXDWDM = p.JurisdictionalUnitCode,
                             GXDWMC = p.JurisdictionalUnitName,
                             GXDWDH = p.JurisdictionalUnitNumber,
                             BJSJ = p.CallPoliceTime,
                             TSSJ = p.PushTime,
                             JJDWDM = p.AlarmReceivingUnitCode,
                             JJDWMC = p.AlarmReceivingUnitName,
                             JJLX = p.AlarmReceptionType,
                             XZQHDM = p.AreaCode,
                             SFBM = p.IsSecret,
                             BJRXBDM = p.FromGender,
                             Title = p.Title
                         })
                         .OrderBy(p => p.JJDBH)
                         .Take(20)
                         .ToListAsync();

                    if (null == listData)
                        apiR = HaiNengDaDeResponse<string>.Failed(null);
                    else
                    {
                        var daoShuDe = HaiNengDaDeResponse<List<ChainAlarm_HNDNewDto>>.Succeed(listData, "调用成功");
                        string jsonResultok = ModelToJson(daoShuDe);
                        // 加密：json通过sm4加密转base64
                        string base64ok = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResultok);
                        _logger.LogInformation($"输出：" + $"\r\n\r\nbase64：{base64ok}\r\nJson：{jsonResultok}");
                        return OpenResponse.Ok(base64ok);
                    }
                }
            }
            catch (Exception)
            {
                apiR = HaiNengDaDeResponse<string>.Failed("接口异常");
            }

            // 返回数据转Json
            //string jsonResult = ModelToJson(apiR);

            string jsonResult = System.Text.Json.JsonSerializer.Serialize(apiR, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions);
            jsonResult = System.Text.RegularExpressions.Regex.Unescape(jsonResult);
            // 加密：json通过sm4加密转base64
            string base64 = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResult);

            _logger.LogInformation($"输出：" + $"\r\n\r\nbase64：{base64}\r\nJson：{jsonResult}");
            return OpenResponse.Ok(base64);
        }

        #endregion

        #region send-工单办结---12345将110推过来的工单办理结果推送给110

        /// <summary>
        /// 工单办结
        /// </summary>
        /// <returns></returns>
        [HttpPost("send/lz12345/orderEnd")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainDeal_Send()
        {
            // 测试JSON
            // {"JJDBH":"510300202304070001202304070001","CZLX":"1"}

            // 测试Base64
            // 6RB6Hat8dpBfvCTtEpwotd/MlonxdmqZaa3TcLaua/xcjFv1SZJzKZPrhgsux63Gq/DXxtAQ25buLsI1fgFv3g==
            ConfigurationPoliceHND configurationPoliceHND = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.LuZhou))
                configurationPoliceHND = _sharingConfigurationManager.GetLuZhouConfig().PoliceHND;

            string sm4 = configurationPoliceHND.token4_sm4_mw;
            var apiR = new HaiNengDaDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceHND.token4_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = HaiNengDaDeResponse<string>.Failed(dcsmMsg);
                }
                else
                {
                    string base64String = await GetStreamBase64(HttpContext.Request);
                    OpenData openData = new();
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        if (!string.IsNullOrEmpty(jsonRes))
                            // json 转 实体类
                            openData = System.Text.Json.JsonSerializer.Deserialize<OpenData>(jsonRes);

                        //await InitRawData("service/api/ds/12345To110/chainDeal", base64String, jsonRes, openData?.AlarmReceiptNumber);
                    }

                    bool bRun = true;

                    if (openData.DYYY != "1" && openData.DYYY != "2" && openData.DYYY != "3" && openData.DYYY != "4")
                    {
                        bRun = false;
                        apiR = HaiNengDaDeResponse<string>.Failed("【接口调用原因】不符合要求");
                    }

                    if (bRun)
                    {
                        var listData = await _dsPoliceSendChainDealHndRepository.Queryable()
                                 .WhereIF(!string.IsNullOrEmpty(openData.FlowID), p => Convert.ToInt64(p.No) > Convert.ToInt64(openData.FlowID))
                                 .Where(p => p.DisposalType == openData.DYYY)
                                 .Select(p => new ChainDeal_HNDNewDto
                                 {
                                     FLOWID = p.No,
                                     JJDBH = p.AlarmReceiptNumber,
                                     FKSJ = p.FeedbackTime,
                                     CJCZQK = p.DisposalSituation,
                                     JQCLJGSM = p.ResultDescription,
                                     FKYBH = p.FeedbackPersonNumber,
                                     FKYXM = p.FeedbackPersonName,
                                     FKDWDM = p.FeedbackUnitCode,
                                     FKDWMC = p.FeedbackUnitName,
                                     TSSJ = p.WarehousingTime,
                                     HFSJ = p.RevisitTime,
                                     DHHFHSQK = p.CheckingContent,
                                     CLJGDM = p.VisitResult,
                                     CLJGMC = p.VisitContent,
                                     HANDLEUSERNAME = p.ReturnName,
                                     HANDLEBMNAME = p.ReturnUnit,
                                     HANDLEOPINION = p.ReturnOpinion,
                                     HANDLETIME = p.ReturnTime,
                                     DYYY = p.DisposalType
                                 })
                                 .OrderBy(p => p.JJDBH)
                                 .Take(20)
                                 .ToListAsync();

                        if (null == listData)
                            apiR = HaiNengDaDeResponse<string>.Failed(null);
                        else
                        {
                            var daoShuDe = HaiNengDaDeResponse<List<ChainDeal_HNDNewDto>>.Succeed(listData, "调用成功");
                            string jsonResultok = ModelToJson(daoShuDe);

                            // 加密：json通过sm4加密转base64
                            string base64ok = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResultok);
                            _logger.LogInformation($"输出：" + $"\r\n\r\nbase64：{base64ok}\r\nJson：{jsonResultok}");
                            return OpenResponse.Ok(base64ok);
                        }
                    }
                }
            }
            catch (Exception)
            {
                apiR = HaiNengDaDeResponse<string>.Failed("接口异常");
            }

            // 返回数据转Json
            //string jsonResult = ModelToJson(apiR);
            string jsonResult = System.Text.Json.JsonSerializer.Serialize(apiR, ProvinceJsonSerializerOptions.UnStandardDatetimeJsonOptions);
            jsonResult = System.Text.RegularExpressions.Regex.Unescape(jsonResult);
            // 加密：json通过sm4加密转base64
            string base64 = Sm4Crypto.Encrypt_ECB_Base64(sm4, jsonResult);
            _logger.LogInformation($"输出：" + $"\r\n\r\nbase64：{base64}\r\nJson：{jsonResult}");

            return OpenResponse.Ok(base64);
        }

        #endregion

        #region 私有方法

        #region 工单办结

        /// <summary>
        /// 工单办结
        /// </summary>
        /// <param name="policeReceiveChainDealDs"></param>
        /// <returns></returns>
        private async Task InitChainDeal(ChainDeal_HND policeReceiveChainDealDs)
        {
            var orderData = await _dsPoliceSendChainAlarmHndRepository.GetAsync(p => p.AlarmReceiptNumber == policeReceiveChainDealDs.AlarmReceiptNumber);
            if (orderData is null)
            {
                //写入对外展示表数据
                DsReceiveHandleData dsReceive = new()
                {
                    OrderNo = orderData.OrderId,
                    Source = "110平台",
                    PlatformsName = "110平台",
                    ReceiveData = System.Text.Json.JsonSerializer.Serialize(policeReceiveChainDealDs)
                };
                if (policeReceiveChainDealDs.DisposalType == "1")//正常办理
                {
                    dsReceive.OperationType = "110推送办理结果";
                    dsReceive.Opinion = policeReceiveChainDealDs.DisposalSituation;
                }
                else if (policeReceiveChainDealDs.DisposalType == "2")//退回 
                {
                    dsReceive.OperationType = "110退回";
                    dsReceive.Opinion = policeReceiveChainDealDs.ReturnOpinion;
                }
                else if (policeReceiveChainDealDs.DisposalType == "3")//回访 
                {
                    var orgProcessingResults = policeReceiveChainDealDs.VisitResult switch
                    {
                        "1" => "非常满意",//非常满意
                        "2" => "满意",//满意
                        "3" => "不满意",//不满意
                        _ => "满意",
                    };
                    dsReceive.OperationType = "110回访内容";
                    dsReceive.Opinion = "回访时间：" + policeReceiveChainDealDs.RevisitTime + "/br回访内容：" + policeReceiveChainDealDs.VisitContent + "/br回访方式：人工回访/br满意度" + orgProcessingResults;
                }

                await _dsReceiveHandleDataRepository.AddAsync(dsReceive, HttpContext.RequestAborted);
                return;
            }

            if (policeReceiveChainDealDs.DisposalType == "1")//正常办理
            {
                OrderResultDto orderResultDto = new()
                {
                    OrderId = orderData.OrderId,
                    FinishType = "1",
                    Opinion = policeReceiveChainDealDs.DisposalSituation,
                    Source = "110"
                };
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResultDto, cancellationToken: HttpContext.RequestAborted);
            }
            else if (policeReceiveChainDealDs.DisposalType == "2")//退回 
            {
                OrderResultDto orderResultDto = new()
                {
                    OrderId = orderData.OrderId,
                    FinishType = "0",
                    Opinion = policeReceiveChainDealDs.ReturnOpinion,
                    Source = "110"
                };
                //向业务系统推送消息
                await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.SharingOrderReultSend, orderResultDto, cancellationToken: HttpContext.RequestAborted);

            }
            else if (policeReceiveChainDealDs.DisposalType == "3")//回访 
            {
                ProvinceOrderVisitDto orderVisitDto = new()
                {
                    ProvinceNo = orderData.OrderId,
                    VisitTime = Convert.ToDateTime(policeReceiveChainDealDs.RevisitTime),
                    VisitContent = policeReceiveChainDealDs.VisitContent,
                    //  OrgProcessingResults = policeReceiveChainDealDs.VisitResult,
                    VisitType = EVisitType.ArtificialVisit
                };
                orderVisitDto.OrgProcessingResults = policeReceiveChainDealDs.VisitResult switch
                {
                    "1" => "5",//非常满意
                    "2" => "4",//满意
                    "3" => "2",//不满意
                    _ => "4",
                };

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

        #endregion

        #region 写入原始数据
        /// <summary>
        /// 写入原始数据
        /// </summary>
        /// <param name="externalId"></param>
        /// <param name="serviceInterface"></param>
        /// <param name="receiveRawData"></param>
        /// <param name="receiveData"></param>
        /// <returns></returns>
        private async Task<string> InitRawData(string serviceInterface, string receiveRawData, string receiveData, string? externalId)
        {
            DsReceivePoliceData dsReceivePoliceData = new()
            {
                ExternalId = externalId,
                ServiceInterface = serviceInterface,
                ReceiveRawData = receiveRawData,
                ReceiveData = receiveData
            };
            return await _dsReceivePoliceDataRepository.AddAsync(dsReceivePoliceData, HttpContext.RequestAborted);
        }
        #endregion

        #region 获取RAW传入的Base64_Json
        /// <summary>
        /// 获取RAW传入的Base64_Json
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static async Task<string> GetStreamBase64(HttpRequest request)
        {
            string base64String = "";
            try
            {
                request.EnableBuffering();
                request.Body.Position = 0;
                using (var stream = new StreamReader(request.Body, Encoding.UTF8))
                {
                    base64String = await stream.ReadToEndAsync();
                }
            }
            catch (Exception)
            {
            }
            return base64String;
        }
        #endregion

        #region 验证DCSM是否正确

        /// <summary>
        /// 验证DCSM是否正确
        /// </summary>
        /// <param name="headrs"></param>
        /// <param name="dcsmIn"></param>
        /// <returns></returns>
        private static string CheckDcsm(string headrs, string dcsmIn)
        {
            string result = "";
            string dcsm = "";
            try
            {
                dcsm = headrs.ToString();
                if (dcsm != dcsmIn)
                {
                    result = "【dcsm】错误";
                }
            }
            catch (Exception)
            {
                result = "【dcsm】不能为空";
            }
            return result;
        }

        #endregion

        #region 验证日期
        private static bool IsDate(string strDate)
        {
            try
            {
                if (strDate.Contains('.') == true || strDate.Contains(',') == true)
                {
                    return false;
                }
                DateTime.Parse(strDate);  //不是字符串时会出现异常
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 转Json
        /// <summary>
        /// 转Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static string ModelToJson(object obj)
        {
            string jsonstr = "";
            try
            {
                IsoDateTimeConverter timejson = new IsoDateTimeConverter
                {
                    DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
                    //如果是年月日的话就是 ：DateTimeFormat = "yyyy'-'MM'-'dd" 注意第一个y前面没有单引号 最后一个d后面也没有单引号
                };
                jsonstr = JsonConvert.SerializeObject(obj, timejson);
            }
            catch (Exception)
            {
            }
            return jsonstr;
        }
        #endregion

        #endregion
    }
}
