<template>
  <div class="user-card">
    <UserHeader />
    <UserText :user-text="userText" @back="handleBack" />
    <UserTabs v-model="activeTab" :hide-tab="false" :tab-list="tabList" />

    <el-form class="user-form" ref="forgotPasswordFormRef" :model="forgotPasswordForm" :rules="forgotPasswordRules">
      <!-- 邮箱输入 -->
      <el-form-item prop="email" v-if="activeTab === 'email'">
        <el-input v-model="forgotPasswordForm.email" placeholder="请输入邮箱" clearable size="large" />
      </el-form-item>

      <!-- 手机号输入 -->
      <el-form-item class="phone-item" prop="phone" v-else-if="activeTab === 'phone'">
        <el-select v-model="forgotPasswordForm.countryCode" :teleported="false" value-key="code" placeholder="国家"
          size="large">
          <el-option v-for="item in countryOptions" :key="item.code" :label="item.code" :value="item.code">
            <div class="country-option">
              <span class="country-name">{{ item.name }}</span>
              <span class="country-code">{{ item.code }}</span>
            </div>
          </el-option>
        </el-select>
        <el-input v-model="forgotPasswordForm.phone" placeholder="请输入手机号" clearable size="large" />
      </el-form-item>

      <!-- 验证码输入 -->
      <UserCaptcha ref="captchaRef" v-model="forgotPasswordForm.code" @sendCode="handleSendCode" :show-send-button="showSendButton"
        :send-state="sendState" />

      <!-- 密码输入（验证码发送后才可输入） -->
      <el-form-item prop="password">
        <el-input v-model="forgotPasswordForm.password" :placeholder="codeSent ? '请输入新密码' : '请先发送验证码'"
          :disabled="!codeSent" type="password" show-password clearable size="large" />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input v-model="forgotPasswordForm.confirmPassword" :placeholder="codeSent ? '请确认新密码' : '请先发送验证码'"
          :disabled="!codeSent" type="password" show-password clearable size="large" />
      </el-form-item>

      <el-form-item class="form-submit">
        <el-button type="primary" @click="handleForgotPassword">{{ codeSent ? '重置密码' : '发送验证码'
          }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>

defineOptions({
  name: 'ForgotPassword'
})
// type类型
import type { FormInstance, FormRules } from 'element-plus'
// 组件
import UserHeader from './components/Header.vue'
import UserText from './components/Text.vue'
import UserTabs from './components/Tabs.vue'
import UserCaptcha from './components/Captcha.vue'

//公共方法/store/配置文件
import { useUserStore } from '@/stores/modules/user'
import { setStorage, getStorage, removeStorage } from '@/utils/storage'
import { md5Encrypt } from '@/utils/crypto'
import { sendCaptcha, initCaptchaState, clearCaptchaTimer } from '@/utils/sendCaptcha'

//用户校验规则
import { countryOptions } from '@/views/user/config/mock'
import { passwordRules, emailRules, phoneRules, codeRules } from './config/rules'

//用户store和router实例
const userStore = useUserStore()
const router = useRouter()

//userText 实例
const userText = ref({
  backText: '返回',
  title: '忘记密码',
  text: '请输入您注册时使用的邮箱或手机号',
  account: '',
})

// tabs实例 - 用于切换邮箱和手机
const tabList = ref([
  { label: '邮箱', name: 'email' },
  { label: '手机', name: 'phone' },
])
const activeTab = ref<string>('email')

// 验证码是否已发送标记
const codeSent = ref(false)

// 表单实例
const forgotPasswordFormRef = ref<FormInstance>()
const captchaRef = ref()
const forgotPasswordForm = ref({
  email: '',
  countryCode: '+86',
  phone: '',
  password: '',
  confirmPassword: '',
  code: ''
})
const forgotPasswordRules = ref<FormRules>({
  email: emailRules().email,
  phone: phoneRules(forgotPasswordForm.value).phone,
  password: passwordRules(forgotPasswordForm.value).password,
  confirmPassword: passwordRules(forgotPasswordForm.value).confirmPassword,
  code: codeRules().code
})

// 监听 activeTab 变化，重置状态并清空所有输入字段
watch(activeTab, (newTab, oldTab) => {
  codeSent.value = false
  forgotPasswordForm.value.password = ''
  forgotPasswordForm.value.confirmPassword = ''
  // 清空验证码输入框
  captchaRef.value?.clear()
  // 切换到手机时清空邮箱，切换到邮箱时清空手机号
  if (newTab === 'phone') {
    forgotPasswordForm.value.email = ''
    forgotPasswordFormRef.value?.clearValidate(['email'])
  } else if (newTab === 'email') {
    forgotPasswordForm.value.phone = ''
    forgotPasswordFormRef.value?.clearValidate(['phone'])
  }
  forgotPasswordFormRef.value?.clearValidate(['code', 'password', 'confirmPassword'])
})

// 验证码实例
const showSendButton = ref<boolean>(true)
const sendState = ref<object>({
  isCounting: false,
  countdown: 0,
})
//初始化验证码倒计时状态
const emailCaptchaState = initCaptchaState('email', 60, 'forgot_email'); // 邮箱专属
const phoneCaptchaState = initCaptchaState('phone', 60, 'forgot_phone'); // 手机专属
// 邮箱验证码状态
const { isCounting: emailIsCounting, countdown: emailCountdown } = emailCaptchaState
// 手机验证码状态
const { isCounting: phoneIsCounting, countdown: phoneCountdown } = phoneCaptchaState

//方法

// 统一更新sendState的方法
const updateSendState = (type: string) => {
  if (type === 'email') {
    sendState.value = {
      isCounting: emailIsCounting,
      countdown: emailCountdown
    }
  } else {
    sendState.value = {
      isCounting: phoneIsCounting,
      countdown: phoneCountdown
    }
  }
}

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

//发送验证码
const handleSendCode = async () => {
  // 根据当前 tab 确定类型
  const type = activeTab.value

  const receiver = type === 'phone' ? forgotPasswordForm.value.phone : forgotPasswordForm.value.email;
  const currentCaptchaState = type === 'phone' ? phoneCaptchaState : emailCaptchaState;
  // 调用封装的发送函数
  await sendCaptcha(
    type,
    receiver,
    currentCaptchaState,
    () => sendCodeApi()
  );

  //把状态同步给子组件
  updateSendState(type)
  // 标记验证码已发送
  codeSent.value = true
}

// 返回上一页
const handleBack = () => {
  router.push('/user/login')
}

//提交表单
const handleForgotPassword = async () => {
  if (!forgotPasswordFormRef.value) return

  try {
    // 根据当前 tab 校验对应的邮箱或手机号
    await forgotPasswordFormRef.value.validateField(activeTab.value)

    // 校验验证码
    await forgotPasswordFormRef.value.validateField('code')

    // 校验密码
    await forgotPasswordFormRef.value.validateField(['password', 'confirmPassword'])

    // 重置密码参数 
    const forgotParams = {
      mobile: activeTab.value === 'phone' ? forgotPasswordForm.value.phone : undefined,
      email: activeTab.value === 'email' ? forgotPasswordForm.value.email : undefined,
      code: forgotPasswordForm.value.code,
      login_password1: forgotPasswordForm.value.password,
      login_password2: forgotPasswordForm.value.confirmPassword,
    }

    // 调用重置密码接口
    await userStore.forgotPassword(forgotParams)

    // 清空存储和表单
    forgotPasswordForm.value = {
      email: '',
      countryCode: '+86',
      phone: '',
      password: '',
      confirmPassword: '',
      code: ''
    }
    codeSent.value = false

    // 跳转到登录页
    ElMessage.success('密码重置成功，请登录')
    router.push('/user/login')
  } catch (error) {
    console.error('表单提交失败：', error)
  }
}
// 组件卸载时清除定时器
onUnmounted(() => {
  clearCaptchaTimer(emailCaptchaState);
  clearCaptchaTimer(phoneCaptchaState);
});
</script>

<style lang="scss" scoped>
.user-form {
  .phone-item {
    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }
  }
}
</style>
