<template>
    <div class="user-card">
        <UserHeader />
        <UserText :user-text="userText" @back="handleBack" />
        <el-form class="user-form" ref="bindEmailFormRef" :model="bindEmailForm" :rules="bindEmailRules">
            <el-form-item prop="email">
                <el-input v-model="bindEmailForm.email" placeholder="请输入邮箱" type="email" clearable
                    size="large" />
            </el-form-item>
            <UserCaptcha v-model="bindEmailForm.code" @sendCode="handleSendCode" :show-send-button="showSendButton"
                :send-state="sendState" />
            <el-form-item class="form-submit">
                <el-button type="primary" @click="handleSubmit">确认绑定</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">

defineOptions({
  name: 'BindEmail'
})
// alert('绑定邮箱')
// type类型
import type { FormInstance, FormRules } from 'element-plus'
// 组件
import UserHeader from './components/Header.vue'
import UserText from './components/Text.vue'
import UserCaptcha from './components/Captcha.vue'
//用户校验规则
import { emailRules, codeRules } from './config/rules'
import { useUserStore } from '@/stores/modules/user'
import { sendCaptcha, initCaptchaState, clearCaptchaTimer } from '@/utils/sendCaptcha'

const userStore = useUserStore()
const router = useRouter()

//userText 实例
const userText = ref({
    backText: '返回',
    account: ''
})

// bindEmail 表单实例
const bindEmailFormRef = ref<FormInstance>()
const bindEmailForm = ref({
    email: '',
    code: '',
})
const bindEmailRules = ref<FormRules>({
    email: emailRules().email,
    code: codeRules().code,
})


// 验证码实例
const showSendButton = ref<boolean>(true)
const sendState = ref<object>({
    isCounting: false,
    countdown: 0,
})
//初始化验证码倒计时状态（添加页面前缀隔离不同页面的倒计时状态）
const emailCaptchaState = initCaptchaState('email', 60, 'bindemail_email');
// 邮箱验证码状态
const { isCounting: emailIsCounting, countdown: emailCountdown } = emailCaptchaState

//方法
// 统一更新sendState的方法
const updateSendState = (type: string) => {
    sendState.value = {
        isCounting: emailIsCounting,
        countdown: emailCountdown
    }
}
// 初始化时根据当前activeTab更新sendState（避免刷新后丢失）
const initSendState = () => {
    const currentType = 'email'
    updateSendState(currentType)
}
onMounted(() => {
    // 页面加载时立即执行，恢复倒计时
    initSendState()
})


// 定义发送验证码接口
const sendCodeApi = async () => {
  // 发送验证码参数
  const sendParams = {
    email: bindEmailForm.value.email,
    type:'resetPass_code'
  }
  return userStore.sendCode(sendParams)
}

//发送验证码
const handleSendCode = async () => {
  const currentType = 'email'
  // 第二步：确定类型、接收方、对应的倒计时状态和发送函数
  const type: string = currentType || 'email'
  const receiver = bindEmailForm.value.email;
  const currentCaptchaState = emailCaptchaState;
  
  // 第三步：调用封装的发送函数（传正确的函数，而非字符串）
  await sendCaptcha(
    type,
    receiver,
    currentCaptchaState, // 只更新当前类型的倒计时状态
    () => sendCodeApi() // 传入返回Promise的函数
  );

  //把状态同步给子组件
  updateSendState(type)
}
// 组件卸载时清除定时器（关键：防止内存泄漏）
onUnmounted(() => {
  clearCaptchaTimer(emailCaptchaState);
});




/**
 * @description: 返回
 */
const handleBack = () => {
    router.back()
}

// 提交表单
const handleSubmit = async () => {
  if (!bindEmailFormRef.value) return;
  await bindEmailFormRef.value.validate();
}
</script>
<style scoped lang="scss">
.user-card{
    .user-text{
        margin-bottom: 0;
    }
}
</style>
