<template>
  <el-input placeholder="请输入验证码" :value ="value" @input ="input">
    <el-button slot ="append" @click ="pushMsg" :disabled="disabled">发送验证码{{timer|showTimer}}</el-button>
  </el-input>
</template>
<script>
  export default {
    computed: {
      disabled () {
        if (this.hasPhone) {
          if (this.phone.trim().length === 0) {
            return true
          }
          if (this.timer > 0) {
            return true
          }
          return false
        }
        if (this.timer > 0) {
          return true
        }
        return false
  
      }
    },
    filters: {
      showTimer (timer) {
        if (timer > 0) {
          return `(${timer})`
        } return ''
      }
    },
    data () {
      return {
        code: '',
        timer: 0
      }
    },
    props: {
      value: {
        default: '',
        type: String
      },
      hasPhone: Boolean,
      phone: {
        type: String,
        default: ''
      }
    },
    methods: {
      input (code) {
        this.$emit('input', code)
      },
      pushMsg () {
        if (this.hasPhone) {
          this.$http.get('/msgs/codes', {
            params: {
              phone: this.phone
            }
          }).then((res) => {
            this.startTimer()
          }).catch((res) => {
            this.$message.error('短信发送失败，请检查您的输入')
          })
        } else {
          this.$http.get('/users/authMessages').then((res) => {
            this.startTimer()
          }).catch((res) => {
            this.$message.error('短信发送失败')
          })
        }
      },
      startTimer () {
        this.timer = 60
        let self = this
  
        function timer () {
          if (self.timer > 0) {
            setTimeout(() => {
              self.timer--
              timer()
            }, 1000)
          }
        }
        timer()
      }
    }
  }
</script>
