<template>
  <span class="fx-row fx-cen-cen f-red f20">{{ countdownDisplay }}</span>
</template>

<script>
import paperMixin from '../mx-paper-mixin'

export default {
  // NOTE: 一道题只能放一个timer插件，使用时请注意
  mixins: [paperMixin],
  name: 'plus-paper-countdown',
  data() {
    return {
      timer: null
    }
  },
  watch: {
    paper: {
      immediate: true,
      handler: function() {
        this.ensureTimer()
      }
    }
  },
  beforeDestroy() {
    this.releaseTimer()
  },
  methods: {
    ensureTimer() {
      this.releaseTimer()
      if (this.allowAnswer) {
        if (this.paper.remaining > 0) {
          // start timer
          this.timer = setInterval(() => {
            if (this.paper.remaining <= 0) {
              this.releaseTimer()
              this.paperTimeUpAction()
              return
            }
            this.paper.remaining -= 1
          }, 1000)
        } else {
          // trigger auto commit
          this.paperTimeUpAction()
        }
      }
    },
    releaseTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  }
}
</script>

<style scoped>

</style>
