using jiouosdp.Controllers;
using RFrameGenerate.BLL;
using RFrameGenerate.BLL.Marketing;
using RFrameGenerate.BLL.Recharge;
using RFrameGenerate.Common;
using RFrameGenerate.Model.PageModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Wechat;

namespace jiouosdp.Areas.Online.Controllers
{
    [PF(IsPermissionFilter = false)]
    [LF(IsLoginFilter = false, IsMaintenance = false)]
    public class WeiXinPayController : Controller
    {
        #region 所有支付必须调用该方法,使用参考Paying
        /// <summary>
        /// 所有支付必须调用该方法,使用参考Paying
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string RedirectPayingUrl(string orderNo, string action, string userid = "", string appid = "")
        {
            if (string.IsNullOrEmpty(userid) != true)
            {
                ViewBag.userid = userid;
                HeadPay.Login(userid, appid);
            }
            else
            {
                ViewBag.userid = "";
            }

            if (string.IsNullOrEmpty(userid) == true && HeadPay.IsPay(RFrameGenerate.Common.CurrentManage.MerchantGuid) != true)
            {
                return weixinopen.WeiXinOpenConfig.webdomain.Replace("http://appid.shop", string.Format("http://{0}.shop", HeadPay.GetPayUserID(CurrentManage.MerchantUserID))) + "Online/WeiXinPay/" + action + "?orderNo=" + orderNo + "&userid=" + CurrentManage.MerchantUserID + "&appid=" + CurrentManage.AppId + "&id=" + OpenIDManage.GetOpenID();
            }
            else
            {

                return "";
            }
        }

        #region 支付
        //后台回调
        public ActionResult PayResult()
        {
            Wechat.LogManage.Log("微信支付异步通知URL:" + Request.Url.ToString());
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Request.InputStream);

            //if (DateTime.Now < new DateTime(2016,4,13))
            //    doc.LoadXml("<xml><appid><![CDATA[wx107c5de59ec6ff20]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[34800]]></cash_fee><device_info><![CDATA[WEB]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1307933801]]></mch_id><nonce_str><![CDATA[J0fbzd49AkjR7NvGRK3RWwuoHXsumNlf]]></nonce_str><openid><![CDATA[oHqQxs8nZRY4m6bZbGGtfpkWA1Ks]]></openid><out_trade_no><![CDATA[16041100864016326255]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[60719BA76D99424EDCF30386C3C025FD]]></sign><time_end><![CDATA[20160411162705]]></time_end><total_fee>34800</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4004352001201604114740206251]]></transaction_id></xml>");

            Wechat.LogManage.Log("微信支付异步通知DATA:" + doc.InnerXml);

            NotifyResult result = new NotifyResult(doc.InnerXml);
            var pay = HeadPay.GetPayWayByOrderNO(result.out_trade_no);
            result.key = pay.GetValue(RFrameGenerate.BLL.DictionaryConst.PayWays.WeiXin.Key);// "88ae321f1e8927f64455422ce7af0e8a";
            if (result.Verify() == true)
            {
                //没有充值,暂不做并发处理
                var usresutl = OrderManage.PaySuccess(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);
                if (usresutl.State == true)
                {
                    return Content(@"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                }
                else
                {
                    //失败暂时不处理,待定[小周]
                    Wechat.LogManage.Log("支付失败:" + usresutl.Msg + ",详情:" + doc.InnerXml);
                    return Content(@"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理逻辑失败]]></return_msg></xml>");
                }
            }
            else
            {
                return Content(@"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>");
            }
        }
        //开始支付
        public ActionResult Paying(string orderNo, string userid = "", string appid = "")
        {
            var url = RedirectPayingUrl(orderNo, "Paying", userid, appid);
            LogManage.Log(url);
            if (string.IsNullOrEmpty(url) != true)
                return Redirect(url);

            if (string.IsNullOrEmpty(orderNo))
                Content("支付请求时出错,请重新支付!");

            var order = OrderManage.GetOrderByNo(orderNo);
            if (order == null)
                return Content("支付出错,非法订单!");

            var payMoneyState = OrderManage.OrderPayMoney(order);
            if (!payMoneyState.State) return Content(payMoneyState.Msg);

            ViewBag.TotalAmount = payMoneyState.Price;
            ViewBag.orderNo = orderNo;
            return View();
        }

        public JsonResult SubmitPaying66(string orderNo)
        {
            string OpenID = OpenIDManage.GetOpenID();

            if (string.IsNullOrEmpty(orderNo))
                return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号!" });
            var order = OrderManage.GetOrderByNo(orderNo);


            if (string.IsNullOrEmpty(OpenID))
            {
                var member = MemberManage.GetMemberByGuid(order.MemberGuid.Value);
                OpenID = member.MemberOpenID;
            }


            if (order == null)
                return Json(new { Result = "NO", Msg = "支付出错,非法订单!" });

            if (string.IsNullOrEmpty(OpenID) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });
            if (string.IsNullOrEmpty(RFrameGenerate.Common.CurrentManage.AppId) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });

