using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Extend.User;
using Mall.WeChat.Helper;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace Mall.WindowsService.Helper
{
   public class PayUtil
    {
        /// <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 CustomerId, string openid, RB_MiniProgram_Extend model,  string Remark = "")
        {

            if (!System.IO.File.Exists(Path.Combine(Config.PayCertificateUrl, "App_Data/Certs/WeChatApp/" + model.WeChatPayCertificateUrl)))
            {
                return false;
            }
            var req = new Common.Pay.WeChatPat.RequestHandler();
            req.SetKey(model.WeChatApiSecret);
            req.SetParameter("mch_appid", model.MiniAppId);//微信开放平台审核通过的应用APPID
            req.SetParameter("mchid", model.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_V2( model.WeChatApiSecret));
            var reqXml = req.ParseXml();
            var result = Common.Pay.WeChatPat.HttpHelper.Post(new Common.Pay.WeChatPat.Model.HttpParam()
            {
                Url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
                PostParam = reqXml,
                Encoding = Encoding.UTF8, //Common.Pay.WeChatPat.HttpHelper.GetRequestEncoding(_accessor.HttpContext.Request),
                CertPath = Path.Combine(Config.PayCertificateUrl, "App_Data/Certs/WeChatApp/" + model.WeChatPayCertificateUrl),//"App_Data/Certs/WeChatApp/apiclient_cert.p12"),// model.WeChatPayCertificateUrl,
                CertPwd = model.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;
        }

    }
}
