const { isMobile } = require('../../utils/validate')
const { sendCode, miniPhoneLogin, miniLogin } = require('../../api/common')
const { login, sessionStorageKey } = require('../../api/request')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {
      cellphone: '',
      code: ''
    },
    numCount: 60,
    checked: false,
    booLock: false
  },
  timer: null,
  wxCode: '',

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

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

  },

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

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.timer)
  },
  bindTip() {
    wx.showToast({
      title: '请阅读并勾选协议',
      icon: 'none'
    })
  },
  bindChange() {
    this.setData({
      checked: !(this.data.checked)
    })
  },
  mobileEventhandle(e) {
    const val = e.detail.value.replace(/[^\d]$/, '').replace(/^0/, '').replace(/(\d{11}(.*))/, '$1')

    this.setData({
      'form.cellphone': val
    })

    return {
      value: val
    }
  },
  codeEventhandle(e) {
    const val = e.detail.value.replace(/[^\d]$/, '').replace(/(\d{6}(.*))/, '$1')

    this.setData({
      'form.code': val
    })

    return {
      value: val
    }
  },
  funCutDown() {
    let numCount = this.data.numCount
    this.timer = setInterval(() => {
      if (numCount === 0) {
        clearInterval(this.timer)
        this.setData({
          numCount: 0
        })
        return
      }
      numCount--
      this.setData({
        numCount: numCount
      })
    }, 1000)
  },
  async funGetCode() {
    const numCount = this.data.numCount
    const { cellphone } = this.data.form

    if (!isMobile(cellphone)) {
      wx.showToast({
        title: '请输入正确的手机号~',
        icon: 'none'
      })
      return
    }
    if (numCount < 60 && numCount > 0) {
      return
    }
    this.setData({
      numCount: 60,
      code: ''
    })

    this.funCutDown()

    try {
      const { status } = await sendCode({ phone: cellphone, type: 1 })
      let title = '验证码发送成功'
      if (status) {
      } else {
        title = '验证码发送失败'
      }
      wx.showToast({
        title: title,
        icon: 'none'
      })
    } catch (err) {}
  },
  async bindEvent() {
    const { cellphone, code } = this.data.form

    if (!this.data.checked) {
      this.bindTip()
      return
    }
    this.setData({
      booLock: true
    })

    try {
      const { status, data } = await miniPhoneLogin({
        wxCode: this.wxCode,
        cellphone,
        code
      })

      if (status) {
        try {
          wx.setStorageSync(sessionStorageKey, data.token)
        } catch (err) {}

        await app.fetchUserData()

        const pages = getCurrentPages()
        if (pages.length > 1) {
          const route = pages[pages.length - 2]
          wx.navigateBack({
            delta: 1
          })
          route.bindCallBack && route.bindCallBack()
        }
      } else {
        wx.showToast({
          title: '登录出错了，请重试',
          icon: 'none'
        })
        this.getWxCode()
      }
    } catch (err) {
      this.getWxCode()
    }

    this.setData({
      booLock: false
    })
  },
  async getPhoneNumber(e) {
    const { errMsg, encryptedData, iv } = e.detail
    if (errMsg === 'getPhoneNumber:ok') {
      this.setData({
        booLock: true
      })

      try {
        const { status, data } = await miniLogin({
          wxCode: this.wxCode,
          encryptedData,
          iv
        })
        if (status) {
          try {
            wx.setStorageSync(sessionStorageKey, data.token)
          } catch (err) {}

          await app.fetchUserData()

          const pages = getCurrentPages()
          if (pages.length > 1) {
            const route = pages[pages.length - 2]
            wx.navigateBack({
              delta: 1
            })
            route.bindCallBack && route.bindCallBack()
          }
        } else {
          wx.showToast({
            title: '登录出错了，请重试',
            icon: 'none'
          })
          this.getWxCode()
        }
      } catch (e) {
        this.getWxCode()
      }

      this.setData({
        booLock: false
      })
    }
  },
  async getWxCode() {
    try {
      this.wxCode = await login()
    } catch (e) {}
  }
})
