const { getOrderList, postOrderDelete } = require('./api/index')
const { postOrderDiffPay, postOrderCancel } = require('../orderDetail/api/index')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        name: '全部',
        value: '0'
      },
      {
        name: '待支付',
        value: '1'
      },
      {
        name: '待出发',
        value: '2'
      },
      {
        name: '进行中',
        value: '3'
      },
      {
        name: '已结束',
        value: '4'
      }
    ],
    active: '0', // 顶部菜单栏默认选中，订单状态：(0全部1待支付2待出发3进行中4已结束)
    current: 0, // 轮播图默认选中
    pageSize: 20,
    originScrollViewData: [],
    booDeleteOrder: false,
    booLock: false,
    refresherThreshold: 60, // 自定义下拉刷新阈值
    booCancelOrder: false,
    booPayment: false,
    itemData: {} // 当前选中的订单
  },
  // 下拉刷新加锁
  freshing: false,
  timer: null,

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

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

  },

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

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.timer)
  },
  bindCallBack() {
    this.onRefresh({ detail: { dy: this.data.refresherThreshold } })
  },
  jumpOrderDetail(e) {
    const { orderId } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' + orderId
    })
  },
  setOriginScrollViewData() {
    const temp = []
    for (let i = 0; i < this.data.tabs.length; i++) {
      temp.push({
        finished: false, // 所有数据是否加载完
        isRefresh: false, // 是否下拉刷新
        isFetchLock: false, // 接口调用加锁
        pageNum: 0,
        list: [],
        scrollY: 0,
        isFirst: true // 是否首次获取列表
      })
    }

    this.setData({
      originScrollViewData: temp
    }, () => {
      this.fetOrderList()
    })
  },
  changeTabs(e) {
    const value = e.currentTarget.dataset.value
    const index = this.data.tabs.findIndex(item => item.value === value)
    const temp = this.data.originScrollViewData[index]

    this.setData({
      active: value,
      current: index
    }, () => {
      if (temp.isFirst) {
        this.fetOrderList()
      }
    })
  },
  handleSwiper(e) {
    const { current, source } = e.detail
    const item = this.data.tabs[current]
    if (source) {
      this.setData({
        active: item.value
      }, () => {
        const temp = this.data.originScrollViewData[current]
        if (temp.isFirst) {
          this.fetOrderList()
        }
      })
    }
  },
  async fetOrderList() {
    const that = this
    const _tab = that.data.tabs.findIndex(item => item.value === that.data.active)
    const temp = that.data.originScrollViewData[_tab]

    if (Object.prototype.toString.call(temp) !== '[object Object]') {
      return
    }

    if (temp.finished) {
      return
    }

    if (temp.isFetchLock) {
      return
    }

    that.setData({
      ['originScrollViewData[' + _tab + '].isFetchLock']: true,
      ['originScrollViewData[' + _tab + '].pageNum']: temp.pageNum + 1
    })
    try {
      const { status, data, msg } = await getOrderList({
        pageNum: that.data.originScrollViewData[_tab].pageNum,
        pageSize: that.data.pageSize,
        type: that.data.tabs[_tab].value
      })
      if (status) {
        const { list } = data
        if (Array.isArray(list)) {
          const arr = list.map(item => {
            return {
              ...item,
              created_at: item.created_at.replace(/(.*)(:\d{2})/, '$1')
            }
          })
          const _list = temp.isRefresh
            ? [].concat(arr)
            : that.data.originScrollViewData[_tab].list.concat(arr)

          that.setData({
            ['originScrollViewData[' + _tab + '].list']: _list,
            ['originScrollViewData[' + _tab + '].finished']: list.length < 10,
            ['originScrollViewData[' + _tab + '].isRefresh']: false,
            ['originScrollViewData[' + _tab + '].isFetchLock']: false,
            ['originScrollViewData[' + _tab + '].isFirst']: false
          })
        }
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (e) {}
    if (that.freshing) {
      that.freshing = false
    }
  },
  onRefresh(e) {
    const { dy } = e.detail
    if (dy < this.data.refresherThreshold || this.freshing) {
      return
    }
    const _tab = this.data.tabs.findIndex(item => item.value === this.data.active)
    this.freshing = true
    // 这里设置延时的目的：页面数据不足一屏时，更好的展示下拉刷新动画
    this.timer = setTimeout(() => {
      clearTimeout(this.timer)
      this.setData({
        ['originScrollViewData[' + _tab + '].pageNum']: 0,
        pageSize: 20,
        ['originScrollViewData[' + _tab + '].finished']: false,
        ['originScrollViewData[' + _tab + '].isRefresh']: true,
        ['originScrollViewData[' + _tab + '].isFetchLock']: false
      }, () => {
        this.fetOrderList()
      })
    }, 1000)
  },
  showDeleteOrder(e) {
    const { item } = e.currentTarget.dataset

    this.setData({
      booDeleteOrder: true,
      itemData: item
    })
  },
  hideDeleteOrder() {
    this.setData({
      booDeleteOrder: false,
      itemData: {}
    })
  },
  async confirmDeleteOrder() {
    const { id } = this.data.itemData

    this.setData({
      booLock: true
    })
    try {
      const { status, msg } = await postOrderDelete(id)
      let _msg = ''
      if (status) {
        _msg = '订单删除成功'
        // 更新全部：去除各个列表中有相同id的
        const originScrollViewData = this.data.originScrollViewData
        for (let i = 0; i < originScrollViewData.length; i++) {
          const _list = originScrollViewData[i].list
          const _delIndex = _list.findIndex(item => item.id === id)
          if (_delIndex > -1) {
            _list.splice(_delIndex, 1)
            this.setData({
              ['originScrollViewData[' + i + '].list']: _list
            })
          }
        }

        this.hideDeleteOrder()
      } else {
        _msg = msg
      }
      wx.showToast({
        title: _msg,
        icon: 'none'
      })
    } catch (err) {}
    this.setData({
      booLock: false
    })
  },
  showPayment(e) {
    const { item } = e.currentTarget.dataset

    this.setData({
      itemData: item,
      booPayment: true
    })
  },
  hidePayment() {
    this.setData({
      booPayment: false,
      itemData: {}
    })
  },
  async handleOrderDiffPay() {
    const { order_number, id } = this.data.itemData

    this.setData({
      booLock: true
    })

    try {
      const { status, data, msg } = await postOrderDiffPay(order_number)
      if (status) {
        const { time_stamp, nonce_str, sign_type, pay_sign } = data.pay_data
        wx.requestPayment({
          timeStamp: time_stamp,
          nonceStr: nonce_str,
          package: data.pay_data.package,
          signType: sign_type,
          paySign: pay_sign,
          success(res) {
            if (res.errMsg === 'requestPayment:ok') {
              wx.redirectTo({
                url: '/pages/orderDetail/orderDetail?orderId=' + id
              })
            } else {
              wx.showToast({
                title: '支付出错，请重试~',
                icon: 'none'
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (err) {}
    this.setData({
      booLock: false
    })
  },
  showCancelOrder(e) {
    const { item } = e.currentTarget.dataset

    this.setData({
      itemData: item,
      booCancelOrder: true
    })
  },
  hideCancelOrder() {
    this.setData({
      booCancelOrder: false,
      itemData: {}
    })
  },
  async confirmCancelOrder() {
    const { id } = this.data.itemData
    this.setData({
      booLock: true
    })
    try {
      const { status, msg } = await postOrderCancel(id)
      if (status) {
        this.hideCancelOrder()
        wx.redirectTo({
          url: '/pages/orderCancel/orderCancel?orderId=' + id
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (err) {}
    this.setData({
      booLock: false
    })
  }
})
