<template>
  <el-dropdown @command="send" :disabled="leftTime > 0 && leftTime < 60">
      <el-button type="primary">
        {{ text }}<i class="el-icon-arrow-down el-icon--right"></i>
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="1">SMS</el-dropdown-item>
        <el-dropdown-item command="2">WhatsApp</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
</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(messageType) {
      if (this.loading || (this.leftTime > 0 && this.leftTime < 60)) return false
      this.loading = true
      this.form['messageType'] = messageType
      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>
