<template>
  <article
    class="verifyCode"
    @click.stop="getCode"
  >
    <div
      v-for="i in 12"
      v-show="show"
      :key="i"
      class="weui_loading_leaf"
      :class="['weui_loading_leaf_' + (i-1)]"
    />
    <span>{{ codeText }}</span>
  </article>
</template>
<script>
export default {
  props: {
    value: {
      type: Object,
      default() {
        return {
          show: false,
          time: 60,
          start: false,
          codeText: ''
        }
      }
    }
  },
  data() {
    return {
      show: false,
      interval: null,
      time: 60,
      start: false,
      codeText: '',
      text: ''
    }
  },
  watch: {
    'value.show' (val) {
      this.show = val
    },
    'value.time' (val) {
      this.time = val
    },
    'value.start' (val) {
      this.start = val
    },
    'value.codeText' (val) {
      this.codeText = val
    },
    show(val) {
      let options = {
        show: val,
        time: this.time,
        start: this.start,
        codeText: this.codeText
      }
      this.$emit('input', options)
    },
    codeText(val) {
      let options = {
        show: this.show,
        time: this.time,
        start: this.start,
        codeText: val
      }
      this.$emit('input', options)
    },
    time(val) {
      let options = {
        show: this.show,
        time: val,
        start: this.start,
        codeText: this.codeText
      }
      this.$emit('input', options)
    },
    start(newVal, oldVal) {
      if (newVal === true && oldVal === false && this.time > 0) {
        this.tick()
      }
      if (newVal === false && oldVal === true) {
        this.stop()
      }
      let options = {
        show: this.show,
        time: this.time,
        start: newVal,
        codeText: this.codeText
      }
      this.$emit('input', options)
    }
  },
  created() {
    this.show = this.value.show
    this.time = this.value.time
    this.start = this.value.start
    this.text = this.codeText = this.value.codeText
    if (this.start) {
      this.tick()
    }
  },
  methods: {
    getCode() {
      if (this.interval !== null) {
        return false
      }
      this.$emit('on-getCode')
    },
    tick() {
      let seconds = this.time
      this.show = false
      this.codeText = `剩余: ${seconds} 秒`
      this.interval = setInterval(() => {
        if (seconds-- > 0) {
          this.codeText = `剩余: ${seconds} 秒`
        } else {
          this.stop()
        }
      }, 1000)
    },
    stop() {
      this.codeText = this.text
      clearInterval(this.interval)
      this.interval = null
      this.start = false
    }
  }
}
</script>
