
using Mall.WeChat.Helper;
using Mall.Common.Pay.WeChatPat.Model;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Xml.Linq;
using Microsoft.AspNetCore.Http;
using Mall.Common.Plugin;

namespace Mall.Common.Pay
{
    /// <summary>
    /// 支付帮助类
    /// </summary>
    public class PayUtilWeiXin
    {
        public PayUtilWeiXin() { }

        /// <summary>
        /// 企业付款
        /// </summary>
        /// <param name="sOrderNo"></param>
        /// <param name="sProductName"></param>
        /// <param name="dPrice"></param>
        /// <param name="CustomerId"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static bool GetTransfersOrder(string sOrderNo, decimal dPrice, string openid, string WeChatPayCertificateUrl,string WeChatApiSecret,string WeChatPayMerchants, string MiniAppId, IHttpContextAccessor _accessor, string Remark = "")
        {
            if (!System.IO.File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/Certs/WeChatApp/" + WeChatPayCertificateUrl)))
            {
                return false;
            }
            var req = new Common.Pay.WeChatPat.RequestHandler();
            req.SetKey(WeChatApiSecret);
            //
            req.SetParameter("mch_appid", MiniAppId);//微信开放平台审核通过的应用APPID
            req.SetParameter("mchid", WeChatPayMerchants);//微信支付分配的商户号
            req.SetParameter("nonce_str", GetNoncestr());//随机字符串，不长于32位
            req.SetParameter("partner_trade_no", sOrderNo);//商户订单号，需保持唯一性(只能是字母或者数字，不能包含有其它字符)
            req.SetParameter("openid", openid);
            req.SetParameter("check_name", "NO_CHECK");
            req.SetParameter("amount", (dPrice * 100).ToString("f0"));
            req.SetParameter("desc", Remark == "" ? "赞羊商城佣金提现" : Remark);
            req.SetParameter("sign", req.CreateMd5Sign(_accessor, WeChatApiSecret));
            var reqXml = req.ParseXml();
            var result = Common.Pay.WeChatPat.HttpHelper.Post(new HttpParam()
            {
                Url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
                PostParam = reqXml,
                Encoding = Common.Pay.WeChatPat.HttpHelper.GetRequestEncoding(_accessor.HttpContext.Request),
                CertPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/Certs/WeChatApp/" + WeChatPayCertificateUrl),//"App_Data/Certs/WeChatApp/apiclient_cert.p12"),// model.WeChatPayCertificateUrl,
                CertPwd = WeChatPayMerchants//证书密码默认为您的商户ID
            });

            var xe = XElement.Parse(result, LoadOptions.SetLineInfo);
            var returnCode = xe.GetElement("return_code").Value;
            var resultCode = xe.GetElement("result_code").Value;
            if (returnCode.Equals("SUCCESS") && resultCode.Equals("SUCCESS"))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取随机字符串
        /// </summary>
        /// <returns></returns>
        public static string GetNoncestr()
        {
            var random = new Random();
            return SecurityHelper.MD5EncryptWeChat(random.Next(1000).ToString(CultureInfo.InvariantCulture), "GBK");
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimestamp()
        {
            var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// 对字符串进行URL编码
        /// </summary>
        /// <param name="instr"></param>
        /// <param name="charset">默认值：utf-8</param>
        /// <returns></returns>
        public static string UrlEncode(string instr, string charset)
        {
            if (instr == null || instr.Trim() == "")
                return "";
            var res = HttpUtility.UrlEncode(instr, !string.IsNullOrWhiteSpace(charset)
               ? Encoding.GetEncoding(charset)
               : Encoding.GetEncoding("utf-8"));
            return res;
        }
    }
}
