<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      width="700px"
      :title="modalTitle"
    >
      <div>
        <Form :label-width="80" inline>
          <Form-item label="邮箱：" style="width: 75%;">
            <el-input v-model="email" name="email" placeholder="请输入邮箱" clearable/>
          </Form-item>
          <Form-item label="验证码：" style="width: 75%;">
            <el-input v-model="code" name="code" placeholder="请输入验证码" clearable/>
          </Form-item>
          <Form-item class="search-btn">
            <div v-show="selected" class="blue-btn" @click="_getCode">
              获取验证码
            </div>
            <div v-show="!selected" class="blue-btn btn-disabled">
              {{ second }}s后重新获取
            </div>
          </Form-item>
        </Form>
      </div>
      <div slot="footer" class="btn-width">
        <el-button style="margin-left: 8px" @click="_cancel">
          取消
        </el-button>
        <el-button type="primary" @click="_ok">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sysEmail } from '../../../api'
export default {
  data() {
    return {
      showModal: false,
      modalTitle: '',
      selected: true,
      second: '59',
      email: '',
      code: '',
      id: ''
    }
  },
  methods: {
    _open() {
      this.showModal = true
      this.code = ''
      this.second = 59
      this.selected = true
      this.email = ''
      this.modalTitle = '修改邮箱'
    },
    _val() {
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (this.email === '') {
        this.$message.warning('请填写邮箱')
        return false
      } else if (!reg.test(this.email)) {
        this.$message.warning('邮箱格式不正确')
        return false
      } else {
        return true
      }
    },
    _ok: async function() {
      const result = await sysEmail.bindEmail(this.code)
      if (result) {
        this.$message.success('验证成功')
        this.showModal = false
        this.$emit('on-result-change')
      }
    },
    _getCode: async function() {
      if (this._val()) {
        this.selected = false
        this.second = 59
        this._count()
        const result = await sysEmail.getCode({ email: this.email })
        if (result) {
          this.$message.success({
            content: '验证码已发送,请到邮箱查看！',
            duration: 5
          })
        }
      }
    },
    _count() {
      const second = this.second
      if (second === 0) {
        this.selected = true
        this.second = 59
        return
      }
      setTimeout(() => {
        this.second = second - 1
        this._count()
      }, 1000)
    },
    _cancel() {
      this.showModal = false
    }
  }
}
</script>

<style scoped>
</style>
