const app = getApp()
const baseUrl = app.globalData.baseUrl
const md5 = require('js-md5');

// page/component/orders/orders.js
Page({
  onLoad: function (options) {
    const orders = {
      id: options.id,
      title: options.title,
      price: options.price,
      num: options.num,
      image: options.image,
      specs: options.specs
    }
    this.setData({ orders })
    console.log(this.data.orders)
  },
  data: {
    address: {},
    hasAddress: false,
    total: 0,
    orders: {},
    config: {
      appid: "wx865aefa5a7115ae0",
      key: "d5a58d44588b42cbbe01daa5cfa4e792"
    }
    // {id:1,title:'新鲜芹菜 半斤',image:'/image/s5.png',num:4,price:0.01},
    // {id:2,title:'素米 500g',image:'/image/s6.png',num:1,price:0.03}
  },

  onReady() {
    this.getTotalPrice()
  },

  onShow: function () {
    const self = this
    wx.getStorage({
      key: "address",
      success(res) {
        self.setData({
          address: res.data,
          hasAddress: true,
        })
      },
    })
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let orders = this.data.orders
    let total = 0
    total += orders.num * orders.price
    this.setData({
      total: total,
    })
  },
  timeStamp: function () {
    return parseInt(new Date().getTime() / 1000) + ''
  },
  /* 随机数 */
  randomString: function () {
    var chars = 'A2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < 32; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },
  // 调起支付签名    这里我不太明白，虽然前面加载签名和后面验证，但里面加了随机数为什么验证还能通过我没还转过	      弯来，希望大家能搞明白吧，到时候可不要吝啬留言讲解一下下
  MixedencryMD5: function (data, randomString, timeStamp) {
    const payString = "appId=" + this.data.config.appid +
      "&nonceStr=" + randomString +
      "&package=prepay_id=" + "data.prepay_id" +
      "&signType=MD5" +
      "&timeStamp=" + timeStamp +
      "&key=" + this.data.config.key;

    const hash = md5(payString);  // 使用 md5 进行签名
    console.log(hash);
    return hash;
  },
  toPay() {
    const self = this;
    const orderData = this.data.orders;

    // 假设用户ID暂时写死
    orderData.userId = 1;
    orderData.status = 1;

    // 生成订单并请求支付
    wx.request({
      url: baseUrl + "/order/addOrUpdate", // 替换为你的后端API地址
      method: "POST",
      data: {
        ...orderData,
      },
      header: {
        "Content-Type": "application/json", // 设置请求头
      },
      success(res) {
        if (res.statusCode === 200) {
          wx.showToast({
            title: "订单已提交",
            icon: "success",
            duration: 2000,
          });

          // 假设服务器返回的支付信息中包含 prepay_id
          const paymentInfo = res.data.paymentInfo;  // 服务器返回的支付信息，包含 prepay_id 等

          // 生成支付签名等所需的参数（最好在服务器生成）
          const time = self.timeStamp()
          const randomString = self.randomString();
          const parSigns = self.MixedencryMD5(paymentInfo, randomString, time);

          // 发起支付请求
          wx.requestPayment({
            timeStamp: time,
            nonceStr: randomString,
            package: "prepay_id=" + "paymentInfo.prepay_id",
            signType: "MD5",
            paySign: parSigns,
            success(ress) {
              console.log('支付成功', ress);
              // 支付成功后的处理，跳转到用户页面或其他页面
              wx.switchTab({
                url: "/page/component/user/user",
              });
            },
            fail(ress) {
              console.log('支付失败', ress);
              wx.showToast({
                title: "支付失败，请重试",
                icon: "none",
                duration: 2000,
              });
            },
            complete(ress) {
              console.log('支付流程结束', ress);
            }
          });

        } else {
          wx.showToast({
            title: "提交失败",
            icon: "none",
            duration: 2000,
          });
        }
      },
      fail() {
        wx.showToast({
          title: "请求失败",
          icon: "none",
          duration: 2000,
        });
      },
    });
  },

})
