<!--
      descript: input-txt 组件
        author: jankergg
        param: props
        example:
-->
<template>
   <!-- input 类型 -->
  <div class="input-countdown-box">
    <root-input
    :formModel="formModel"
    :index="index"
    :showExtra="true"
    :name="name">
      <button class="countdown-btn" :disabled="btnDisabled" @click="btnClick">{{cdText}}</button>
    </root-input>
  </div>
</template>
<script>
import rootInput from './input'
import inputMixin from './mixin/input-mixin'
export default {
  name: 'za-input-countdown',
  data () {
    return {
      btnDisabled: this.formModel.rules.btnDisabled === undefined ? !!this.formModel.rules.readOnly || !!this.formModel.rules.disabled : this.formModel.rules.btnDisabled,
      time: +this.formModel.rules.extra.time || 60,
      cdText: this.formModel.rules.extra.countdown || '获取验证码',
      timer: null
    }
  },
  props: {
    index: [String, Number],
    name: String,
    formModel: Object
  },
  mixins: [inputMixin],
  watch: {
    ['formModel.rules.btnDisabled'] (v) {
      this.$set(this, 'btnDisabled', v)
    }
  },
  methods: {
    btnClick () {
      if(!this.btnDisabled){
        this.onEvent('onclick', {
          name: this.name,
          event: null,
          type: 'click',
          triggerType: 'onclick',
          value: this.cdText
        })
        this.countDown()
      }
    },
    countDown() {
      if(this.time === 0) {
        this.btnDisabled = false
        this.time = +this.formModel.rules.extra.time || 60
        this.cdText = this.formModel.rules.extra.countdown || '获取验证码'
        this.$nextTick(() => {
          this.onEvent('countdown', {
            name: this.name,
            event: null,
            type: 'over',
            triggerType: 'over',
            value: this.time
          })
        })
        clearTimeout(this.timer)
        return
      }
      this.cdText = this.time + 's后重试'
      this.btnDisabled = true
      this.timer = setTimeout(() => {
        this.time--
        this.countDown()
      }, 1000)
    }
  },
  components: {
    rootInput
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
.input-countdown-box{
  .input-extra{
    height: 24px;
    margin-left: 15px;
    padding-left: 15px !important;
    position: relative;
    &::before{
      content: "";
      width: 1px;
      height: 100%;
      background-color: #D9D9D9;
      position: absolute;
      left: 0;
    }
    .countdown-btn{
      min-width: 74px;
      line-height: 24px;
      font-size: 14px;
      display: block;
      background: none;
      border: 0 none;
    }
  }
}
</style>
