<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="state.rules">
      <el-form-item prop="phone">
        <el-input v-model="ruleForm.phone" placeholder="请输入手机号" :prefix-icon="Iphone">
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-input v-model="ruleForm.code" placeholder="请输入验证码" :prefix-icon="Tickets">
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-button :disabled="state.disabled" @click="sendCode">{{ state.btnText }}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="phoneLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { Iphone, Tickets } from '@element-plus/icons-vue'

const props = defineProps({
  countDown: {
    type: Number,
    default: 60
  }
})

const emits = defineEmits(['submit', 'errHandle', 'send'])

let checkPhone = (rule: any, value: any, callback: Function) => {
  if (!value) {
    return callback(new Error('手机号不能为空'))
  } else {
    let reg = /^1[3|4|5|7|8][0-9]\d{8}$/
    if (reg.test(value)) {
      callback()
    } else {
      return callback(new Error('请输入正确的手机号'))
    }
  }
}
const ruleFormRef = ref()
const ruleForm = ref({
  phone: '',
  code: ''
})
const state = reactive({
  rules: {
    phone: [{ validator: checkPhone, trigger: 'change' }],
    code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
  },
  disabled: false,
  btnText: '发送验证码',
  time: 60
})
const phoneLogin = () => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      emits('submit')
    } else {
      emits('errHandle')
    }
  })
}
const sendCode = () => {
  ruleFormRef.value.validateField('phone', (errorMessage: string) => {
    if (errorMessage) {
      ElMessage.error(errorMessage)
    } else {
      // 1.时间开始倒数
      // 2.按钮进入禁用状态
      // 3.如果倒计时结束 按钮恢复可用状态 按钮文字变为重新发送, 时间重置
      // 4.倒计时的过程中 按钮文字为 多少s后重新发送
      let timer = setInterval(() => {
        state.time--
        state.btnText = `${state.time}s后重新发送`
        state.disabled = true
        if (state.time === 0) {
          state.disabled = false
          state.btnText = '重新发送'
          state.time = props.countDown
          clearInterval(timer)
        }
      }, 1000)
      emits('send')
    }
  })
}
//  <verification-code @send="send" @submit="submit" @errHandle="errHandle" />
// const submit = () => {
//   ElMessage.success('提交成功')
// }
// const errHandle = () => {
//   ElMessage.error('表单填写有误，请检查')
// }
// const send = () => {
//   ElMessage.info('发送验证码成功')
// }
</script>
