<template>
  <div class="step1">
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-position="top">
      <el-form-item prop="mobile" label="手机号" :error="error.mobileError">
        <el-input v-model="form.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item prop="code" label="验证码" :error="error.codeError">
        <div class="flex">
          <div class="code-input">
            <el-input placeholder="请输入验证码" v-model="form.code" />
          </div>
          <div
            :class="[
              'btn',
              'cp',
              timer.getTime() === 60 && form.mobile.length > 0 ? '' : 'disabled'
            ]"
            @click="getCode"
          >
            {{ timer.getTime() === 60 ? '获取验证码' : `重新发送(${timer.getTime()})` }}
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import useTimer from '@/hooks/useTimer'

const timer = useTimer(60)

const emit = defineEmits<{
  (event: 'success', value: typeof form.value): void
}>()

const getCode = () => {
  if (timer.getTime() === 60 && form.value.mobile.length > 0) {
    timer.start()
  } else {
    // console.log('不允许点击')
  }
}

const form = ref({
  mobile: '',
  code: ''
})

const error = ref({
  mobileError: '',
  codeError: ''
})
const rules = reactive<FormRules>({
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

const ruleFormRef = ref<FormInstance>()

const next = () => {
  ruleFormRef.value!.validate((valid: any) => {
    if (valid) {
      if (form.value.mobile !== '15279140234') {
        error.value.mobileError = '账号未注册'
        return
      }
      if (form.value.code !== '123456') {
        error.value.codeError = '验证码错误'
        return
      }
      emit('success', form.value)
    } else {
      return false
    }
  })
}

defineExpose({
  next
})
</script>

<style scoped lang="less">
.step1 {
  width: 100%;
  .code-input {
    width: 280px;
  }
  .btn {
    width: 104px;
    height: 40px;
    border: 1px solid #3480c6;
    border-radius: 4px;
    color: #3480c6;
    line-height: 40px;
    text-align: center;
    margin-left: 16px;
  }
  .disabled {
    color: #999;
    border-color: #999;
  }
}
</style>
