// pages/shop/goodDetail.js

const goodService = require("../../services/good")
const orderService = require("../../services/order")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodId: -1,
    goodinfo: {},

    buyGoodCount: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("goodDetail ->options", options)
    let goodId = options.id
    this.setData({
      goodId: goodId
    })
    this.loadPageData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },


  bindCountInput(e) {
    console.log("e", e)
    console.log("e.detail.value", e.detail.value)

    let regexp = /^[0-9]+$/.exec(e.detail.value)
    let buyGoodCountNum = Number(e.detail.value)
    if (!regexp || isNaN(buyGoodCountNum) || buyGoodCountNum < 1) {
      wx.showToast({
        title: '输入无效',
        icon: "error",
      })
      this.setData({
        buyGoodCount: this.data.buyGoodCount,
      })
      return
    }

    this.setData({
      buyGoodCount: buyGoodCountNum,
    })
  },
  btnAddCount() {
    this.setData({
      buyGoodCount: this.data.buyGoodCount + 1,
    })
  },
  btnSubtractCount() {
    this.setData({
      buyGoodCount: this.data.buyGoodCount - 1,
    })
  },


  // 立即下单
  btnBuyTap() {
    (async () => {
      // 创建订单
      let orderList = [{
        goodId: this.data.goodId,
        count: this.data.buyGoodCount,
      }]
      let orderId = await orderService.createOrder(orderList)
      console.log("orderId", orderId)

      if (!orderId) {
        wx.showModal({
          title: '出错了',
          content: '创建订单失败，请重试',
          showCancel: false,
          complete: (res) => {
          }
        })
      } else {
        // 跳转订单查看页面（携带订单号）
        wx.navigateTo({
          // url: "/pages/scan/entrance?a=1"
          url: "/pages/shop/orderDetail?orderId=" + orderId
        })
      }
    })();
  },

  btnAddCartTap() {
    wx.showModal({
      title: '暂未实现',
      content: '时间有限，该功能暂未实现~',
      showCancel: false,
      complete: (res) => {
      }
    })
  },

  loadPageData() {
    (async () => {
      let goodDetail = await goodService.getGoodDetail(this.data.goodId)
      console.log("goodDetail", goodDetail)
      this.setData({
        goodinfo: goodDetail
      })
    })();
  }
})
