// pages/shop/myOrder.js

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

Page({

  /**
   * 页面的初始数据
   */
  data: {
    filterActiveId: '',
    filterActiveName: '',
    filterList: [],

    filterPirckerIndex: 0,

    orderList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadPageData()
  },

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

  },

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

  },

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

  },

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

  },

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

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

  },

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

  },

  // filterRadioChange(e) {
  //   console.log("e.detail.value", e.detail.value)
  //   this.setData({
  //     filterActiveId: e.detail.value,
  //   })
  //   this.updatePageData()
  // },

  filterPickerChange(e) {
    console.log("e.detail.value", e.detail.value)
    let filter = this.data.filterList[e.detail.value]
    console.log("filterActiveId", filter.id)
    console.log("filterActiveName", filter.name)
    this.setData({
      filterActiveId: filter.id,
      filterActiveName: filter.name
    })
    this.updatePageData()
  },

  bindOrderDetailTap(e) {
    let dataset = e.currentTarget.dataset
    console.log("dataset", dataset)
    console.log("orderDetail", dataset.orderdetail)
    // 订单确认页
    wx.navigateTo({
      url: "/pages/shop/orderDetail?orderId=" + dataset.orderdetail.id,
    })
  },



  loadPageData() {
    (async () => {
      let userOrder = await orderService.listUserOrder()
      console.log("userOrder", userOrder)
      
      if (!userOrder) {
        wx.showModal({
          title: '订单查询失败',
          content: '',
          showCancel: false,
          complete: (res) => {
            wx.navigateBack()
          }
        })
        return
      }

      let filterList = Object.keys(userOrder.filter).map(key => {
        return {
          id: key,
          name: userOrder.filter[key],
        }
      })
      filterList.unshift({
        id: '',
        name: "全部",
      })
      console.log("filterList", filterList)
      this.setData({
        filterList: filterList,
        filterActiveName: "全部",
        orderList: userOrder.orders.map(order => {
          order.displayDate = order.orderDate
          return order
        })
      })
    })();
  },

  updatePageData() {
    this.setData({
      orderList: [],
    });
    (async () => {
      let userOrder = await orderService.listUserOrder(this.data.filterActiveId)
      console.log("userOrder", userOrder)
      this.setData({
        orderList: userOrder.orders.map(order => {
          order.displayDate = order.orderDate
          return order
        })
      })
    })();
  }
})