<template>
  <el-button :disabled="leftTime > 0 && leftTime < 60" @click="send">{{ text }}</el-button>
</template>
<script>
import { sendSmsCode } from '@/api/order'
export default {
  props: {
    orderId: [String, Number],
    scene: [String, Number]
  },
  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() {
      if (this.loading || (this.leftTime > 0 && this.leftTime < 60)) return false
      this.loading = true
      sendSmsCode({
        orderId: this.orderId,
        scene: this.scene
      }).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>
