const {
  api,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  authAgainByUser,
  userLocation
} = require('../../lib/util.js')
const qrcode = require('../../lib/qrcode.js')
Page({
  data: {
    userList: [],
    addUserShow: false,
    email: '',
    promtFalse: {
      title: '还没有紧急联系号码！',
      buttons: [{
        text: '添加一个',
      }],
    },
    actions: [{
        name: '删除',
        color: '#fff',
        fontsize: '16',
        width: 60,
        icon: 'trash',
        background: '#ed3f14'
      },
      {
        name: '取消',
        width: 60,
        color: '#80848f',
        fontsize: '16',
        icon: 'undo'
      }
    ]
  },
  onLoad: function() {
    let userList = wx.getStorageSync('user').userMapp.email
    if (userList) {
      userList = userList.split(',')
      this.setData({
        userList
      })
    }
  },
  onShow: function() {},
  addUser() {
    this.setData({
      addUserShow: true
    })
  },
  handleClose2() {
    this.setData({
      addUserShow: false
    })
  },

  phoneInput(e) {
    this.setData({
      email: e.detail.value
    })
  },
  apiAddUser() {
    let {
      email,
      userList
    } = this.data
    let newUserList = [...userList]
    newUserList.push(email)
    email = newUserList.join(',')
    api.post('user/editInfo', {
        email
      })
      .then(res => {
        this.setData({
          userList: newUserList,
          email: '',
          addUserShow: false
        })
        let user = wx.getStorageSync('user')
        user.userMapp.email = email
        wx.setStorageSync('user', user)
        alertTip('添加成功')
      })
      .catch(err => {
        alertTip(err)
      })
  },
  actionsClick(e) {
    if (e.detail.index === 0) {
      const id = e.target.id
      this.removeUser(id)
    }
  },
  getUserList() {
    api.get('user/getAssistantUser')
      .then(res => {
        console.log('res:', res)
        this.setData({
          userList: res.items
        })
      })
      .catch(err => {
        alertTip(err)
      })
  },
  removeUser(email) {
    let that = this
    let userList = this.data.userList.filter(elt => elt != email)
    email = userList.join(',')
    console.log(userList, email)
    wx.showModal({
      title: '警告',
      content: '确定删除该紧急联系人',
      success: function(res) {
        if (res.confirm) {
          api.post('user/editInfo', {
              email
            })
            .then(res => {
              let user = wx.getStorageSync('user')
              user.userMapp.email = email
              wx.setStorageSync('user', user)
              that.setData({
                userList,
                email
              })
            })
            .catch(err => {
              alertTip(err)
            })
        }
      }
    })
  }
})