            var payMoneyState = OrderManage.OrderPayMoney(order);
            if (!payMoneyState.State) return Json(new { Result = "NO", Msg = payMoneyState.Msg });

            if (payMoneyState.Price <= 0) return Json(new { Result = "NO", Msg = "订单总价为0元,请使用余额支付" });

            if (order.PrivilegeGuid != null)
            {
                var coupon = ActivityDetailManage.GetMemberCoupon(order.PrivilegeGuid.Value);

                var couponState = ActivityDetailManage.CheckCoupon(coupon);

                if (!couponState.State) return Json(new { Result = "NO", Msg = couponState.Msg });
            }

            //屏蔽支付方式的关联
            //var upw = OrderManage.UpdatePayWay(orderNo);//只有微信支付
            //if (upw.State != true)
            //    return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });

            #region 微信支付
            var pay = HeadPay.GetPayWayByOrderNO(orderNo);
            string key = pay.GetValue(DictionaryConst.PayWays.WeiXin.Key);
            string mch_id = pay.GetValue(DictionaryConst.PayWays.WeiXin.MChid);
            string appid = pay.GetValue(DictionaryConst.PayWays.WeiXin.AppID);

            //if (CurrentManage.AppId == "wxd5e10229829c4d76")
            //{//测试 极欧云时使用Rightcode支付
            //    key = "88ae321f1e8927f64455422ce7af0e8a";
            //    mch_id = "10018169";
            //    appid = "wx1efed944cad6ca0f";
            //    OpenID = "oYVmZjt31CcH0vJqI3-1znIGDgVs";
            //}

