// pages/order/addcustom/addcustom.js
let util = require('../../../utils/util.js');
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    createUser: '',
    name: '',
    tel: '',
    level: '0',
    levels: [{
      name: '普通用户',
      value: 1
    }, {
      name: '高级用户',
      value: 2
    }],
    levelindex: 0
  },
  levelChange(e) {
    this.setData({
      levelindex: e.detail.value,
      level: this.data.levels[e.detail.value].value
    })
  },
  setname(e) {
    this.setData({
      name: e.detail.value
    })
  },
  settel(e) {
    this.setData({
      tel: e.detail.value
    })
  },
  save() {
    if (!this.data.name) {
      util.showToast('请填写客户姓名')
      return
    }
    var url = 'customer/wxapi/create'
    var param = {
      name: this.data.name,
      tel: this.data.tel,
      customerLevel: this.data.level
    }
    if (this.data.id) {
      url = 'customer/wxapi/update'
      this.data.olddata.name = this.data.name
      this.data.olddata.tel = this.data.tel
      this.data.olddata.customerLevel = this.data.level
      param = this.data.olddata
    }
    util.query(url, param, function(res) {
      if (res.code === 10000) {
        util.showToast("保存成功")
        setTimeout(function() {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      } else {
        util.showToast('保存失败')
      }
    }, 'POST')
  },
  getData(id) {
    util.query('customer/wxapi/findbyid?id=' + id, {}, function(e) {
      if (e.code === 10000) {
        var levelindex = 0
        for (var i = 0; i < that.data.levels.length; i++) {
          if (that.data.levels[i].value + '' === e.data.customerLevel) {
            levelindex = i
            break
          }
        }

        that.setData({
          olddata: e.data,
          id: e.data.id,
          onlyID: e.data.onlyID,
          name: e.data.name,
          tel: e.data.tel,
          levelindex: levelindex,
          level: e.data.customerLevel,
          createUser: e.data.userName
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    if (options.id) {
      this.getData(options.id)
    } else {
      var ui = wx.getStorageSync('userinfo')
      if (ui) {
        this.setData({
          createUser: ui.wechatName
        })
      }
    }

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})