const app = getApp()
const baseUrl = app.globalData.baseUrl
// 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: {},
    // {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,
    })
  },
  toPay() {
    const self = this
    // 假设订单信息在 this.data.orders 中
    const orderData = this.data.orders
    // TODO 用户id暂时写死
    orderData.userId = 1
    orderData.status = 1
    console.log(orderData)
    //先生成订单
    wx.request({
      // TODO 未测试
      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,
          })
          // 跳转到用户页面
          wx.switchTab({
            url: "/page/component/user/user",
          })
        } else {
          wx.showToast({
            title: "提交失败",
            icon: "none",
            duration: 2000,
          })
        }
      },
      fail() {
        wx.showToast({
          title: "请求失败",
          icon: "none",
          duration: 2000,
        })
      },
    })
    wx.showModal({
      title: "提示",
      content: "本系统只做演示，支付系统已屏蔽",
      text: "center",
      complete() {
        // 发送订单数据到后端
      },
    })
  },
})
