using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using Google.Protobuf.WellKnownTypes;
using Mall.CacheManager.AppletWeChat;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Pay.WeChatPat;
using Mall.Common.Plugin;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Mall.WeChat.Common;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Libmongocrypt;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Crypto.Generators;
using RabbitMQ.Client.Framing.Impl;

namespace Mall.WebApi.Controllers.AppletWeChat
{


    [Route("api/[controller]/[action]/{MallBaseId?}/{TenantId?}")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class WeChatNotifyController : Controller
    {
        private readonly object _lock = new object();
        private readonly UserCommonModule userCommonModule = new UserCommonModule();
        private readonly Module.MarketingCenter.RechargeModule rechargeModule = new Module.MarketingCenter.RechargeModule();
        private readonly Module.MarketingCenter.CouponModule couponModule = new Module.MarketingCenter.CouponModule();
        private readonly Module.Education.PointModule pointModule = new Module.Education.PointModule();
        private readonly Module.TradePavilion.BuildingCarrierModule buildingCarrierModule = new Module.TradePavilion.BuildingCarrierModule();
        private readonly Module.Education.ActivityModule activityModule = new Module.Education.ActivityModule();
        private readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public WeChatNotifyController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        /// <summary>
        /// 订单支付回调  作废
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string Notify()
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.Notify(_accessor);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];

                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间// Convert.ToDateTime(dic["PayDate"]);

                    #region 新增订单支付信息

                    userCommonModule.InsertOrderPayInfo(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate, 0);


                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }


