<template>
  <div v-if="code">
    <lx-button v-if='countdown' bg='#fff' color='#1890FF'>{{timeLeft}}s后可重发</lx-button>
    <lx-button v-else @click='getCode' bg='#fff' color='#1890FF'>获取验证码</lx-button>
  </div>
  <div v-else>
    <lx-button bg='#fff' color='#1890FF'>{{timeLeft}}s</lx-button>
  </div>
</template>

<script>
  export default {
    name: 'lxCountdown',
    props: {
      time: {
        type: Number,
        default: 3
      },
      start: Boolean,
      code: Boolean,

    },
    data () {
      return {
        timeLeft: this.time,
        msg: '获取验证码',
        countdown: false,
      }
    },
    mounted() {
      if (this.start) {
        this.getCode()
      }
    },
    methods: {
      getCode() {
        this.countdown = true
        this.timeLeft = this.time
        let timer = setInterval(() => {
          if (this.timeLeft > 0) {
            this.timeLeft--
          } else {
            clearInterval(timer)
            this.countdown = false
            this.$emit('timeEnd')
          }
        }, 1000)
      }
    },
  }
</script>

