<template>
  <div class="f-main">
    <div class="content-top">
      <p>验证邮箱</p>
    </div>
    <div class="f-form">
      <div class="page-part">
        <mt-field placeholder="新邮箱地址"
                  v-model="valid.email"
                  :state="state.email"
                  @blur.native.capture="validateEmail"
        ></mt-field>
      </div>
      <div class="page-part">
        <mt-button :disabled="hasSend" size="large"
                   type="primary"
                   @click="sureAccount()"
                   v-text="secretEmail">发送验证请求</mt-button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'step-one',
    props: ['tokenId'],
    data () {
      return {
        state: {
          email: 'error'
        },
        valid: {
          email: ''
        },
        secretEmail: '发送验证请求',
        hasSend: false
      }
    },
    methods: {
      // 弹窗处理
      downToast (type) {
        this.$toast({
          message: type,
          iconClass: 'el-icon-warning'
        })
      },
      // 验证邮箱号
      validateEmail () {
        let reg = /@/
        if (!this.valid.email) {
          this.downToast('请先填写邮箱号')
          this.state.email = 'error'
        } else {
          if (!reg.test(this.valid.email)) {
            this.downToast('请填写正确的邮箱号')
            this.state.email = 'warning'
          } else {
            this.state.email = 'success'
          }
        }
      },
      sureAccount () {
        if (this.state.email !== 'success') {
          this.downToast('请确认填写是否有误')
        } else {
          this.$indicator.open('发送过程中...')
          this.$http.get(`/update/user/setEmail`, {params: {email: this.valid.email, token: this.tokenId ? this.tokenId : this.$route.query.token, url: window.location.href}})
            .then(response => {
              this.$indicator.close()
              if (response.data.success) {
                this.hasSend = true
                this.secretEmail = '已发送验证邮件，请查收'
              } else {
                this.hasSend = false
                this.downToast(response.data.errMsg)
              }
            }).catch((err) => {
              this.$indicator.close()
              this.downToast(err.errMsg)
            })
        }
      }
    }
  }
</script>
