using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog;
using Senparc.Weixin.MP.TenPayLibV3;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WechatApi.Controllers
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/Payment/[action]")]
    public class PaymentController : BaseController
    {
        private readonly string AppId;
        private readonly string MchId;
        private readonly string TenPayV3Notify;
        private readonly string Key;

        static Logger Logger = LogManager.GetCurrentClassLogger();

        public PaymentController(IConfiguration configuration)
        {
            AppId = configuration["WechatStatic:AppId"];
            MchId = configuration["WechatStatic:MchId"];
            TenPayV3Notify = configuration["WechatStatic:TenPayV3Notify"];
            Key = configuration["WechatStatic:Key"];
        }
        public IActionResult AdvancedPay()
        {
            #region 生成商户订单(系统内订单)TODO

            #endregion


            #region 调用微信统一下单API，生成预付单，获取预付单信息

            var attach = "efg";
            var body = "abc";
            var openId = "oKOqcv_4HD3qeuf6aL5gaD--z4Xs";
            var orderNum = DateTime.Now.ToString("yyyyMMddHHmmss");
            var total_fee = "1";


            RequestHandler requestHandler = new RequestHandler(HttpContext);
            //微信分配的公众账号ID（企业号corpid即为此appId）
            requestHandler.SetParameter("appid", AppId);
            //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
            requestHandler.SetParameter("attach", "attach");
            //商品或支付单简要描述
            requestHandler.SetParameter("body", "body");
            //微信支付分配的商户号
            requestHandler.SetParameter("mch_id", MchId);
            //微信支付分配的商户号
            // requestHandler.SetParameter("detail", "detail");
            //随机字符串，不长于32位。
            requestHandler.SetParameter("nonce_str", TenPayV3Util.GetNoncestr());
            //接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
            requestHandler.SetParameter("notify_url", TenPayV3Notify);
            //trade_type=JSAPI，此参数必传，用户在商户公众号appid下的唯一标识。
            requestHandler.SetParameter("openid", openId);
            //商户系统内部的订单号,32个字符内、可包含字母，自己生成
            requestHandler.SetParameter("out_trade_no", orderNum);
            //APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
            requestHandler.SetParameter("spbill_create_ip", "127.0.0.1");
            //订单总金额，单位为分，做过银联支付的朋友应该知道，代表金额为12位，末位分分
            requestHandler.SetParameter("total_fee", total_fee);
            //取值如下：JSAPI，NATIVE，APP，我们这里使用JSAPI
            requestHandler.SetParameter("trade_type", "JSAPI");
            requestHandler.SetParameter("sign", requestHandler.CreateMd5Sign("key", Key));

            string xml = requestHandler.ParseXML();
            //获取并返回预支付XML信息
            var result = TenPayV3.Unifiedorder(xml);
            XmlHelper xmlHelper = new XmlHelper();
            xmlHelper.LoadFromXmlString(result);

            Logger.Info($"result={result}");
            Logger.Info($"return_code={xmlHelper.GetValue("return_code")}");
            Logger.Info($"return_msg={xmlHelper.GetValue("return_msg")}");

            if (xmlHelper.GetValue("return_code") == "SUCCESS" && xmlHelper.GetValue("return_msg") == "OK")
            {
                return Success("预付单成功", new
                {
                    state = true,
                    appid = AppId,
                    package = xmlHelper.GetValue("prepay_id"),
                    sign = xmlHelper.GetValue("sign"),
                    noncestr = xmlHelper.GetValue("nonce_str"),
                    timeStamp = DateTime.UtcNow.Ticks
                });
            }
            return Error($"预付单失败。return_code={xmlHelper.GetValue("return_code")}, return_msg={ xmlHelper.GetValue("return_msg")}");
            #endregion
        }

        public void callback()
        {

        }

        private void GetPayInfo()
        {

        }
    }
}
