using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Pay.WeChatPat;
using Mall.Common.Pay.WeChatPat.Model;
using Mall.Common.Plugin;
using Mall.Model.Entity.Point;
using Mall.Model.Entity.User;
using Mall.Model.Extend.Point;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.Education;
using Mall.Module.MarketingCenter;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Mall.WeChat.Helper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client.Framing.Impl;

namespace Mall.WebApi.Controllers.AppletWeChat
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class WeChatPayController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public WeChatPayController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        /// <summary>
        /// 商户小程序处理类
        /// </summary>
        private readonly MiniProgramModule programModule = new MiniProgramModule();
        private readonly UserModule userModule = new UserModule();
        private readonly RechargeModule rechargeModule = new RechargeModule();
        private readonly UserVipModule userVipModule = new UserVipModule();
        private readonly PointModule pointModule = new PointModule();
        private readonly UserCommonModule userCommonModule = new UserCommonModule();
        private readonly CouponModule couponModule = new CouponModule();
        private readonly ActivityModule activityModule = new ActivityModule();

        #region 商品支付
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.OrderPayType.HasValue)
            {
                return ApiResult.Failed("请选择支付方式！");
            }
            var model = new Module.Product.OrderModule().GetOrderInfo(demodel.OrderId);
            if (model == null)
            {
                return ApiResult.Failed("订单信息不存在！");
            }

            if (model.OrderStatus == Common.Enum.Goods.OrderStatusEnum.Cancel)
            {
                return ApiResult.Failed("订单已取消");
            }
            if (model.MallBaseId == 19)//支付定金金额
            {
                if ((model?.Income ?? 0) <= (model?.PayIncome ?? 0))
                {
                    return ApiResult.Failed("订单已支付");
                }
            }
            else
            {
                if ((int)model.OrderStatus > 1)
                {
                    return ApiResult.Failed("订单已支付");

                }
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + model.OrderId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.OrderPayType)
            {
                case 1://微信支付     _accessor.HttpContext.Connection.RemoteIpAddress.ToString()

                    decimal payIncome = (model.Income.Value) - (model?.PayIncome ?? 0);//实际应付金额-已支付金额
                    if (model.TenantId == 29 && (model?.PayIncome ?? 0) == 0)//支付定金金额
                    {
                        var modelDetailList = new Module.Product.OrderModule().GetOrderDetailList(new RB_Goods_OrderDetail_Extend { OrderId = model.OrderId, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                        decimal depositMoney = modelDetailList.Where(x => x.DepositRatio > 0).Sum(x => (1 - (x.DepositRatio / 100)) * (x.Final_Price ?? 0));
                        payIncome = payIncome - depositMoney;//最终应付金额-定金-退款
                    }
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, demodel.GoodsName, payIncome, model.UserId.ToString(), demodel.OpenId, (Config.sTenpayNotify + "/" + model.MallBaseId + "/" + model.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }
        #endregion

        #region 余额充值
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRechargePayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Member_BalanceRecharge demodel = JsonConvert.DeserializeObject<RB_Member_BalanceRecharge>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (!demodel.Balance.HasValue)
            {
                return ApiResult.Failed("请输入充值金额");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "余额充值";
            var rechargeRulesModel = rechargeModule.GetRechargeRulesList(new Model.Extend.MarketingCenter.RB_Recharge_Rules_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, ID = demodel.RechargeRulesId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("选择的充值规则不存在");
            }
            if (demodel.RechargeRulesId > 0)
            {
                if (demodel.Balance.Value != Convert.ToDecimal(rechargeRulesModel.Money))
                {
                    return ApiResult.Failed("充值金额与设定的金额不符");
                }
                demodel.GiveIntegral = rechargeRulesModel.GiveIntegral;
                demodel.GiveMoney = rechargeRulesModel.GiveMoney;
                demodel.RechargeRulesId = rechargeRulesModel.ID;
            }
            else
            { //自定义
                var rechareSettings = rechargeModule.GetRechargeSettingsList(new Model.Entity.MarketingCenter.RB_Recharge_Settings { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId }).FirstOrDefault();

                if (rechareSettings.IsExploitMoney == 0)
                {
                    return ApiResult.Failed("暂未开启自定义金额");
                }
            }

            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.RechargeType = 1;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            //新增充值记录
            int rechargeId = rechargeModule.AddBalanceRecharge(demodel);
            if (rechargeId == 0)
            {
                return ApiResult.Failed("在线充值失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + rechargeId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(rechargeRulesModel.Money), userInfo.UserId.ToString(), userModel.OpenId, (Config.sTenpayRechargeNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }
        #endregion

        #region 点数充值（教育线上约课）
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPointPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Point_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Order_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (!demodel.Income.HasValue)
            {
                return ApiResult.Failed("请传入点数购买金额");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "购买点数";
            var rechargeRulesModel = pointModule.GetPointGoodsList(new Model.Extend.Point.RB_Point_Goods_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, ID = demodel.PointGoodsId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("选择的点数产品不存在");
            }
            if (demodel.PointGoodsId > 0)
            {
                if (demodel.Income.Value != Convert.ToDecimal(rechargeRulesModel.SellingPrice.Value))
                {
                    return ApiResult.Failed("购买点数金额与设定的金额不符");
                }
                demodel.PonitNum = rechargeRulesModel.PonitNum;
                demodel.OldPonitNum = userModel.PointNum;
                demodel.GivePoint = rechargeRulesModel.GivePoint;
            }
            else
            {
                return ApiResult.Failed("点数产品不存在");
            }

            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.State = 0;
            demodel.CreateDate = System.DateTime.Now;
            demodel.PaymentWay = Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment;
            demodel.OrderStatus = 1;
            demodel.VersionSource = 1;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.OrderSource = userModel.Source;
            //新增充值记录
            int rechargeId = pointModule.SetPointOrder(demodel);
            if (rechargeId == 0)
            {
                return ApiResult.Failed("购买点数失败");
            }
            string sOrderNo = (DateTime.Now.ToString("yyyyMMddHHmmssfff")) + rechargeId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(demodel.Income), userInfo.UserId.ToString(), userModel.OpenId, (Config.sTenpayPointNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }
        #endregion

        #region 会员购买

        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult GetMemberBuyPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Member_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Buy_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (!demodel.GradeId.HasValue)
            {
                return ApiResult.Failed("请选择您需要购买的会员等级");
            }
            if (demodel.GradeId.Value == 0)
            {
                return ApiResult.Failed("请选择您需要购买的会员等级");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "会员等级购买";

            var rechargeRulesModel = userModule.GetMemberGradeList(new RB_Member_Grade_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = demodel.GradeId ?? 0 }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("您选择的会员等级不存在");
            }
            if (userModel.MemberGrade != 0)
            {
                return ApiResult.Failed("只有普通会员可以购买会员等级");

            }
            //if (userModel.MemberGrade >= rechargeRulesModel.Grade)
            //{
            //    return ApiResult.Failed("购买会员等级低于您当前会员等级");
            //}
            if (rechargeRulesModel.IsMemberBuy == 1)
            {
                if (rechargeRulesModel.MemberBuyMoney != demodel.Money)
                {
                    return ApiResult.Failed("会员购买支付金额有误，请稍后重试");
                }
                demodel.GradeName = rechargeRulesModel.Name;
            }
            else
            {
                return ApiResult.Failed("当前会员等级不能购买");
            }
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.PayState = 0;
            demodel.Status = 0;
            demodel.OrderSource = Common.Enum.User.UserSourceEnum.WeiXin;
            demodel.CreateDate = DateTime.Now;
            //新增充值记录
            int memberBuyId = userModule.AddMemberBuy(demodel);
            if (memberBuyId == 0)
            {
                return ApiResult.Failed("购买会员失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + memberBuyId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(rechargeRulesModel.MemberBuyMoney), userInfo.UserId.ToString(), userModel.OpenId, (Config.sTenpayMemberBuyNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }

        #endregion

        #region 会员vip购买
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult GetVIPBuyPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Vip_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Vip_Buy_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (demodel.PayWay == 0)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (demodel.GradeId == 0)
            {
                return ApiResult.Failed("请选择您需要购买的会员等级");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }

            //获取会员的分享商记录
            var distributorModel = userModule.GetDistributorInfoList(new RB_Distributor_Info_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, UserId = userModel.Id }).FirstOrDefault();

            if (distributorModel == null)
            {
                return ApiResult.Failed("请先申请成为分销商");
            }
            string payGoodsName = "VIP会员购买";
            var rechargeRulesModel = userModule.GetFXDistributorGradeList(new RB_Distributor_FXGrade_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = demodel.GradeId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("您选择的VIP等级不存在");
            }

            if (distributorModel.Grade > rechargeRulesModel.Grade)
            {
                return ApiResult.Failed("购买VIP等级低于您当前VIP等级");
            }
            if (rechargeRulesModel.IsCanBuy == 1)
            {
                if (rechargeRulesModel.BuyMoney != demodel.Money)
                {
                    return ApiResult.Failed("VIP购买支付金额有误，请稍后重试");
                }
                demodel.GradeName = rechargeRulesModel.GradeName;
            }
            else
            {
                return ApiResult.Failed("当前VIP等级不能购买");
            }

            //判断订单状态是否是待支付 
            var buyList = userVipModule.GetVipBuyList(new RB_Vip_Buy_Extend { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            if (buyList.Where(x => x.PayState == 1).Count() == 0)
            {
                demodel.Remark = "购买";
            }
            else
            {
                demodel.Remark = "续费";
            }
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.PayState = 0;
            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.ExpiryDate = Convert.ToDateTime(DateTime.Now.AddYears(rechargeRulesModel.Year ?? 1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
            //新增充值记录
            int memberBuyId = userVipModule.AddVipBuy(demodel);
            if (memberBuyId == 0)
            {
                return ApiResult.Failed("购买VIP等级失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + memberBuyId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(rechargeRulesModel.BuyMoney), userInfo.UserId.ToString(), userModel.OpenId, (Config.sTenpayVipBuyNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }
        #endregion

        #region 测试接口


        public ApiResult TestReturn()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wx1bf3a7c76b10bb6d", WeChatApiSecret = "1e54ed9de09f99d87970aaf798cbc936", WeChatPayMerchants = "1554826431" };
            string RefundOrderNo = "2020052916044326411";
            var pram = new Common.Pay.WeChatPat.PayParam()
            {
                TotalFee = Convert.ToInt32(0.01 * 100),
                RefundFee = Convert.ToInt32(0.01 * 100),
                OrderNumber = "202005291604432641",
                RefundNumber = RefundOrderNo
            };
            var Robj = new App_Code.PayUtil().Refund(pram, miniProgram, _accessor);
            return ApiResult.Success("", Robj);
        }

        //public ApiResult TestSendEducationDynamicMsg()
        //{
        //    List<string> openIds = new List<string>();
        //    openIds.Add("oshxs5I-6uR1J91Rs3QVyi2rJIm4");
        //    openIds.Add("oshxs5I-6uR1J91Rs3QVyi2rJIm4");
        //    new MiniProgramMsgModule().SendEducationDynamicMsg(15,5, openIds, "您关注的老师发布又有新动态了", "李琴",System.DateTime.Now.ToString("yyyy年MM月dd日"));
        //    return ApiResult.Success("");
        //}


        public ApiResult TestWeChatPay()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wxacd9f8cc3480d29e", WeChatApiSecret = "936110e2c2214340b9829a3608bde6b0", WeChatPayMerchants = "1562277941" }; // programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = 1, TenantId =1 });
            string RefundOrderNo = "2020052916044326411";
            var pram = new Common.Pay.WeChatPat.PayParam()
            {
                TotalFee = Convert.ToInt32(0.01 * 100),
                RefundFee = Convert.ToInt32(0.01 * 100),
                OrderNumber = "202005291604432641",
                RefundNumber = RefundOrderNo
            };
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + "1001";
            App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, "测试", Convert.ToDecimal(0.05), "1", "", Config.sTenpayNotify, miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
            return ApiResult.Success("");
        }


        public ApiResult TestTransfersOrder()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wxacd9f8cc3480d29e", WeChatApiSecret = "936110e2c2214340b9829a3608bde6b0", WeChatPayMerchants = "1562277941" };
            string RefundOrderNo = "20200529160443264111";
            var Robj = App_Code.PayUtil.GetTransfersOrder(RefundOrderNo, Convert.ToDecimal("0.01"), "21233", "ow_7I5XC1-RGwwk8QANBmWKYKmOc", miniProgram, _accessor); ;
            return ApiResult.Success("", Robj);
        }


        public ApiResult TestNativeOrder()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wxacd9f8cc3480d29e", WeChatApiSecret = "936110e2c2214340b9829a3608bde6b0", WeChatPayMerchants = "1562277941" }; // programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = 1, TenantId =1 });
            string RefundOrderNo = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");

            var Robj = App_Code.PayUtil.GetNativeOrder(RefundOrderNo, Convert.ToDecimal("0.01"), "测试商品", "21233", miniProgram, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString(), _accessor); ;
            return ApiResult.Success("", Robj);
        }



        public ApiResult TestVIPBuyPayOrder()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string orderNo = parms.GetStringValue("orderNo");
            int orderId = parms.GetInt("orderId");
            int userId = parms.GetInt("userId");
            var Robj = userCommonModule.InsertVipBuyCommission(userId, orderId, orderNo, Convert.ToDecimal(365.00), System.DateTime.Now);
            return ApiResult.Success("", Robj);
        }
        /// <summary>
        /// 测试接口调用支付成功
        /// </summary>
        /// <returns></returns>
        public ApiResult InsertOrderPayInfo()
        {
            var request = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(request.msg.ToString());
            userCommonModule.InsertOrderPayInfo(demodel.UserId ?? 0, demodel.OrderId, (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + demodel.OrderId, demodel.MerchantsNo, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, demodel.StoreName, (demodel.Income ?? 0), System.DateTime.Now, 0);
            return ApiResult.Success("");
        }

        public ApiResult TestUpdatePointOrder()
        {
            var request = RequestParm;
            RB_Point_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Order_Extend>(request.msg.ToString());
            pointModule.UpdatePointOrder(demodel);
            return ApiResult.Success("");
        }

        public ApiResult UpdateDepositBuy()
        {
            var request = RequestParm;
            RB_Member_DepositBuy demodel = JsonConvert.DeserializeObject<RB_Member_DepositBuy>(request.msg.ToString());
            couponModule.UpdateDepositBuy(demodel.UserId ?? 0, demodel.Id, demodel.OrderNo, demodel.Out_Trade_No, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", demodel.SalePrice, System.DateTime.Now);
            // couponModule.UpdateDepositBuy(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate);
            return ApiResult.Success("");
        }


        public ApiResult UpdateActivityEnroll()
        {
            var request = RequestParm;
            Model.Extend.Education.RB_Education_Consult_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.Education.RB_Education_Consult_Extend>(request.msg.ToString());
            activityModule.UpdateActivityEnroll(demodel.UserId, demodel.Id, demodel.OrderNo, demodel.MerchantsNo, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, demodel.Money, System.DateTime.Now);
            // couponModule.UpdateDepositBuy(UserId, OrderId, sOrderNo, TransactionId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, PayType, dPaid, PayDate);
            return ApiResult.Success("");
        }




        public ApiResult UpdateMemberBuy()
        {
            var request = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(request.msg.ToString());
            userCommonModule.UpdateMemberBuy(demodel.UserId ?? 0, demodel.OrderId, demodel.OrderNo, "s1111111111111", Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, (demodel.Income ?? 0), System.DateTime.Now);
            return ApiResult.Success("");
        }
        public ApiResult UpdatePointOrder()
        {
            var request = RequestParm;
            RB_Point_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Order_Extend>(request.msg.ToString());
            pointModule.UpdatePointOrder(demodel);
            return ApiResult.Success("");
        }
        #endregion

        #region 星星充值（相亲）
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStarsPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Point_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Point_Order_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (!demodel.Income.HasValue)
            {
                return ApiResult.Failed("请传入星星购买金额");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "购买星星";
            var rechargeRulesModel = pointModule.GetPointGoodsList(new Model.Extend.Point.RB_Point_Goods_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, ID = demodel.PointGoodsId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("选择的星星产品不存在");
            }
            if (demodel.PointGoodsId > 0)
            {
                if (demodel.Income.Value != Convert.ToDecimal(rechargeRulesModel.SellingPrice.Value))
                {
                    return ApiResult.Failed("购买星星金额与设定的金额不符");
                }
                demodel.PonitNum = rechargeRulesModel.PonitNum;
                demodel.OldPonitNum = userModel.PointNum;
                demodel.GivePoint = rechargeRulesModel.GivePoint;
            }
            else
            {
                return ApiResult.Failed("星星产品不存在");
            }

            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.State = 0;
            demodel.CreateDate = System.DateTime.Now;
            demodel.PaymentWay = Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment;
            demodel.OrderStatus = 1;
            demodel.VersionSource = 2;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.OrderSource = userModel.Source;
            //新增充值记录
            int rechargeId = pointModule.SetPointOrder(demodel);
            if (rechargeId == 0)
            {
                return ApiResult.Failed("购买星星失败");
            }
            string sOrderNo = (DateTime.Now.ToString("yyyyMMddHHmmssfff")) + rechargeId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(demodel.Income), userInfo.UserId.ToString(), userModel.OpenId, (Config.sTenpayPointNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }
        #endregion

        #region 储值卡购买（赞羊）
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDepositPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Member_DepositBuy demodel = JsonConvert.DeserializeObject<RB_Member_DepositBuy>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (demodel.SalePrice <= 0)
            {
                return ApiResult.Failed("请输入购买金额");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "储值卡购买";

            if (demodel.DepositId > 0)
            {
                var rechargeRulesModel = couponModule.GetDepositList(new Model.Extend.MarketingCenter.RB_Deposit_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, ID = demodel.DepositId, PickupCenter = 1 }).FirstOrDefault();
                if (rechargeRulesModel == null)
                {
                    return ApiResult.Failed("选择的储值卡不存在");
                }
                if (demodel.SalePrice != Convert.ToDecimal(rechargeRulesModel.SalePrice))
                {
                    return ApiResult.Failed("支付金额与设定的金额不符");
                }
                demodel.DepositPrice = rechargeRulesModel.DepositPrice;
                demodel.SurplusPrice = rechargeRulesModel.DepositPrice;
                demodel.Name = rechargeRulesModel.Name;
                demodel.CouponIco = rechargeRulesModel.CouponIco;
                demodel.IndateDay = rechargeRulesModel.IndateDay;
                demodel.DepositId = rechargeRulesModel.ID;
            }
            else
            {
                return ApiResult.Failed("选择的储值卡不存在");
            }

            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.RechargeType = 1;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.Status = 0;
            demodel.SendStatus = 0;
            demodel.OrderSource = userModel.Source;
            //新增充值记录
            int rechargeId = couponModule.AddDepositBuy(demodel);
            if (rechargeId == 0)
            {
                return ApiResult.Failed("在线购买储值卡失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + rechargeId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(demodel.SalePrice), userInfo.UserId.ToString(), userModel.OpenId, (Config.sTenpayDepositNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }

        #endregion


        #region 赞羊教育活动报名
        //GetMemberUserInfo

        /// <summary>
        /// 活动报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public ApiResult SetActivityEnrollInfo()
        {
            bool flag = false;
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            Model.Extend.Education.RB_Education_Consult_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.Education.RB_Education_Consult_Extend>(request.msg.ToString());
            var model = activityModule.GetActivityModule(demodel.ActivityId);
            var list = activityModule.GetCommerceConsultListRepository(new Model.Extend.Education.RB_Education_Consult_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, ActivityId = demodel.ActivityId, EnrollState = 1, UserId = userInfo.UserId, OrderStatus = 1 });
            if (list.Any()) { return ApiResult.Failed("已存在报名信息"); }

            if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return ApiResult.Failed("活动不存在"); }
            if (model.SignStartTime >= DateTime.Now)
            {
                return ApiResult.Failed("报名还未开始，无法报名");
            }
            if (model.SignEndTime <= DateTime.Now)
            {
                return ApiResult.Failed("已过了报名时间，无法报名");
            }

            var bmodel = activityModule.GetEducationBaseInfo(new Model.Extend.Education.RB_Education_BaseInfo_Extend() { MallBaseId = model.MallBaseId, TenantId = model.TenantId, UserId = userInfo.UserId }).FirstOrDefault();

            if (model.Distinguish == 0)
            {
                if (bmodel == null || bmodel.Sex == 0)
                {
                    return ApiResult.Failed("您的性别保密，无法报名");
                }
                if (bmodel.Sex == 1)
                {
                    int ManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 1);
                    if (model.ManNum <= ManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
                }
                else if (bmodel.Sex == 2)
                {
                    int WoManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 2);
                    if (model.WoManNum <= WoManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
                }
                else
                {
                    return ApiResult.Failed("性别未维护，无法报名");
                }
            }
            else
            {
                int ManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 0);
                if (model.ManNum <= ManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
            }
            if (model.AgeLimit == 0)
            {
                if (bmodel == null || string.IsNullOrWhiteSpace(bmodel.Birthday))
                {
                    return ApiResult.Failed("您未绑定学员信息无法获取到年龄，无法报名");
                }
                int Age = Convert.ToInt32(Common.Plugin.StringHelper.GetAge(bmodel.Birthday));
                if (model.StartAge > 0 && model.EndAge > 0)
                {
                    if (Age < model.StartAge || Age > model.EndAge)
                    {
                        return ApiResult.Failed($"年龄限制在{model.StartAge}-{model.EndAge}岁，无法报名");
                    }
                }
                else if (model.StartAge > 0 && model.EndAge == 0)
                {
                    if (Age < model.StartAge)
                    {
                        return ApiResult.Failed($"年龄必须大于{model.StartAge}岁，无法报名");
                    }
                }
                else if (model.StartAge == 0 && model.EndAge > 0)
                {
                    if (Age > model.EndAge)
                    {
                        return ApiResult.Failed($"年龄必须小于{model.EndAge}岁，无法报名");
                    }

                }
            }
            if (model.LnsideLimit == 1)
            {
                if (bmodel == null || bmodel.StudentId == 0)
                {
                    return ApiResult.Failed("您未绑定学员信息，无法报名");
                }
            }
            demodel.Sex = bmodel?.Sex ?? 0;
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.Status = 0;
            demodel.IsCancelConfirm = model.IsCancelConfirm;
            demodel.CreateTime = System.DateTime.Now;
            demodel.EduStudentId = (bmodel != null && bmodel.Id > 0) ? bmodel.StudentId : 0;
            demodel.IsCommission = 1;
            demodel.IsRollCall = 1;
            demodel.WeiXinType = 0;
            var umodel = userModule.GetMemberUserInfo(demodel.UserId);
            demodel.OrderSource = umodel.Source;
            //判断当前人的点数
            if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.PayPoint)
            {
                if (umodel == null || umodel.Id == 0)
                {
                    return ApiResult.Failed("用户信息不存在");
                }
                if (model.PointNum == demodel.TotalPoint)
                {
                    if (umodel.PointNum < model.PointNum)
                    {
                        return ApiResult.Failed("您的点数不足，请充值后再试");
                    }
                }
                else
                {
                    return ApiResult.Failed("支付点数不正确");
                }
                demodel.PaymentTime = System.DateTime.Now;
                demodel.OrderStatus = 1;
                flag = activityModule.SetActivityEnrollInfo(demodel, umodel) > 0;

                return flag ? ApiResult.Success("报名成功") : ApiResult.Failed("出错了，请联系管理员");
            }
            else if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment)
            {
                string sPayInfo = string.Empty;
                if (!demodel.PayWay.HasValue)
                {
                    return ApiResult.Failed("请选择支付方式");
                }

                if (model.Price != demodel.Money)
                {
                    return ApiResult.Failed("支付金额不正确");
                }
                demodel.OrderStatus = 0;
                int id = activityModule.SetActivityEnrollInfo(demodel, umodel);
                if (id == 0)
                {
                    return ApiResult.Failed("出错了，请联系管理员");
                }
                string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + id;
                //根据订单号获取微信支付配置信息
                RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
                miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
                App_Code.PayUtil payUtil = new App_Code.PayUtil();
                switch ((int)demodel.PayWay)
                {
                    case 1://微信支付     
                        sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, (model.ActivityName.Length > 50 ? model.ActivityName.Substring(0, 50) : model.ActivityName), Convert.ToDecimal(demodel.Money), userInfo.UserId.ToString(), umodel.OpenId, (Config.sTenpayActivityNotify + "/" + demodel.MallBaseId + "/" + demodel.TenantId), miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                        break;
                    default:
                        break;
                }
                return ApiResult.Success("", sPayInfo);
            }
            return ApiResult.Failed("支付方式错误");
        }

        #endregion

        #region 甲小鹤活动报名


        /// <summary>
        /// 活动报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        [HttpPost]
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        public ApiResult SetActivityEnrollInfoJXH()
        {
            bool flag;
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                userInfo = new AppletUserInfo
                {
                    UserId = RequestParm.UserId,
                    MallBaseId = RequestParm.MallBaseId,
                    TenantId = RequestParm.TenantId,
                    EduStudentId = RequestParm.EduStudentId
                };
            }
            Model.Extend.Education.RB_Education_Consult_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.Education.RB_Education_Consult_Extend>(request.msg.ToString());
            demodel.EduStudentId = userInfo.EduStudentId;
            var model = activityModule.GetActivityModule(demodel.ActivityId);
            var list = activityModule.GetCommerceConsultListRepository(new Model.Extend.Education.RB_Education_Consult_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, ActivityId = demodel.ActivityId, EnrollState = 1, EduStudentId = userInfo.EduStudentId, OrderStatus = 1 });
            if (list.Any()) { return ApiResult.Failed("已存在报名信息"); }

            if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return ApiResult.Failed("活动不存在"); }
            if (model.SignStartTime >= DateTime.Now)
            {
                return ApiResult.Failed("报名还未开始，无法报名");
            }
            if (model.SignEndTime <= DateTime.Now)
            {
                return ApiResult.Failed("已过了报名时间，无法报名");
            }

            var bmodel = activityModule.GetEducationBaseInfo(new Model.Extend.Education.RB_Education_BaseInfo_Extend() { MallBaseId = model.MallBaseId, TenantId = model.TenantId, UserId = userInfo.UserId }).FirstOrDefault();

            if (model.Distinguish == 0)
            {
                if (demodel.Sex == 0)
                {
                    return ApiResult.Failed("您的性别保密，无法报名");
                }
                if (demodel.Sex == 1)
                {
                    int ManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 1);
                    if (model.ManNum <= ManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
                }
                else if (demodel.Sex == 2)
                {
                    int WoManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 2);
                    if (model.WoManNum <= WoManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
                }
                else
                {
                    return ApiResult.Failed("性别未维护，无法报名");
                }
            }
            else
            {
                int ManPeopleNum = activityModule.GetActivityEnrollNum(demodel.ActivityId, 0);
                if (model.ManNum <= ManPeopleNum) { return ApiResult.Failed("已报满，无法报名"); }
            }
            if (model.AgeLimit == 0)
            {
                if (string.IsNullOrWhiteSpace(demodel.StuBirth))
                {
                    return ApiResult.Failed("您未绑定学员信息无法获取到年龄，无法报名");
                }
                int Age = Convert.ToInt32(Common.Plugin.StringHelper.GetAge(demodel.StuBirth));
                if (model.StartAge > 0 && model.EndAge > 0)
                {
                    if (Age < model.StartAge || Age > model.EndAge)
                    {
                        return ApiResult.Failed($"年龄限制在{model.StartAge}-{model.EndAge}岁，无法报名");
                    }
                }
                else if (model.StartAge > 0 && model.EndAge == 0)
                {
                    if (Age < model.StartAge)
                    {
                        return ApiResult.Failed($"年龄必须大于{model.StartAge}岁，无法报名");
                    }
                }
                else if (model.StartAge == 0 && model.EndAge > 0)
                {
                    if (Age > model.EndAge)
                    {
                        return ApiResult.Failed($"年龄必须小于{model.EndAge}岁，无法报名");
                    }

                }
            }

            demodel.Sex = bmodel?.Sex ?? 0;
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.Status = 0;
            demodel.IsCancelConfirm = model.IsCancelConfirm;
            demodel.CreateTime = System.DateTime.Now;
            demodel.IsCommission = 1;
            demodel.IsRollCall = 1;
            demodel.WeiXinType = 1;
            var umodel = userModule.GetMemberUserInfo(demodel.UserId);
            demodel.OrderSource = umodel.Source;
            //判断当前人的点数
            if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.PayPoint)
            {
                if (umodel == null || umodel.Id == 0)
                {
                    return ApiResult.Failed("用户信息不存在");
                }
                if (model.PointNum == demodel.TotalPoint)
                {
                    if (umodel.PointNum < model.PointNum)
                    {
                        return ApiResult.Failed("您的点数不足，请充值后再试");
                    }
                }
                else
                {
                    return ApiResult.Failed("支付点数不正确");
                }
                demodel.PaymentTime = System.DateTime.Now;
                demodel.OrderStatus = 1;
                flag = activityModule.SetActivityEnrollInfo(demodel, umodel) > 0;

                return flag ? ApiResult.Success("报名成功") : ApiResult.Failed("出错了，请联系管理员");
            }
            else if (demodel.PaymentWay == Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment)
            {
                return ApiResult.Failed("您暂时在线支付");
            }
            return ApiResult.Failed("支付方式错误");
        }
        #endregion
    }
}