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;

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();
        #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 ((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()
                    //(model.MallBaseId==6&&model.TenantId==16)? "https://mallapi.oytour.com/api/WeChatNotify/NotifyZhouTian" : 
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, demodel.GoodsName, model.Income.Value, 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("请选择您需要购买的会员等级");
            }
            //查询用户的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, Grade = demodel.GradeId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                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);
        }

        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, demodel.OrderNo, "s1111111111111", Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "test", (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("");
        }
        #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 }).FirstOrDefault();
                if (rechargeRulesModel == null)
                {
                    return ApiResult.Failed("选择的储值卡不存在");
                }
                if (demodel.SalePrice != Convert.ToDecimal(rechargeRulesModel.SalePrice))
                {
                    return ApiResult.Failed("支付金额与设定的金额不符");
                }
                demodel.DepositPrice = 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;
            //新增充值记录
            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.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
    }
}