<template>
  <div class="input-ver">
    <el-input v-model="code" @change="$emit('change', code)" placeholder="请输入验证码"></el-input>
    <el-button :class="{grey: running}" type="text" @click="run">{{text}}</el-button>
  </div>
</template>

<script>
let time = 60
let text = '获取验证码'
let interval

export default {
  data() {
    return {
      // 验证码
      code: '',
      time: time + 1,
      running: false,
    }
  },
  computed: {
    text() {
      if(this.time < 1 || this.time > time) {
        this.running = false
        if(this.time < 1) {
          clearInterval(interval)
          this.time = time + 1
          this.running = false
        }
        return text
      }
      return `重新获取(${this.time}s)`
    }
  },
  mounted() {

  },
  methods: {
    run() {
      if(this.running) return
      this.$emit('click', () => {
        this.running = true
        this.time--
        interval = setInterval(() => {
          this.time--
        }, 1000)
      })
    },
  }
}
</script>

<style scoped>
.input-ver {
  position: relative;
}
.el-button {
  position: absolute;
  top: 0;
  right: 10px;
}
.grey {
  color: #909399;
}
</style>
