// pages/paySuccess/paySuccess.js
import { get, post } from '../../utils/http'
import { $wuxCountDown } from '../../components/dist/index'
import { PROJECT_TYPE } from '../../utils/global'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: 0,
    orderData: {},
    isMember: -1,
    source: '', //订单类型，project项目订单，product升级产品订单，goods美妆产品订单，默认project
    orderType: '', // 接口返回的订单类型
    recommendList: [],
    productList: [],
    seconds: 0, // 倒计时秒数
    countdownStr: '', // 倒计时字符串
    takeOutTime: '', //  取货截止时间
    tips: {
      show_tips: 0,
      project: ['您的预约单已生效，请准时到店体验'],
      product: ['您的预约单已生效，请准时到店体验'],
      goods: ['您的预约单已生效', '请于_TIME_OUT_之前']
    },
    mainOrderId: -1, // 主订单ID
    selectProductData: null // 选中的新人推荐项目升级产品
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.setData(
      {
        orderId: options.order_id,
        source: options.source || 'project',
        isMember:
          getApp().globalData.userInfo && getApp().globalData.userInfo.is_vip
            ? getApp().globalData.userInfo.is_vip
            : 0
      },
      () => {
        if(options.source === 'secondaryCard'){
          this.setData({
            orderType: options.source
          })
          return
        }
        that.getOrderSuccess(options.order_id)
      }
    )
  },

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

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

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

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.c1) this.c1.stop()
  },

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  /**
   * 获取订单信息
   * @param {*} order_id
   */
  getOrderSuccess(order_id) {
    let that = this
    let { source } = this.data
    if (source == 'product_with_project_order') {
      source = 'product'
    }
    get(
      'api/order/success',
      {
        order_id,
        order_type: source
      },
      (res) => {
        let orderData = res.data

        this.setData(
          {
            orderData: orderData,
            productList: orderData.product_list,
            recommendList: orderData.recommend_list,
            takeOutTime: orderData.take_out_time,
            seconds: orderData.seconds,
            orderType: orderData.type,
            mainOrderId: orderData.main_order_id
          },
          () => {
            that.c1 = new $wuxCountDown({
              date: +new Date() + orderData.seconds * 1000,
              render(date) {
                const hours = this.leadingZeros(date.hours, 2)
                const min = this.leadingZeros(date.min, 2)
                const sec = this.leadingZeros(date.sec, 2)
                that.setData({ countdownStr: `${hours}:${min}:${sec}` })
              },
              onEnd() {
                that.c1.stop()
                // that.getOrderDetail(that.data.orderId)
              }
            })
          }
        )
        console.log(res)
      }
    )
  },

  /**
   * 跳转订单详情
   */
  gotoOrderDetail() {
    let { orderType, orderId, mainOrderId } = this.data
    let _orderId = mainOrderId ? mainOrderId : orderId
    let url = `/pages/orderDetail/orderDetail?source=${orderType}&id=${_orderId}`
    if (['goods', 'cardgoods'].indexOf(orderType) > -1) {
      url = `/pages/goods/orderDetail/orderDetail?source=${orderType}&id=${_orderId}`
    }
    if(['secondaryCard'].indexOf(orderType) > -1){
      url = `/subPackages/pages/cardBag/cardBag`
    }
    wx.navigateTo({
      url: url
    })
  },

  /**
   * 跳转首页
   */
  gotoHome() {
    wx.switchTab({
      url: '/pages/home/home'
    })
  },

  /**
   * 跳转至项目耗材详情页
   */
  gotoProductDetail(e) {
    let item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/projectDetail/projectDetail?source=product&project_id=${item.product_id}`
    })
  },

  /**
   * 跳转至推荐详情页
   */
  gotoRecommendDetail(e) {
    let { source } = this.data
    let item = e.currentTarget.dataset.item
    if (source == 'product_with_project_order') {
      source = 'product'
    }
    wx.navigateTo({
      url: `/pages/projectDetail/projectDetail?source=${source}&project_id=${item.id}`
    })
  },

  /**
   * 勾选了新人推荐产品
   */
  selectProjectProduct(e) {
    let { selectProductData } = this.data
    let item = e.currentTarget.dataset.item
    if (selectProductData && selectProductData.product_id == item.product_id) {
      this.setData({ selectProductData: null })
      return
    }
    this.setData({ selectProductData: item })
  },
  /**
   * 选中新人福利推荐的项目升级产品
   */
  addProductOrder() {
    let { selectProductData } = this.data
    if (!selectProductData) {
      wx.showToast({
        title: '请先选择升级产品',
        icon: 'none'
      })
      return
    }
    let source = 'product'
    let sourceType = PROJECT_TYPE[source]
    get(
      'api/product/info',
      {
        store_id: wx.getStorageSync('store_id'),
        product_id: selectProductData.product_id,
        type: sourceType
      },
      (res) => {
        // 正常应该直接传入selectProductData，但是接口参数不齐，所以调用一次详情接口
        wx.navigateTo({
          url: `/pages/reserveProduct/reserveProduct?source=${source}&productData=${encodeURIComponent(
            JSON.stringify(res.data)
          )}`
        })
      }
    )
  }
})
