<template>
  <el-input
    v-model="input"
    :disabled="isSendDisable"
    type="text"
    placeholder="验证码"
    :style="{ width: width }"
  >
    <el-button
      slot="suffix"
      size="mini"
      :disabled="isSendDisable || isSendCode"
      @click="sendCode"
    >{{sendBtnText}}</el-button>
  </el-input>
</template>

<script>
import Login from '@/pages/login/components/action/index.js'
export default {
  name: 'sendCode',
  props: {
    defaultValue: {
      default: ''
    },
    width: {
      type: String,
      default: '80%'
    },
    isSendDisable: {
      type: Boolean,
      default: true
    },
    ruleForm: {}
  },
  data() {
    return {
      isSendCode: false,
      sendBtnText: '发送验证码',
      phone: null
    }
  },
  computed: {
    input: {
      get() {
        return this.defaultValue
      },
      set(val) {
        this.$emit('input', val, this.$attrs.querykey)
      }
    }
  },
  watch: {
    ruleForm(form) {
      this.phone = form.account
    }
  },
  methods: {
    clearTime() {
      this.isSendCode = true
      this.sendBtnText = '发送验证码'
      clearInterval(this.timeInterval)
    },
    sendCode() {
      if (!this.isSendCode) {
        const params = {
          account: this.phone,
          service: 'https://cu.ezijing.com'
        }
        Login.sendCode(params)
          .then(res => {
            if (res.code === 0) {
              let time = 60
              this.isSendCode = true
              this.sendBtnText = '60s后重发'
              this.timeInterval = setInterval(() => {
                if (time-- > 0) {
                  this.sendBtnText = time + 's后重发'
                } else {
                  this.isSendCode = false
                  this.sendBtnText = '发送验证码'
                  clearInterval(this.timeInterval)
                }
              }, 1000)
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(e => {})
      }
    }
  },
  beforeDestroy() {
    /* 清空倒计时 */ this.clearTime()
  }
}
</script>

<style>
</style>
