// pages/shop/orderDetail.js

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

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 订单 ID
    orderId: '',
    // 订单详情
    order: {},

    /**
     * 用于界面渲染
     */
    // 订单商品列表
    orderGoodList: [],
    // 订单状态
    orderStatusCode: '',
    // 订单创建时间
    orderTime: '',
    // 订单总金额
    orderPrice: '',
  },

  clearPageData() {
    this.setData({
      order: {},
      orderGoodList: [],
      orderStatusCode: '',
      orderTime: '',
      orderPrice: '',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    if (!options || !options.orderId) {
      wx.showModal({
        title: '订单查询失败',
        content: '请刷新页面后重试',
        showCancel: false,
        complete: (res) => {
          wx.navigateBack()
        }
      })
    }

    this.setData({
      _options: options,
      orderId: options.orderId,
    })
    this.loadPageData()
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  refreshMyOrderPage() {
    // 刷新
    console.log("刷新上级订单列表页")
    let myOrderPage = getCurrentPages().find(p => p.route == "pages/shop/myOrder")
    myOrderPage && myOrderPage.onPullDownRefresh()
  },

  // 订单状态：等待确认
  confirmPayment() {
    // 点击确认支付按钮
    wx.showModal({
      title: '拉起支付',
      content: '点击确认完成支付，点击取消放弃支付',
      complete: (res) => {
        if (res.cancel) {
          wx.showToast({
            title: '用户取消支付',
            icon: 'error',
          })
        }

        if (res.confirm) {
          (async () => {
            this.clearPageData()
            let payResult = await orderService.payOrder(this.data.orderId)
            console.log("payResult", payResult)
            this.onLoad(this.data._options)
            this.refreshMyOrderPage()
            wx.showModal({
              title: '支付结果',
              content: payResult,
              showCancel: false,
              complete: (res) => {
                // wx.navigateBack({
                //   delta: getCurrentPages().length - 1
                // })
                // wx.navigateTo({
                //   url: "/pages/shop/orderDetail?orderId=" + this.data.orderId,
                // })
              }
            })
          })();
        }
      }
    })
  },

  // 订单状态：等待确认
  cancelPayment() {
    // 点击取消订单按钮
    wx.showModal({
      title: '是否取消订单？',
      content: '点击确认取消订单，点击取消关闭弹窗（未发货前可取消订单）',
      complete: (res) => {
        if (res.confirm) {
          (async () => {
            this.clearPageData()
            let cancelResult = await orderService.cancelOrder(this.data.orderId)
            console.log("cancelResult", cancelResult)
            this.onLoad(this.data._options)
            this.refreshMyOrderPage()
            wx.showModal({
              title: '操作结果',
              content: cancelResult || "操作失败，请重试",
              showCancel: false,
              complete: (res) => {
                // wx.navigateBack({
                //   delta: getCurrentPages().length - 1
                // })
                // wx.navigateTo({
                //   url: "/pages/shop/orderDetail?orderId=" + this.data.orderId,
                // })
              }
            })
          })();
        }
      }
    })
  },

  loadPageData() {
    (async () => {
      console.log("orderId", this.data.orderId)
      let orderDetail = await orderService.getOrderDetail(this.data.orderId)
      console.log("orderDetail", orderDetail)

      if (!orderDetail) {
        wx.showModal({
          title: '订单查询失败',
          content: '',
          showCancel: false,
          complete: (res) => {
            wx.navigateBack()
          }
        })
        return
      }

      let orderGoodList = []
      for (let item of orderDetail.orderItem) {
        orderGoodList.push({
          wxid: item.goodId, // 用于列表渲染
          good: orderDetail.goods.find(good => good.id == item.goodId),
          goodCount: item.goodCount,
          unitPrice: item.unitPrice,
        })
      }
      console.log("orderGoodList", orderGoodList)

      let orderStatusCode = orderDetail.order.orderStatusCode
      console.log("orderStatusCode", orderStatusCode)

      let orderPrice = orderDetail.order.orderPrice
      console.log("orderPrice", orderPrice)

      this.setData({
        order: orderDetail.order,
        orderGoodList: orderGoodList,
        orderTime: orderDetail.order.orderDate.replace("T", " "),
        orderStatusCode: orderStatusCode,
        orderPrice: orderPrice,
      })
    })();
  }
})