            if (string.IsNullOrEmpty(key) == true)
                return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });
            if (string.IsNullOrEmpty(mch_id) == true)
                return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });

            var mentity = DistributionManage.GetStoreInfo();

            UnifiedOrderRequest payRequest = new UnifiedOrderRequest()
            {
                key = key,
                mch_id = mch_id,
                appid = appid,
                body = mentity.SotreTitle + "商品订单",
                openid = weixinopen.WeiXinOpenRequest.GetOpenId(OpenID),//取openid,格式{openid-6-1-userid}
                out_trade_no = order.OrderNo,
                total_fee = (payMoneyState.Price * 100).ToString("0"),
                spbill_create_ip = "120.55.189.247",
                notify_url = RFrameGenerate.Common.CurrentManage.Domain + "Online/WeiXinPay/PayResult",
                trade_type = "JSAPI",
                device_info = "WEB",
            };

            UnifiedOrderResult orderPay = (UnifiedOrderResult)payRequest.Request();

            orderPay.key = key;
            if (orderPay.Verify())
            {
                var payConfig = new Wechat.ChoosePayConfig(key)
                {
                    appId = appid,
                    package = string.Format("prepay_id={0}", orderPay.prepay_id),
                };

                LogManage.Log("开始微信支付:appid=" + payRequest.appid + ",openid=" + OpenID + ",out_trade_no=" + payRequest.out_trade_no + ",notify_url=" + payRequest.notify_url + ",最终openid:" + payRequest.openid);

                return Json(new { Result = "OK", pay = payConfig });
            }
            else
            {
                LogManage.Log("支付失败(appid=" + appid + "):" + ",openid=" + OpenID + ",return_code=" + orderPay.return_code + ",return_msg=" + orderPay.return_msg + ",err_code=" + orderPay.err_code + ",err_code_des=" + orderPay.err_code_des + ",result_code=" + orderPay.result_code + ",最终openid:" + payRequest.openid);
                return Json(new { Result = "NO", Msg = "支付失败" });
            }
            #endregion
        }

        //前台支付成功回调
        public ActionResult Payed(decimal amount)
        {
            ViewBag.TotalAmount = amount;
            return View();
        }

        /// <summary>
        /// 获取客户ip
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected string GetIP()
        {
            string ip = string.Empty;
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
                ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            if (string.IsNullOrEmpty(ip))
                ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
            return ip;
        }
        #endregion

        #region 一元购支付

        //后台回调
        public ActionResult PaydResultCrow()
        {
            Wechat.LogManage.Log("微信支付异步通知URL:" + Request.Url.ToString());
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Request.InputStream);
            //doc.LoadXml("<xml><appid><![CDATA[wx2baed91b098d5689]]></appid><attach><![CDATA[16052308740118221221-]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><device_info><![CDATA[WEB]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1288824901]]></mch_id><nonce_str><![CDATA[5Rxfe69l9hthtjzMN44uDB2WkELwSJDJ]]></nonce_str><openid><![CDATA[o5t1Rt-T9vBZMOPdTDMslga20cFg]]></openid><out_trade_no><![CDATA[16052308740118221221-]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[B24129BC19CB21478B68A7C1530DA6EF]]></sign><time_end><![CDATA[20160523182141]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4009112001201605236207478640]]></transaction_id></xml>");

            Wechat.LogManage.Log("微信支付异步通知DATA:" + doc.InnerXml);

            NotifyResult result = new NotifyResult(doc.InnerXml);
            var pay = HeadPay.GetPayWayByOrderNO_Crowd(result.out_trade_no);
            result.key = pay.GetValue(RFrameGenerate.BLL.DictionaryConst.PayWays.WeiXin.Key);// "88ae321f1e8927f64455422ce7af0e8a";

            //////var usresutl222 = CrowdParticipateManage.PaySuccess(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);

            if (result.Verify() == true)
            {
                //没有充值,暂不做并发处理
                var usresutl = CrowdParticipateManage.PaySuccess(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);
                if (usresutl.State == true)
                {
                    return Content(@"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                }
                else
                {
                    //失败暂时不处理,待定[小周]
                    Wechat.LogManage.Log("支付失败:" + usresutl.Msg);
                    return Content(@"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理逻辑失败]]></return_msg></xml>");
                }
            }
            else
            {
                return Content(@"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>");
            }
        }
        //开始支付
        public ActionResult PayingCrowd(string orderNo, string userid = "", string appid = "")
        {
            var url = RedirectPayingUrl(orderNo, "PayingCrowd", userid, appid);
            if (string.IsNullOrEmpty(url) != true)
                return Redirect(url);

            if (string.IsNullOrEmpty(orderNo))
                Content("支付请求时出错,请重新支付!");

            var amount = CrowdParticipateManage.GetBuyAmount(orderNo);
            if (amount == 0)
            {
                Response.Redirect("../../Crowdfunding/Index");
                return Content("支付出错,非法订单!!");
            }
            ViewBag.TotalAmount = amount;
            ViewBag.orderNo = orderNo;
            return View();
        }

        public JsonResult SubmitPayingCrowd(string orderNo)
        {
            if (string.IsNullOrEmpty(orderNo))
                return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号!" });

            string OpenID = OpenIDManage.GetOpenID();


            if (string.IsNullOrEmpty(OpenID))
            {
                OpenID = CrowdParticipateManage.GetOpenID(orderNo);
            }
            var amount = CrowdParticipateManage.GetBuyAmount(orderNo);

            if (CurrentManage.Domain.Contains("jioukeji.com") == true)
                amount = 0.01M;

            if (string.IsNullOrEmpty(OpenID) == true)
            {
                Response.Redirect("../../Crowdfunding/Index");
                return Json(new { Result = "NO", Msg = "支付出错,非法订单!!!" });
            }
            if (string.IsNullOrEmpty(OpenID) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });
            if (string.IsNullOrEmpty(RFrameGenerate.Common.CurrentManage.AppId) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });
            if (amount <= 0)
                return Json(new { Result = "NO", Msg = "支付失败,支付金额不能小于或等于0!" });

            //屏蔽支付方式的关联
            //var upw = CrowdParticipateManage.UpdatePayWay(orderNo);//只有微信支付
            //if (upw.State != true)
            //    return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });

            #region 微信支付
            var pay = HeadPay.GetPayWayByOrderNO_Crowd(orderNo);
            string key = pay.GetValue(DictionaryConst.PayWays.WeiXin.Key);
            string mch_id = pay.GetValue(DictionaryConst.PayWays.WeiXin.MChid);
            string appid = pay.GetValue(DictionaryConst.PayWays.WeiXin.AppID);

            if (string.IsNullOrEmpty(key) == true)
                return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });
            if (string.IsNullOrEmpty(mch_id) == true)
                return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });

            var mentity = DistributionManage.GetStoreInfo();

            UnifiedOrderRequest payRequest = new UnifiedOrderRequest()
            {
                key = key,
                mch_id = mch_id,
                appid = appid,
                body = mentity.SotreTitle + "商品订单",
                openid = weixinopen.WeiXinOpenRequest.GetOpenId(OpenID),//取openid,格式{openid-6-1-userid},
                out_trade_no = orderNo,
                total_fee = (amount * 100).ToString("0"),
                spbill_create_ip = "112.74.79.61",
                notify_url = RFrameGenerate.Common.CurrentManage.Domain + "Online/WeiXinPay/PaydResultCrow",
                trade_type = "JSAPI",
                device_info = "WEB",
                attach = orderNo,
            };

            UnifiedOrderResult orderPay = (UnifiedOrderResult)payRequest.Request();

            orderPay.key = key;
            if (orderPay.Verify())
            {
                var payConfig = new Wechat.ChoosePayConfig(key)
                {
                    appId = appid,
                    package = string.Format("prepay_id={0}", orderPay.prepay_id),
                };

                LogManage.Log("开始微信支付:appid=" + payRequest.appid + ",openid=" + OpenID + ",out_trade_no=" + payRequest.out_trade_no + ",notify_url=" + payRequest.notify_url);

                return Json(new { Result = "OK", pay = payConfig });
            }
            else
            {
                LogManage.Log("支付失败(appid=" + appid + "):" + ",openid=" + OpenID + ",return_code=" + orderPay.return_code + ",return_msg=" + orderPay.return_msg + ",err_code=" + orderPay.err_code + ",err_code_des=" + orderPay.err_code_des + ",result_code=" + orderPay.result_code);
                return Json(new { Result = "NO", Msg = "支付失败" });
            }
            #endregion
        }

        //前台支付成功回调
        public ActionResult PayedCrowd(decimal amount)
        {
            ViewBag.TotalAmount = amount;
            return View();
        }

        #endregion

        #region 充值支付
        //后台回调
        public ActionResult PaydResultRecharge()
        {
            Wechat.LogManage.Log("微信支付异步通知URL:" + Request.Url.ToString());
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Request.InputStream);
            //doc.LoadXml("<xml><appid><![CDATA[wx2baed91b098d5689]]></appid><attach><![CDATA[16052104365010740735]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><device_info><![CDATA[WEB]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1288824901]]></mch_id><nonce_str><![CDATA[1sh4AynsV7WyB2k4LMKRni27kCGO2OEf]]></nonce_str><openid><![CDATA[o5t1Rt-T9vBZMOPdTDMslga20cFg]]></openid><out_trade_no><![CDATA[16052104365010740735]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[C55DFA8709588671FE2DC8E4286A6091]]></sign><time_end><![CDATA[20160521104045]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4009112001201605216104665222]]></transaction_id></xml>");

            Wechat.LogManage.Log("微信支付异步通知DATA:" + doc.InnerXml);

            NotifyResult result = new NotifyResult(doc.InnerXml);
            var pay = HeadPay.GetPayWayByOrderNO_T_BAS_Recharge(result.out_trade_no);
            result.key = pay.GetValue(RFrameGenerate.BLL.DictionaryConst.PayWays.WeiXin.Key);// "88ae321f1e8927f64455422ce7af0e8a";

            //var usresutl222 = CrowdParticipateManage.PaySuccess(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);

            if (result.Verify() == true)
            {
                var usresutl = RechargeManage.PaySuccess(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);
                if (usresutl.State == true)
                {
                    return Content(@"<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                }
                else
                {
                    RechargeManage.ExecuteFaile(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);
                    Wechat.LogManage.Log("处理逻辑失败:" + usresutl.Msg);
                    return Content(@"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理逻辑失败]]></return_msg></xml>");
                }
            }
            else
            {
                RechargeManage.VerifyFailed(result.out_trade_no, result.total_fee, result.appid, result.openid, result.transaction_id);
                Wechat.LogManage.Log("验证失败:" + result.out_trade_no);
                return Content(@"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>");
            }
        }

        public ActionResult RechargePaying(string orderNo, string userid = "", string appid = "")
        {
            var url = RedirectPayingUrl(orderNo, "RechargePaying", userid, appid);
            if (string.IsNullOrEmpty(url) != true)
                return Redirect(url);

            if (string.IsNullOrEmpty(orderNo))
                return Content("支付请求时出错,请重新支付!");

            var order = RechargeManage.GetOrder(orderNo);
            if (order == null)
                return Content("支付出错,非法订单");

            if (order.Amount <= 0.0m)
                return Content("订单金额出错,非法订单");

            ViewBag.TotalAmount = order.Amount;
            ViewBag.orderNo = orderNo;

            return View();
        }

        public JsonResult SubmitPayingRecharge(string orderNo)
        {
            if (string.IsNullOrEmpty(orderNo))
                return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号!" });

            string openID = OpenIDManage.GetOpenID();

            if (string.IsNullOrEmpty(openID))
            {
                openID = RechargeManage.GetMemberOpenID(orderNo);
            }
            if (string.IsNullOrEmpty(openID) == true)
            {
                Response.Redirect("../../My/Recharge");
                return Json(new { Result = "NO", Msg = "支付出错,非法订单!!!" });
            }
            if (string.IsNullOrEmpty(openID) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });
            if (string.IsNullOrEmpty(RFrameGenerate.Common.CurrentManage.AppId) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });

            var order = RechargeManage.GetOrder(orderNo);
            if (order == null)
                return Json(new { Result = "NO", Msg = "支付出错,非法订单!" });

            var amount = order.Amount;

            if (CurrentManage.MerchantUserID == "liuyi" || CurrentManage.MerchantUserID == "jioukeji01" || CurrentManage.MerchantUserID == "jioushuiguo")
                amount = 0.01M;

            if (amount <= 0)
                return Json(new { Result = "NO", Msg = "支付失败,支付金额不能小于或等于0!" });

            //var upw = RechargeManage.UpdatePayWayAndInnerState(orderNo);//只有微信支付

            //if (upw.State != true)
            //    return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });

            #region 微信支付
            var pay = HeadPay.GetPayWayByOrderNO_T_BAS_Recharge(orderNo);
            string key = pay.GetValue(DictionaryConst.PayWays.WeiXin.Key);
            string mch_id = pay.GetValue(DictionaryConst.PayWays.WeiXin.MChid);
            string appid = pay.GetValue(DictionaryConst.PayWays.WeiXin.AppID);

            if (string.IsNullOrEmpty(key) == true)
                return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });
            if (string.IsNullOrEmpty(mch_id) == true)
                return Json(new { Result = "NO", Msg = "支付失败,商家未配置微信支付,请联系商家!" });

            var mentity = DistributionManage.GetStoreInfo();

            UnifiedOrderRequest payRequest = new UnifiedOrderRequest()
            {
                key = key,
                mch_id = mch_id,
                appid = appid,
                body = mentity.SotreTitle + "充值订单",
                openid = weixinopen.WeiXinOpenRequest.GetOpenId(openID),//取openid,格式{openid-6-1-userid},
                out_trade_no = orderNo,
                total_fee = (amount * 100).ToString("0"),
                spbill_create_ip = "112.74.79.61",
                notify_url = RFrameGenerate.Common.CurrentManage.Domain + "Online/WeiXinPay/PaydResultRecharge",
                trade_type = "JSAPI",
                device_info = "WEB",
                attach = orderNo,
            };

            UnifiedOrderResult orderPay = (UnifiedOrderResult)payRequest.Request();

            orderPay.key = key;
            if (orderPay.Verify())
            {
                var payConfig = new Wechat.ChoosePayConfig(key)
                {
                    appId = appid,
                    package = string.Format("prepay_id={0}", orderPay.prepay_id),
                };

                LogManage.Log("开始微信支付:appid=" + payRequest.appid + ",openid=" + openID + ",out_trade_no=" + payRequest.out_trade_no + ",notify_url=" + payRequest.notify_url);

                return Json(new { Result = "OK", pay = payConfig });
            }
            else
            {
                LogManage.Log("支付失败(appid=" + appid + "):" + ",openid=" + openID + ",return_code=" + orderPay.return_code + ",return_msg=" + orderPay.return_msg + ",err_code=" + orderPay.err_code + ",err_code_des=" + orderPay.err_code_des + ",result_code=" + orderPay.result_code);
                return Json(new { Result = "NO", Msg = "支付失败" });
            }
            #endregion

        }
        #endregion

        #region 余额支付

        public JsonResult PayBalance(string orderNo)
        {
            if (string.IsNullOrEmpty(orderNo))
                return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号！" });

            var order = OrderManage.GetOrderByNo(orderNo);
            if (order == null)
                return Json(new { Result = "NO", Msg = "支付出错,非法订单!" });
            string openID = OpenIDManage.GetOpenID();

            var member = MemberManage.GetMemberByGuid(order.MemberGuid.Value);

            if (member == null)
                return Json(new { Result = "NO", Msg = "不存在会员!" });

            if (string.IsNullOrEmpty(openID))
            {
                openID = member.MemberOpenID;
            }
            if (string.IsNullOrEmpty(openID) == true)
                return Json(new { Result = "NO", Msg = "支付失败,请重新进入支付页面!" });

            var payMoneyState = OrderManage.OrderPayMoney(order);
            if (!payMoneyState.State) return Json(new { Result = "NO", Msg = payMoneyState.Msg });

            if (payMoneyState.Price < 0)//支付0元购
                return Json(new { Result = "NO", Msg = "支付失败,支付金额不能小于0!" });

            if (member.Balance < payMoneyState.Price)
                return Json(new { Result = "NO", Msg = "余额不足，请充值或使用微信支付！" });

            var amount = member.Amount;
            var balance = member.Balance;

            var usresutl = OrderManage.PaySuccess(order.OrderNo, (payMoneyState.Price * 100).ToString("N02"), CurrentManage.AppId, openID, "余额支付", true);
            if (usresutl.State == true)
            {
                //RechargeRecordManage.AddConsume(orderNo, order.OrderGuid, member.MemberGuid, payMoneyState.Price, amount, balance);

                return Json(new { Result = "OK", Amount = payMoneyState.Price });
            }
            else
            {
                Wechat.LogManage.Log("PayBalance.Pay Failed" + order.OrderNo + "\r\n" + usresutl.Msg);
                return Json(new { Result = "NO", Msg = usresutl.Msg });
            }
        }

        public JsonResult GetAmount(string orderNo)
        {
            if (string.IsNullOrEmpty(orderNo)) return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号！" });

            var order = OrderManage.GetOrderByNo(orderNo);

            if (order == null) return Json(new { Result = "NO", Msg = "支付出错,非法订单!" });

            var payMoneyState = OrderManage.OrderPayMoney(order);

            if (!payMoneyState.State) return Json(new { Result = "NO", Msg = payMoneyState.Msg });

            var member = MemberManage.GetMemberByGuid(order.MemberGuid.Value);

            if (member == null) return Json(new { Result = "NO", Msg = "不存在会员!" });

            if (member.Balance < payMoneyState.Price) return Json(new { Result = "NO", Msg = "余额不足，请充值或使用微信支付！" });

            return Json(new { Result = "OK", Amount = payMoneyState.Price, Balance = member.Balance.ToString("N02") });

        }
        #endregion

        #region 模拟支付
        //开始支付
        public ActionResult PayTest(string orderNo)
        {
            if (string.IsNullOrEmpty(orderNo))
                Content("支付请求时出错,请重新支付!");

            var order = OrderManage.GetOrderByNo(orderNo);
            if (order == null)
                return Content("支付出错,非法订单!");

            var payMoneyState = OrderManage.OrderPayMoney(order);
            if (!payMoneyState.State) return Content(payMoneyState.Msg);

            ViewBag.TotalAmount = payMoneyState.Price;
            ViewBag.orderNo = orderNo;
            return View();
        }

        public ActionResult PaySimulation(string orderNo, decimal totalAmount)
        {
            ViewBag.orderNo = orderNo;
            ViewBag.TotalAmount = totalAmount;
            return View();
        }

        public JsonResult SubmitSimulationPaying(string orderNo, string amount)
        {
            string OpenID = OpenIDManage.GetOpenID();

            if (string.IsNullOrEmpty(orderNo))
                return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号!" });

            var order = OrderManage.GetOrderByNo(orderNo);

            if (order == null)
                return Json(new { Result = "NO", Msg = "不存在订单，支付失败!" });

            if (order.PrivilegeGuid != null)
            {
                var coupon = ActivityDetailManage.GetMemberCoupon(order.PrivilegeGuid.Value);

                var couponState = ActivityDetailManage.CheckCoupon(coupon);

                if (!couponState.State) return Json(new { Result = "NO", Msg = couponState.Msg });
            }

            var usresutl = OrderManage.PaySuccess(orderNo, (decimal.Parse(amount) * 100).ToString(), RFrameGenerate.Common.CurrentManage.AppId, OpenID, "模拟支付");
            if (usresutl.State)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = usresutl.Msg });
        }

        /// <summary>
        /// 测试支付
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public JsonResult SubmitTest(string orderNo, string amount)
        {
            if (string.IsNullOrEmpty(orderNo))
                return Json(new { Result = "NO", Msg = "支付出错,缺少订单编号!" });
            var usresutl = OrderManage.PayTest(orderNo, (decimal.Parse(amount) * 100).ToString(), RFrameGenerate.Common.CurrentManage.AppId);
            if (usresutl.State)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = usresutl.Msg });
        }
        #endregion


        #endregion
    }
}
