<template>
  <el-button :disabled="leftTime > 0 && leftTime < 60" @click="send">{{ text }}</el-button>
</template>
<script>
import { getCode } from '@/api/user'
export default {
  props: {
    form: Object
  },
  data() {
    return {
      leftTime: 60,
      loading: false,
      timeout: null
    }
  },
  computed: {
    text() {
      if (this.leftTime === 60) {
        return this.$t('setting.getCode')
      }
      if (this.leftTime > 0) {
        return this.leftTime + this.$t('sendSmsCode.seconds')
      }
      return this.$t('setting.getCode')
    }
  },
  destroyed() {
    if (this.timeout)clearTimeout(this.timeout)
  },
  methods: {
    send() {
      if (this.loading || (this.leftTime > 0 && this.leftTime < 60)) return false
      this.loading = true
      getCode(this.form).then(() => {
        this.$message({
          message: this.$t('common.success'),
          type: 'success'
        })
        this.countDown()
      }).finally(res => {
        this.loading = false
      })
    },
    countDown() {
      this.leftTime--
      if (this.leftTime <= 0) {
        return false
      }
      this.timeout = setTimeout(this.countDown, 1000)
    }
  }
}
</script>
