<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 { sendSmsCode } from '@/api/order'
export default {
  props: {
    form: Object
  },
  data() {
    return {
      leftTime: 60,
      loading: false,
      timeout: null
    }
  },
  computed: {
    text() {
      if (this.leftTime === 60) {
        return this.$t('sendSmsCode.send')
      }
      if (this.leftTime > 0) {
        return this.leftTime + this.$t('sendSmsCode.seconds')
      }
      return this.$t('sendSmsCode.again')
    }
  },
  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
      sendSmsCode(this.form).then(res => {
        this.$message.success(this.$t('sendSmsCode.success'))
        this.countDown()
      }).finally(res => {
        this.loading = false
      })
    },
    countDown() {
      this.leftTime--
      if (this.leftTime <= 0) {
        return false
      }
      this.timeout = setTimeout(this.countDown, 1000)
    }
  }
}
</script>
