using DataSharing.FwDataExchange;
using DataSharing.Police110.DaoShu110;
using DataSharing.Police110.DCJT110;
using DataSharing.Police110.Encryption;
using DataSharing.RawData;
using DataSharing.Share.Dtos;
using DataSharing.Share.Dtos.HotlineSetting;
using DataSharing.Share.Dtos.Police110;
using DataSharing.Share.Dtos.Police110.DaoShu110;
using DataSharing.Share.Dtos.Police110.DCJT110;
using DataSharing.Share.Enums;
using DotNetCore.CAP;
using Hotline.Share.Dtos.DataSharing.PusherHotlineDto;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using MediatR;
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 PoliceDCJTController : BaseOkController
    {
        #region 注入
        private readonly IMapper _mapper;
        private readonly ICapPublisher _capPublisher;
        private readonly IMediator _mediator;
        private readonly IRepository<DsPoliceSendChainAlarmDcjt> _dsPoliceSendChainAlarmDcjtRepository;
        private readonly IRepository<DsPoliceSendChainDealDcjt> _dsPoliceSendChainDealDcjtRepository;
        private readonly IRepository<DsKnowledgeRawData> _dsKnowledgeRawDataRepository;
        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<PoliceDCJTController> _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="capPublisher"></param>
        /// <param name="mediator"></param>
        /// <param name="dsPoliceSendChainAlarmDcjtRepository"></param>
        /// <param name="dsPoliceSendChainDealDcjtRepository"></param>
        /// <param name="dsKnowledgeRawDataRepository"></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>
        public PoliceDCJTController(IMapper mapper,
            ICapPublisher capPublisher,
            IMediator mediator,
            IRepository<DsPoliceSendChainAlarmDcjt> dsPoliceSendChainAlarmDcjtRepository,
            IRepository<DsPoliceSendChainDealDcjt> dsPoliceSendChainDealDcjtRepository,
            IRepository<DsKnowledgeRawData> dsKnowledgeRawDataRepository,
            IRepository<DsReceivePoliceData> dsReceivePoliceDataRepository,
            FwClient fwClient,
            ISharingConfigurationManager sharingConfigurationManager,
            IRepository<SendHotlineErrorData> sendHotlineErrorDataRepository,
            IRepository<DsReceiveHandleData> dsReceiveHandleDataRepository,
            ILogger<PoliceDCJTController> logger)
        {
            _mapper = mapper;
            _capPublisher = capPublisher;
            _mediator = mediator;
            _dsPoliceSendChainAlarmDcjtRepository = dsPoliceSendChainAlarmDcjtRepository;
            _dsPoliceSendChainDealDcjtRepository = dsPoliceSendChainDealDcjtRepository;
            _dsKnowledgeRawDataRepository = dsKnowledgeRawDataRepository;
            _dsReceivePoliceDataRepository = dsReceivePoliceDataRepository;
            _fwClient = fwClient;
            _sharingConfigurationManager = sharingConfigurationManager;
            _sendHotlineErrorDataRepository = sendHotlineErrorDataRepository;
            _dsReceiveHandleDataRepository = dsReceiveHandleDataRepository;
            _logger = logger;
        }
        #endregion

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

        /// <summary>
        /// 工单受理
        /// </summary>
        /// <returns></returns>
        [HttpPost("service/api/dcjt/110To12345/chainAlarm")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainAlarm_Receive()
        {
            // 测试JSON
            // {"LSH":"510300202304070001202304070001","JJYBH":"1001","JJDBH":"510300202304070001202304070001","BJDH":"13555555555","BJDHYHM":"李四","LXDH":"13555555555","BJDZ":"报警地址","JQLBDM":"","JQLBMC":"","BJNR":"报警内容","GXDWDM":"","GXDWMC":"","GXDWDH":"","BJSJ":"2023-04-07 10:43:17","TSSJ":"2023-04-07 10:43:21","JJDWDM":"12345","JJDWMC":"12345","JJLX":"1","XZQHDM":"510300"}
            // 测试Base64
            // kKeUhfS8zca5WTA9D2Z7z/GthYLHroPi8jLN2HduG2vK1PCjb56BZ3wLNCiA8V91ARHpOkE50xFdwBJhW+QKB7J2FRjJ6WUrzkKal75G3DCWzl+Fzto+XbkS5U5wUYnII2zSpdo4U6ILrrK2t2u8mFTd1i03+D1Ytv4TlUH5Jwg/xq00AeF/CVhes4+H5PPcxdU/h3KCDMq9Qaoxf6pALQCMBfatQdsDMw4MG0RK5DUbuaCuElOxfCjlDadZTLuVjHWHDw6wWG9sucqN3mrRllxytIDqIsLSdBi1KuCPaW+FhXf5/+v6Eipby8QEXXTPZxOW4m/Kp8cF87+rxBxRE7nIGAjdO2mKDyfiDeipENxKkQs6taTS52U2OG99Prfp+UAU1Uaj69gQ0IShMVqLgnESWhL5b/vIgO2mtYgIIZ7RpwlTuVqVZKxaFfPpjnQtGRFZPDPHVQcqQ7MMT3rjg6/AWVI/Jh7q+pdu18Y6cojl/EGd/XsNVip+uvAeXdCk
            ConfigurationPoliceDCJT configurationPoliceDCJT = new();

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

                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = DCJTDeResponse<string>.Failed(null, dcsmMsg);
                }
                else
                {
                    string base64String = await GetStreamBase64(HttpContext.Request);
                    _logger.LogInformation("base64String---------" + base64String);
                    ChainAlarm_DCJT 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_DCJT>(jsonRes);

                        id = await InitRawData("/service/api/dcjt/110To12345/chainAlarm", base64String, jsonRes, chainAlarm?.AlarmReceiptNumber);
                        _logger.LogInformation("添加数据---------" + id);
                    }

                    #region 数据验证
                    //数据验证
                    string strResult = chainAlarm.Validate();
                    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,
                            Street = chainAlarm.CallPoliceAddress,
                            SourceChannel = "110接警平台",
                            SourceChannelCode = "110",
                            Source = ESource.Police110,
                            IdentityType = EIdentityType.Citizen,
                            Transpond = false,
                            IsEnforcementOrder = false,
                            Title = string.Empty,
                            AcceptType = "咨询",
                            AcceptTypeCode = "10"
                        };
                       
                        if (!string.IsNullOrEmpty(orderDto.AreaCode))
                        {
                            if (orderDto.AreaCode == "510399")
                                orderDto.AreaCode = "519800";
                            if(orderDto.AreaCode.Length>6)
                                orderDto.AreaCode=orderDto.AreaCode.Substring(0,6);
                        }
                        orderDto.FromGender = chainAlarm.FromGender switch
                        {
                            "0" => EGender.Female,
                            "1" => EGender.Male,
                            _ => 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/dcjt/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 = DCJTDeResponse<string>.Succeed(null, "调用成功");

                    }
                    else
                        apiR = DCJTDeResponse<string>.Failed(null, strResult);
                }
            }
            catch (Exception)
            {
                apiR = DCJTDeResponse<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("service/api/dcjt/110To12345/chainDeal")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainDeal_Receive()
        {
            // 测试 办结 {"JJDBH":"510300202304070001202304070001","CZLX":"1","FKSJ":"2023-04-07 10:52:44","CJCZQK":"办理结果","JQCLJGSM":"办理结果","FKYBH":"1001","FKYXM":"1001","FKDWDM":"","FKDWMC":"","HFSJ":"","DHHFHSQK":"","CLJGDM":"","CLJGMC":"","HANDLEUSERNAME":"","HANDLEBMNAME":"","HANDLEOPINION":"","HANDLETIME":"","TSSJ":"2023-04-07 10:53:19"}
            // 测试 退回 {"JJDBH":"510300202304070001202304070001","CZLX":"2","FKSJ":"","CJCZQK":"","JQCLJGSM":"","FKYBH":"","FKYXM":"","FKDWDM":"","FKDWMC":"","HFSJ":"","DHHFHSQK":"","CLJGDM":"","CLJGMC":"","HANDLEUSERNAME":"退回人","HANDLEBMNAME":"退回姓名","HANDLEOPINION":"退回原因","HANDLETIME":"2023-04-07 10:53:19","TSSJ":"2023-04-07 10:53:19"}
            // 测试 回访 {"JJDBH":"510300202304070001202304070001","CZLX":"3","FKSJ":"","CJCZQK":"","JQCLJGSM":"","FKYBH":"","FKYXM":"","FKDWDM":"","FKDWMC":"","HFSJ":"2023-04-07 10:54:23","DHHFHSQK":"回访情况","CLJGDM":"2","CLJGMC":"回访内容","HANDLEUSERNAME":"","HANDLEBMNAME":"","HANDLEOPINION":"","HANDLETIME":"","TSSJ":"2023-04-07 10:53:19"}

            // 测试Base64
            // 办结 Jv5JJHwByfD4CXMb1l4PtPsgC6UmNeRfws6mEKz24rackMA28z27tu2GRlIyq0qmbeYeEM0nY783aUxb0jlqSQlk+xtc6cop/CvZI5vczHIsXhtfNozkW/hlx/R43ecuKEvyMzEHwf3EuBZ7jsY1zGuJe61K6YTkmCt6+Xndbd585ZMluNJNIA0qZPbT08jVDiI+wa9ot3HA7AEuDqNxJwfU7NfqoTk6Ml5nnuPkdmp55VKeoLZspAgBflEtFJyppIsN0VQyJkrn+ADQFOPcTpedx5H6+V+2MYM9+5pE/Re17S+s3cA53vWHsf6KhHnCm3M9qtbocu0TtpAEfyMEBQOIRn4pSEJ1i98fpD3xjzuxddkGPOBvhYrh8Tf3IbNTNpNozEda2a0RFmBCQyfzLvEdk4ZK/obYDKncePIRrE3ZtO2QAeAa3H6V532MxcniZJ4mIqHsKShR2Q8uxdsR5Q==
            // 退回 Jv5JJHwByfD4CXMb1l4PtPsgC6UmNeRfws6mEKz24rackMA28z27tu2GRlIyq0qm1U2lexAxHJK7Bhoyw7CNiEXjiobQjSKF2RWOrUHZINPed01DQRTw2pIL03EFsrQpEjsslviumN+BTn/cuJQp8zD2ifPclM87jEJfP2EY6D+UGvUfSebT9mMghSo2VaUeqFzlRKpJmcU6XjV7C65zddc8DEXuYzt0zqATyhac9AO3RGB5SEw9MX1olV8WwPgV4h3OkTTVZ+Dq5co/eb28YIBN+Rshjpv82RusV2thgfvudOyCDZcRDbjh6pEdtj/lvVH/BU2cDo3ch17KtzsPE+xkQvJ68zaAnS8f/klQrFrDHlkmTMi6rEa605yUhhPZFz0Jba+Axizil38YbHV9A1YoxoJNjFXIyL90yCMznb4joMQPRRddp5ky/CbT9r0q283gKBdAY6/v+ywPdalFjg==
            // 回访 Jv5JJHwByfD4CXMb1l4PtPsgC6UmNeRfws6mEKz24rackMA28z27tu2GRlIyq0qmvLqUgIfd0QkyZbzT0iQZwEXjiobQjSKF2RWOrUHZINPed01DQRTw2pIL03EFsrQpEjsslviumN+BTn/cuJQp8zD2ifPclM87jEJfP2EY6D8cMxuK/4X9pyxRWKIQtLFdh4ieC9bhojhr2XxStPHmDV4c3oNEybczbb7IXsaW2FCGMI4SLF7Z+VXDSpCGpFX+0dyUUQPnoRrgU7wndkn/6VYi2Axm19MBkwK+Wm5v85oVQ1HFptf5leUiSXomF9XCPtgWbLOFzu313JW7WQvjgllM7usjI2mbyGtQ5EMXyOGJ/AmAupELpMYVwjoGAKy6B/GE1HFyPiLAazsUE3jfaLPxn/Gld0Ef2glG1SQ/vakDtyvyoJDE83pYvBesmQMx
            ConfigurationPoliceDCJT configurationPoliceDCJT = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configurationPoliceDCJT = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;

            string sm4 = configurationPoliceDCJT.token4_sm4_mw;
            var apiR = new DCJTDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceDCJT.token4_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = DCJTDeResponse<string>.Failed(null, dcsmMsg);
                }
                else
                {
                    ChainDeal_DCJT chainDeal = new();

                    string base64String = await GetStreamBase64(HttpContext.Request);
                    _logger.LogInformation($"接收原始数据：" + $"\r\n\r\nbase64：{base64String}");
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        _logger.LogInformation($"接收原始数据jsonRes：" + $"jsonRes：{jsonRes}");
                        if (!string.IsNullOrEmpty(jsonRes))
                        {
                            var data = JsonConvert.DeserializeObject<ChainDeal_DCJTNewDto>(jsonRes);
                            jsonRes = JsonConvert.SerializeObject(data);
                        }
                        // json 转 实体类
                        chainDeal = System.Text.Json.JsonSerializer.Deserialize<ChainDeal_DCJT>(jsonRes);

                        _logger.LogInformation("base64String---------" + base64String);
                        await InitRawData("service/api/dcjt/110To12345/chainDeal", 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 = DCJTDeResponse<string>.Succeed(null, "调用成功");
                    }
                    else
                        apiR = DCJTDeResponse<string>.Failed(null, "调用失败");

                }
            }
            catch (Exception)
            {
                apiR = DCJTDeResponse<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 send-工单受理-已完成---12345将警情工单推送给110

        /// <summary>
        /// 工单受理
        /// </summary>
        /// <returns></returns>
        [HttpPost("service/api/dcjt/12345To110/chainAlarm")]
        [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=
            ConfigurationPoliceDCJT configurationPoliceDCJT = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configurationPoliceDCJT = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;

            string sm4 = configurationPoliceDCJT.token3_sm4_mw;
            var apiR = new DCJTDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceDCJT.token3_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = DCJTDeResponse<string>.Failed(null, dcsmMsg);
                }
                else
                {
                    SendData sendData = 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 转 实体类
                            sendData = System.Text.Json.JsonSerializer.Deserialize<SendData>(jsonRes);

                        //await InitRawData("service/api/dcjt/12345To110/chainAlarm", base64String, jsonRes, sendData?.AlarmReceiptNumber);
                    }
                    bool bRun = true;
                    if (!string.IsNullOrEmpty(sendData.StartDate) && !IsDate(sendData.StartDate))
                    {
                        bRun = false;
                        apiR = DCJTDeResponse<string>.Failed(null, "【创建开始时间】不是日期格式 yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(sendData.EndDate) && !IsDate(sendData.EndDate))
                    {
                        bRun = false;
                        apiR = DCJTDeResponse<string>.Failed(null, "【创建结束时间】不是日期格式 yyyy-MM-dd HH:mm:ss");
                    }
                    if (bRun)
                    {
                        int takeNum = 10;
                        if (!string.IsNullOrEmpty(sendData.StartDate) || !string.IsNullOrEmpty(sendData.EndDate))
                            takeNum = 100;

                        var listData = await _dsPoliceSendChainAlarmDcjtRepository.Queryable()
                             .WhereIF(!string.IsNullOrEmpty(sendData.StartDate), p => p.CallPoliceTime >= Convert.ToDateTime(sendData.StartDate))
                             .WhereIF(!string.IsNullOrEmpty(sendData.EndDate), p => p.CallPoliceTime <= Convert.ToDateTime(sendData.EndDate))
                             .Select(p => new ChainAlarm_DCJTNewDto
                             {
                                 LSH = p.SerialNumber,
                                 JJYBH = p.RegisterNo,
                                 JJYXM = p.RegisterName,
                                 JJDBH = p.AlarmReceiptNumber,
                                 BJDH = p.CallPoliceNumber,
                                 BJRXB = p.FromGender,
                                 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
                             })
                             .OrderByDescending(p => p.TSSJ)
                             .Take(takeNum)
                             .ToListAsync();

                        if (null == listData)
                            apiR = DCJTDeResponse<string>.Failed(null);
                        else
                        {
                            var daoShuDe = DaoShuDeResponse<List<ChainAlarm_DCJTNewDto>>.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 = DCJTDeResponse<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 send-工单办结---12345将110推过来的工单办理结果推送给110

        /// <summary>
        /// 工单办结
        /// </summary>
        /// <returns></returns>
        [HttpPost("service/api/dcjt/12345To110/chainDeal")]
        [AllowAnonymous]
        public async Task<OpenResponse> ChainDeal_Send()
        {
            // 测试JSON
            // {"JJDBH":"510300202304070001202304070001","CZLX":"1"}

            // 测试Base64
            // 6RB6Hat8dpBfvCTtEpwotd/MlonxdmqZaa3TcLaua/xcjFv1SZJzKZPrhgsux63Gq/DXxtAQ25buLsI1fgFv3g==
            ConfigurationPoliceDCJT configurationPoliceDCJT = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configurationPoliceDCJT = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;

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

                        //await InitRawData("service/api/dcjt/12345To110/chainDeal", base64String, jsonRes, sendData?.AlarmReceiptNumber);
                    }
                    bool bRun = true;

                    if (!string.IsNullOrEmpty(sendData.StartDate) && !IsDate(sendData.StartDate))
                    {
                        bRun = false;
                        apiR = DCJTDeResponse<string>.Failed(null, "【创建开始时间】不是日期格式 yyyy-MM-dd HH:mm:ss");
                    }
                    if (!string.IsNullOrEmpty(sendData.EndDate) && !IsDate(sendData.EndDate))
                    {
                        bRun = false;
                        apiR = DCJTDeResponse<string>.Failed(null, "【创建结束时间】不是日期格式 yyyy-MM-dd HH:mm:ss");
                    }

                    if (bRun)
                    {
                        //默认查询20条，当有参数查询100条
                        int takeNum = 20;
                        if (!string.IsNullOrEmpty(sendData.StartDate) || !string.IsNullOrEmpty(sendData.EndDate))
                            takeNum = 100;
                        if (!string.IsNullOrEmpty(sendData.AlarmReceiptNumber))
                            takeNum = 100;
                        if (!string.IsNullOrEmpty(sendData.DisposalType))
                            takeNum = 100;
                        var listData = await _dsPoliceSendChainDealDcjtRepository.Queryable()
                                 .WhereIF(!string.IsNullOrEmpty(sendData.StartDate), p => p.WarehousingTime >= Convert.ToDateTime(sendData.StartDate))
                                 .WhereIF(!string.IsNullOrEmpty(sendData.EndDate), p => p.WarehousingTime <= Convert.ToDateTime(sendData.EndDate))
                                 .WhereIF(!string.IsNullOrEmpty(sendData.AlarmReceiptNumber), p => p.AlarmReceiptNumber == sendData.AlarmReceiptNumber)
                                 //  .Where(p => p.DisposalType == sendData.DisposalType)
                                 .WhereIF(!string.IsNullOrEmpty(sendData.DisposalType), p => sendData.DisposalType.Contains(p.DisposalType))
                                 .Select(p => new ChainDeal_DCJTNewDto
                                 {
                                     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,
                                     CZLX = p.DisposalType,
                                     DYYY = p.CreatorName
                                 })
                                 .OrderByDescending(p => p.TSSJ)
                                 .Take(50)
                                 .ToListAsync();

                        if (null == listData)
                            apiR = DCJTDeResponse<string>.Failed(null);
                        else
                        {
                            var daoShuDe = DCJTDeResponse<List<ChainDeal_DCJTNewDto>>.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 = DCJTDeResponse<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-知识库列表-已完成

        /// <summary>
        /// 查询知识库列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("service/api/dcjt/get_knowledge_info")]
        [AllowAnonymous]
        public async Task<OpenResponse> Get_Knowledge_Info()
        {
            // 测试Json
            // {"createTimeBegin":"2003-04-07 10:59:14","createTimeEnd":"2023-12-07 10:59:21","keyWord":"市民"}
            // {"createTimeBegin":"2003-04-07 10:59:14","createTimeEnd":"2023-12-07 10:59:21","keyWord":""}

            // 测试Base64
            // sVGPN7BDsKnDLrd6NzrGx+2IH6vVAo6bjGSenIgCJATssZduYxBOLdQi7TVdsBCy7AGk15xjKRVe4AdovL6r49fxDvWjyDlxS8K4qkukEOtYs/VyP6WIdiKQL6PC3i/T
            // sVGPN7BDsKnDLrd6NzrGx+2IH6vVAo6bjGSenIgCJATssZduYxBOLdQi7TVdsBCy7AGk15xjKRVe4AdovL6r49fxDvWjyDlxS8K4qkukEOuaeRL4jMcFsN7HoUTHfDrk
            ConfigurationPoliceDCJT configurationPoliceDCJT = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configurationPoliceDCJT = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;

            string sm4 = configurationPoliceDCJT.token5_sm4_mw;
            var apiR = new DCJTDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceDCJT.token5_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                {
                    apiR = DCJTDeResponse<string>.Failed(dcsmMsg);
                }
                else
                {
                    string base64String = await GetStreamBase64(HttpContext.Request);

                    SendKnowledgeRequestDto sendKnowledge = new SendKnowledgeRequestDto();
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        if (!string.IsNullOrEmpty(jsonRes))
                            // json 转 实体类
                            sendKnowledge = System.Text.Json.JsonSerializer.Deserialize<SendKnowledgeRequestDto>(jsonRes);

                        await InitRawData("service/api/dcjt/get_knowledge_info", base64String, jsonRes, null);
                    }

                    bool bRun = true;
                    if (string.IsNullOrEmpty(sendKnowledge.createTimeBegin) || !IsDate(sendKnowledge.createTimeBegin))
                    {
                        bRun = false;
                        apiR = DCJTDeResponse<string>.Failed("【创建开始时间】不是日期格式 yyyy-MM-dd HH:mm:ss");
                    }
                    if (string.IsNullOrEmpty(sendKnowledge.createTimeEnd) || !IsDate(sendKnowledge.createTimeEnd))
                    {
                        bRun = false;
                        apiR = DCJTDeResponse<string>.Failed("【创建结束时间】不是日期格式 yyyy-MM-dd HH:mm:ss");
                    }
                    if (bRun)
                    {
                        var listData = await _dsKnowledgeRawDataRepository
                        .Queryable()
                        .WhereIF(!string.IsNullOrEmpty(sendKnowledge.createTimeBegin), p => p.CreatDate >= Convert.ToDateTime(sendKnowledge.createTimeBegin))
                          .WhereIF(!string.IsNullOrEmpty(sendKnowledge.createTimeEnd), p => p.CreatDate <= Convert.ToDateTime(sendKnowledge.createTimeEnd))
                          .WhereIF(!string.IsNullOrEmpty(sendKnowledge.keyWord), p => p.KName.Contains(sendKnowledge.keyWord))
                         .OrderByDescending(p => p.CreatDate)
                          .ToListAsync();

                        if (null == listData)
                            apiR = DCJTDeResponse<string>.Failed(null);
                        else
                        {
                            var dto = _mapper.Map<IReadOnlyList<KnowledgeDto>>(listData);
                            // 返回数据
                            apiR = DCJTDeResponse<string>.Succeed(System.Text.Json.JsonSerializer.Serialize(dto), "调用成功");
                        }
                    }
                }
            }
            catch (Exception)
            {
                apiR = DCJTDeResponse<string>.Failed("接口异常");
            }

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

            return OpenResponse.Ok(base64);
        }

        #endregion

        #region send-知识库内容-已完成

        /// <summary>
        /// 查询知识库内容
        /// </summary>
        /// <returns></returns>
        [HttpPost("service/api/dcjt/get_knowledge_content")]
        [AllowAnonymous]
        public async Task<OpenResponse> Get_Knowledge_Content()
        {
            ConfigurationPoliceDCJT configurationPoliceDCJT = new();

            //根据不同地市州获取不同的配置信息
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.ZiGong))
                configurationPoliceDCJT = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;

            string sm4 = configurationPoliceDCJT.token6_sm4_mw;
            var apiR = new DCJTDeResponse<string>();
            try
            {
                // 验证dcsm
                string dcsmMsg = CheckDcsm(Request.Headers["dcsm"].ToString(), configurationPoliceDCJT.token6_dcsm);
                if (!string.IsNullOrEmpty(dcsmMsg))
                    apiR = DCJTDeResponse<string>.Failed(dcsmMsg);
                else
                {
                    string base64String = await GetStreamBase64(HttpContext.Request);

                    SendKnowledgeRequestDto sendKnowledge = new SendKnowledgeRequestDto();
                    if (!string.IsNullOrEmpty(base64String))
                    {
                        // 解密：base64通过sm4解密转json
                        string jsonRes = Sm4Crypto.Decrypt_ECB_Base64(sm4, base64String);
                        if (!string.IsNullOrEmpty(jsonRes))
                            // json 转 实体类
                            sendKnowledge = System.Text.Json.JsonSerializer.Deserialize<SendKnowledgeRequestDto>(jsonRes);

                        await InitRawData("service/api/dcjt/get_knowledge_content", base64String, jsonRes, null);
                    }

                    if (string.IsNullOrEmpty(sendKnowledge.id))
                    {
                        apiR = DCJTDeResponse<string>.Failed("【知识库ID】不能为空");
                    }
                    else
                    {
                        var data = await _dsKnowledgeRawDataRepository.GetAsync(p => p.Id == sendKnowledge.id);
                        if (null == data)
                            apiR = DCJTDeResponse<string>.Failed(null);
                        else
                        {
                            var dto = _mapper.Map<KnowledgeContent>(data);
                            // 返回数据
                            apiR = DCJTDeResponse<string>.Succeed(System.Text.Json.JsonSerializer.Serialize(dto), "调用成功");
                        }
                    }
                }
            }
            catch (Exception)
            {
                apiR = DCJTDeResponse<string>.Failed("接口异常");
            }

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

            return OpenResponse.Ok(base64);
        }

        #endregion

        #region 私有方法

        #region 工单办结

        /// <summary>
        /// 工单办结
        /// </summary>
        /// <param name="policeReceiveChainDealDs"></param>
        /// <returns></returns>
        private async Task InitChainDeal(ChainDeal_DCJT policeReceiveChainDealDs)
        {
            var checkDataDeal = await _dsPoliceSendChainAlarmDcjtRepository.GetAsync(p => p.AlarmReceiptNumber == policeReceiveChainDealDs.AlarmReceiptNumber && p.AlarmReceptionType == "0", HttpContext.RequestAborted);
            if (checkDataDeal is null)
            {
                //写入对外展示表数据
                DsReceiveHandleData dsReceive = new()
                {
                    OrderNo = policeReceiveChainDealDs.AlarmReceiptNumber,
                    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 = checkDataDeal.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 = checkDataDeal.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 = checkDataDeal.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);
            }
            else if (policeReceiveChainDealDs.DisposalType == "4" || policeReceiveChainDealDs.DisposalType == "5")
            {
                //自贡独有业务，目前不需要处理（老系统未处理），4警情签收，5结果签收
            }
        }

        #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,
                PoliceSource = EPoliceSource.DCJT
            };
            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
    }
}
