<template>
  <Form v-show="getShow" :rules="rules" :schema="schema"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)" hide-required-asterisk label-position="top"
    size="large" @register="register">
    <template #title>
      <LoginFormTitle style="width: 100%" />
    </template>

    <template #phone="form">
      <div class="w-[100%] flex">
        <el-input v-model="form['phone']" placeholder="请输入手机号">
          <template #append>
            <el-button type='primary' @click="getCaptcha" :disabled="countdown > 0">
              {{ countdown > 0 ? `${countdown}秒后可重新获取` : '获取验证码' }}
            </el-button>
          </template>
        </el-input>
      </div>
    </template>
    <template #code="form">
      <div class="w-[100%] flex">
        <el-input v-model="form['code']" :placeholder="t('login.codePlaceholder')" />
      </div>
    </template>

    <template #register>
      <div class="w-[100%]">
        <XButton :loading="loading" :title="t('login.register')" class="w-[100%]" type="primary"
          @click="loginRegister()" />
      </div>
      <div class="mt-15px w-[100%]">
        <XButton :title="t('login.hasUser')" class="w-[100%]" @click="handleBackLogin()" />
      </div>
    </template>
  </Form>
</template>
<script lang="ts" setup>
import type { FormRules } from 'element-plus'

import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'
import { FormSchema } from '@/types/form'
const message = useMessage()
defineOptions({ name: 'RegisterForm' })

const { t } = useI18n()
const { required } = useValidator()
const { register, elFormRef, methods } = useForm()
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER)

const countdown = ref(0);
// 获得验证码
const getCaptcha = async () => {
  const { getFormData } = methods
  const model = await getFormData()
  if (model.phone == null) {
    message.error("手机号不能为空")
    return
  }else if(!/^(?:(?:\+|00)86)?1\d{10}$/.test(model.phone)){
    message.error("手机号格式错误")
    return
  }
  try {
    // 假设 sendCaptcha 是一个发送验证码的函数
    // await sendCaptcha(phoneNumber.value);
    // console.log('验证码已发送至', phoneNumber.value);
    // feedback.value = '验证码已发送';
    startCountdown();
  } catch (error) {
    // console.error('获取验证码失败', error);
    // feedback.value = '获取验证码失败，请稍后重试';
  }
}
// 启动倒计时
const startCountdown = () => {
  countdown.value = 60; // 倒计时60秒
  const intervalId = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      clearInterval(intervalId);
    }
  }, 1000);
};
const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24
    }
  },
  {
    field: 'username',
    label: t('login.username'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.usernamePlaceholder')
    }
  },
  {
    field: 'password',
    label: t('login.password'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      strength: true,
      placeholder: t('login.passwordPlaceholder')
    }
  },
  {
    field: 'check_password',
    label: t('login.checkPassword'),
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      strength: true,
      placeholder: t('login.passwordPlaceholder')
    }
  },
  {
    field: 'phone',
    label: '手机号',
    colProps: {
      span: 24
    }
  },
  {
    field: 'code',
    label: t('login.code'),
    colProps: {
      span: 24
    }
  },
  {
    field: 'register',
    colProps: {
      span: 24
    }
  }
])

const rules: FormRules = {
  username: [required()],
  password: [required()],
  check_password: [required()],
  phone: [required(), { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }],
  code: [required()]
}

const loading = ref(false)

const loginRegister = async () => {
  const formRef = unref(elFormRef)
  formRef?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
      } finally {
        loading.value = false
      }
    }
  })
}
</script>
