var util = require('../../utils/util.js');
var api = require('../../config/api.js');
let referCode = 0
// pages/graveDetail/graveDetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    currentSize: 0,
    phoneTypes: ['853', '852', '86'],
    name: '',
    email: '',
    phone: '',
    desc: '',
    statusMap: ['現貨', '已預定', '已售', '現貨', '預售', '轉售', '已下架'],
    detail: {}
  },

  bindIndexChange(val) {
    this.setData({index: val.detail.value})
  },

  bindDescChange(val) {
    this.setData({
      currentSize: val.detail.value.length > 50 ? 50 : val.detail.value.length,
      desc: val.detail.value
    })
  },

  bindNameChange(val) {
    this.setData({
      name: val.detail.value
    })
  },
  bindPhoneChange(val) {
    this.setData({
      phone: val.detail.value
    })
  },
  bindEmailChange(val) {
    this.setData({
      email: val.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let res = await util.request(api.BoxDetail, {id: options.boxId}, 'GET')

    console.log(res.data)
    this.setData({
      detail: res.data
    })
  },

  async submit() {
    if (!this.data.name.trim().length) {
      return wx.showToast({
        icon: 'none',
        title: '請輸入您的姓名',
      })
    } else if (!this.data.email.trim().length) {
      return wx.showToast({
        icon: 'none',
        title: '請輸入您的常用郵箱',
      })
    } else if (!this.data.phone.trim().length) {
      return wx.showToast({
        icon: 'none',
        title: '請輸入您的手機號碼',
      })
    }

    let options = {
      boxUserName: this.data.name,
      boxUserPhone: this.data.phone,
      boxUserRemark: this.data.desc,
      boxUserEmail: this.data.email,
      phonePlaceCode: this.data.phoneTypes[this.data.index],
      boxSn: this.data.detail.boxSn
    }

    let res = await util.request(api.BoxSubmitOrder, options, 'POST', 'application/json')
    if (res.code === 0) {
      wx.showToast({
        title: '預訂成功',
        icon: 'success'
      })

      getApp().callOrderBuyCbs({referCode: referCode++})

      wx.navigateBack()
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
    
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})