<template>
  <div class="verification-code">
    <div v-if="codeStatus" class="time">{{ codeTime }}s</div>
    <el-button v-else style="color: #E9423A;" @click="getCode">获取验证码 </el-button>
  </div>
</template>

<script>
import { validPhone, validMail } from '@/utils/validate'
import { getNumberCode, getMailCode, userPhoneCode, userEmailCode } from '@/api/common'
export default {
  props: {
    code: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入手机号码'
    },
    type: {
      type: String,
      default: 'phone' // mail
    },
    module: {
      type: String,
      default: 'other' // phoneBind、passwordEdit、emailBind passwordReset
    }
  },
  data() {
    return {
      codeTime: 60,
      codeStatus: false
    }
  },
  methods: {
    getCode() {
      if (!this.code) {
        this.$message.warning(this.placeholder)
        return
      }
      if (this.type === 'phone') {
        if (!validPhone(this.code)) {
          this.$message.warning(`请输入正确的${this.placeholder}`)
          return
        }
      } else if (this.type === 'mail') {
        if (!validMail(this.code)) {
          this.$message.warning(`请输入正确的邮箱号${this.placeholder}`)
          return
        }
      }
      this.codeStatus = true
      this.$emit('startCall', this.codeStatus)
      const interval = setInterval(() => {
        this.codeTime -= 1
        if (this.codeTime === 0) {
          this.codeStatus = false
          this.$emit('endCall', this.codeStatus)
          this.codeTime = 60
          clearInterval(interval)
        }
      }, 1000)
      if (this.module === 'other' || this.module === 'passwordReset') {
        if (this.type === 'phone') {
          getNumberCode({ phoneNumber: this.code, type: this.module })
        } else if (this.type === 'mail') {
          getMailCode({ mail: this.code, type: this.module })
        }
      } else {
        if (this.type === 'phone') {
          userPhoneCode({ phoneNumber: this.code, type: this.module })
        }
        if (this.type === 'mail' && this.module === 'emailBind') {
          userEmailCode({ mail: this.code })
        }
      }
    }
  }
}

</script>

<style lang="scss" scoped>
.verification-code {
  .time {
    min-width: 57px;
    text-align: center;
    height: 30px;
    line-height: 30px;
  }

}
</style>