        /// <summary>
        /// 订单支付回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string AllNotify(int MallBaseId, int TenantId)
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];

                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间// Convert.ToDateTime(dic["PayDate"]);

                    #region 新增订单支付信息

                    userCommonModule.InsertOrderPayInfo(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate, 0);


                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }









        /// <summary>
        /// 会员点数购买回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string PointNotify(int MallBaseId, int TenantId)
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间

                    #region 新增订单支付信息

                    // pointModule.UpdatePointOrder(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate);
                    pointModule.UpdatePointOrder(new Model.Extend.Point.RB_Point_Order_Extend { ID = OrderId, OrderNo = sOrderNo, Income = dPaid, MerchantsNo = TransactionId, PaymentTime = PayDate });

                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }



        /// <summary>
        /// 订单支付回调   作废
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        [HttpPost]
        public string NotifyZhouTian()
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.NotifyZhouTian(_accessor);
            LogHelper.WriteInfo("NotifyZhouTian返回信息进来了");
            if (result.IsSuccess)
            {
                LogHelper.WriteInfo("NotifyZhouTian回调成功：" + result.ToString());
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间// Convert.ToDateTime(dic["PayDate"]);

                    #region 新增订单支付信息
                    LogHelper.WriteInfo("NotifyZhouTian订单信息");
                    userCommonModule.InsertOrderPayInfo(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate, 0);


                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }



        /// <summary>
        /// 会员充值支付回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string RechargeNotify(int MallBaseId, int TenantId)
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间

                    #region 新增订单支付信息

                    rechargeModule.UpdateBalanceRecharge(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate);


                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }



        /// <summary>
        /// 会员购买支付回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string VipBuyNotify(int MallBaseId, int TenantId)
        {
            LogHelper.Write(null, "VipBuyNotify返回信息进来了");
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间

                    #region 修改会员购买支付信息

                    userCommonModule.InsertVipBuyCommission(UserId, OrderId, sOrderNo, dPaid, PayDate);
                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }



        /// <summary>
        /// 会员购买支付回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string MemberBuyNotify(int MallBaseId, int TenantId)
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间

                    #region 修改会员购买支付信息
                    userCommonModule.UpdateMemberBuy(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dPaid, PayDate);
                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }




        /// <summary>
        /// 会员购买储值卡回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string DepositBuyNotify(int MallBaseId, int TenantId)
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间

                    #region 新增订单支付信息

                    couponModule.UpdateDepositBuy(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate);
                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "DepositBuyNotify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }




        /// <summary>
        /// 赞羊教育活动报名支付回调
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public string ActivityNotify(int MallBaseId, int TenantId)
        {
            var req = new RequestHandler();
            App_Code.PayUtil PayUtil = new App_Code.PayUtil();
            var result = PayUtil.AllNotify(_accessor, MallBaseId, TenantId);
            if (result.IsSuccess)
            {
                var dic = ((Dictionary<string, string>)result.Data);
                //开始回写订单状态
                lock (_lock)
                {
                    string sOrderNo = dic["sOrderNo"];//订单号 时间挫+OrderId
                    int OrderId = Convert.ToInt32(sOrderNo[17..]);

                    decimal dPaid = Convert.ToDecimal(dic["dPrice"]) / 100;
                    string sPayerOpenID = dic["sPayerOpenID"];
                    int UserId = Convert.ToInt32(dic["bIsRecharge"]);
                    string TransactionId = dic["sTradeNo"];
                    string PayType = dic["OrderPayType"];
                    DateTime PayDate = DateTime.ParseExact(dic["PayDate"], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);//转换时间

                    #region 修改会员购买支付信息
                    activityModule.UpdateActivityEnroll(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dPaid, PayDate);
                    #endregion
                }
                //告诉微信我们已经处理成功，不需要再调用我们的接口了
                req.SetParameter("return_code", "SUCCESS");
                req.SetParameter("return_msg", "OK");
                var reqXml = req.ParseXml();
                return reqXml;
                //  return ApiResult.Success("", reqXml);
            }
            else
            {
                req.SetParameter("return_code", "FAIL");
                req.SetParameter("return_msg", "订单失败");
                var reqXmlFAIL = req.ParseXml();
                LogHelper.Write(null, "Notify返回信息：" + reqXmlFAIL);
                return reqXmlFAIL;
                // return ApiResult.Failed("", reqXmlFAIL);
            }
        }



        /// <summary>
        /// 微信消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        public string EventMessageCall(int MallBaseId, int TenantId)
        {
            string timestamp = "";
            string nonce = "";
            string echostr = "";
            string signature = "";
            string encrypt_type = "";
            string msg_signature = "";
            string openid = "";
            try
            {
                signature = HttpContext.Request.Query["signature"].ToString();
            }
            catch (Exception ex)
            {
                signature = "";
                LogHelper.Write("signature:" + ex.Message);
            }
            try
            {
                timestamp = HttpContext.Request.Query["timestamp"].ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Write("timestamp:" + ex.Message);
                timestamp = "";
            }
            try
            {
                nonce = HttpContext.Request.Query["nonce"].ToString();
            }
            catch (Exception ex)
            {
                nonce = "";
                LogHelper.WriteInfo("nonce:" + ex.Message);
            }
            try
            {
                encrypt_type = HttpContext.Request.Query["encrypt_type"].ToString();
            }
            catch (Exception ex)
            {
                encrypt_type = "";
                LogHelper.WriteInfo("encrypt_type:" + ex.Message);
            }
            try
            {
                msg_signature = HttpContext.Request.Query["msg_signature"].ToString();
            }
            catch (Exception ex)
            {
                msg_signature = "";
                LogHelper.WriteInfo("msg_signature" + ex.Message);
            }
            try
            {
                openid = HttpContext.Request.Query["openid"].ToString();
            }
            catch (Exception ex)
            {
                openid = "";
                LogHelper.WriteInfo("openid:" + ex.Message);
            }

            LogHelper.WriteInfo($"我进来了参数如下[MallBaseId:" + MallBaseId + "，" +
                "TenantId：" + TenantId + "，signature：" + signature + "，echostr：" + echostr + "，timestamp：" + timestamp + "，nonce：" + nonce + "，openid：" + openid + "，encrypt_type：" + encrypt_type + "，msg_signature：" + msg_signature);
            var req = new RequestHandler();
            try
            {
                var request = _accessor.HttpContext.Request;
                if (request.Method == "GET")
                {
                    try
                    {
                        echostr = HttpContext.Request.Query["echostr"].ToString();
                    }
                    catch (Exception ex)
                    {
                        echostr = "";
                        LogHelper.WriteInfo("echostr:::" + ex.Message);
                    }
                    return echostr ?? "echostr is null";
                }
                else
                {
                    var str = new StreamReader(request.Body);
                    string postStr = str.ReadToEnd();
                    lock (_lock)
                    {
                        if (!string.IsNullOrWhiteSpace(postStr))
                        {
                            WechatMessage wx = WXBizMsgCrypt.GetWxMessage(postStr, timestamp, nonce, signature, encrypt_type, msg_signature, openid);
                            if (!string.IsNullOrWhiteSpace(wx.PagePath) && wx.MsgType == "miniprogrampage")// 卡片消息发送联系人信息
                            {
                                var parameters = GetQueryParameters(wx.PagePath);

                                int id = 0;
                                if (parameters != null && parameters.Any())
                                {
                                    foreach (System.Text.RegularExpressions.Match m in parameters)
                                    {
                                        if (m.Result("$2").Equals("id"))
                                        {
                                            try
                                            {
                                                id = Convert.ToInt32(m.Result("$3"));
                                            }
                                            catch (Exception ex)
                                            {
                                                id = 0;
                                            }
                                        }
                                    }

                                }

                                if (id > 0)
                                {
                                    bool sendMsg = false;
                                    string contactName = "";
                                    string contactPhone = "";
                                    if (wx.PagePath.Contains("pages/kotra/carrier/detail_building"))//楼宇
                                    {
                                        var model = buildingCarrierModule.GetBuildingInfoModule(id);
                                        contactName = model?.ContactName??"";
                                        contactPhone = model?.ContactPhone??"";
                                        sendMsg = true;
                                    }
                                    else if (wx.PagePath.Contains("pages/kotra/carrier/detail_carrier"))//载体
                                    {
                                        var model = buildingCarrierModule.GetBuildingCarrierModule(id);
                                        contactName = model?.ContactName ?? "";
                                        contactPhone = model?.ContactPhone ?? "";
                                        sendMsg = true;
                                    }
                                    else if (wx.PagePath.Contains("pages/kotra/brand/detail_brand"))//品牌
                                    {
                                        var model = buildingCarrierModule.GetBrandEnterpriseModule(id);
                                        contactName = model?.ContactName ?? "";
                                        contactPhone = model?.ContactPhone ?? "";
                                        sendMsg = true;
                                    }
                                    else if (wx.PagePath.Contains("pages/kotra/brand/detail_company"))//企业
                                    {
                                        var model = buildingCarrierModule.GetEnterpriseServicesInfoModule(id);
                                        contactName = model?.ContactName ?? "";
                                        contactPhone = model?.ContactPhone ?? "";
                                        sendMsg = true;
                                    }
                                    if (sendMsg)
                                    {
                                        RB_MiniProgram_Extend modelMiniProgram = new RB_MiniProgram_Extend();
                                        modelMiniProgram = activityModule.GetMiniProgramExtend(MallBaseId);
                                        string token = WeiXinReidsCache.Get(modelMiniProgram.MiniAppId);
                                        if (string.IsNullOrEmpty(token))
                                        {
                                            token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, modelMiniProgram.MiniAppId, modelMiniProgram.MiniAppSecret);
                                            System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(modelMiniProgram.MiniAppId, token));
                                        }
                                        if (string.IsNullOrEmpty(token))
                                        {
                                            return "";
                                        }
                                        string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token;
                                        string contetnStr = "";
                                        if (string.IsNullOrWhiteSpace(contactName) && String.IsNullOrWhiteSpace(contactPhone))
                                        {
                                            contetnStr = "暂无相关主体联系人信息";
                                        }
                                        else
                                        {
                                            contetnStr = "联系人：" + contactName + "\n" + "联系电话：" + contactPhone;
                                        }
                                        var obj = new
                                        {
                                            touser = wx.FromUserName,
                                            msgtype = "text",
                                            text = new { content = contetnStr },
                                        };
                                        string result = Common.Plugin.HttpHelper.HttpPostStr(url, JsonHelper.Serialize(obj));
                                       // LogHelper.WriteInfo("发送消息返回信息：" + result);
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteInfo(ex.ToString());
            }
            return echostr ?? "echostr is null";
        }


        private static MatchCollection GetQueryParameters(string url)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", System.Text.RegularExpressions.RegexOptions.Compiled);
            System.Text.RegularExpressions.MatchCollection mc = re.Matches(url);
            return mc;
        }
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        public static string ReceivedText(string FromUserName, string ToUserName, string Content)
        {
            string textpl = string.Empty;
            textpl = "<xml>" +
                     "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>" +
                     "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>" +
                     "<CreateTime>" + (int)(DateTime.Now - DateTime.Parse("1970-1-1")).TotalSeconds + "</CreateTime>" +
                     "<MsgType><![CDATA[text]]></MsgType>" +
                     "<Content><![CDATA[" + Content + "]]></Content>" +
                     "<MsgId>" + (int)(DateTime.Now - DateTime.Parse("1970-1-1")).TotalSeconds + "</MsgId>" +
                     "</xml>";
            return textpl;
        }
    }
}