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

    <el-form class="user-form" ref="changePasswordFormRef" :model="changePasswordForm" :rules="changePasswordRules">
      <UserCaptcha v-model="changePasswordForm.code" @sendCode="handleSendCode" :show-send-button="showSendButton"
        :send-state="sendState" />
      <el-form-item prop="password">
        <el-input v-model="changePasswordForm.password" placeholder="请输入新密码" type="password" show-password clearable
          size="large" />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input v-model="changePasswordForm.confirmPassword" placeholder="请确认新密码" type="password" show-password
          clearable size="large" />
      </el-form-item>
      <el-form-item class="form-submit">
        <el-button type="primary" @click="handleChangePassword">重新登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>

defineOptions({
  name: 'ChangePassword'
})
// 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 { getStorage } from '@/utils/storage'
import { md5Encrypt } from '@/utils/crypto'
import { sendCaptcha, initCaptchaState, clearCaptchaTimer } from '@/utils/sendCaptcha'

//用户校验规则
import { passwordRules, emailRules, phoneRules, codeRules } from './config/rules'
//store实例和获取user信息
const userStore = useUserStore()
const userInfo = getStorage<any>('userInfo')
  const router = useRouter()

//userText 实例
const userText = ref({
  backText: '返回',
  account: userInfo?.username || ''
})

//tabs 实例
const tabList = ref([
  { label: '邮箱验证', name: 'email' },
  { label: '手机验证', name: 'phone' },
])
const activeTab = ref<string>(getStorage('loginType', 'session') || 'email')

// ChangePassword 表单实例
const changePasswordFormRef = ref<FormInstance>()
const changePasswordForm = ref({
  email: userInfo?.email || '',
  countryCode: '+86',
  phone: userInfo?.mobile || '',
  password: '',
  confirmPassword: '',
  code: '',
})
console.log('changePasswordForm.value', changePasswordForm.value);
const changePasswordRules = ref<FormRules>({
  email: emailRules().email,
  phone: phoneRules(changePasswordForm.value).phone,
  password: passwordRules(changePasswordForm.value).password,
  confirmPassword: passwordRules(changePasswordForm.value).confirmPassword,
  code: codeRules().code,
})

// 验证码实例
const showSendButton = ref<boolean>(true)
const sendState = ref<object>({
  isCounting: false,
  countdown: 0,
})
//初始化验证码倒计时状态（添加页面前缀隔离不同页面的倒计时状态）
const emailCaptchaState = initCaptchaState('email', 60, 'changepwd_email'); // 邮箱专属
const phoneCaptchaState = initCaptchaState('phone', 60, 'changepwd_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
    }
  }
}
// 初始化时根据当前activeTab更新sendState（避免刷新后丢失）
const initSendState = () => {
  const currentType = activeTab.value === 'email' ? 'email' : 'phone'
  updateSendState(currentType)
}
onMounted(() => {
  // 页面加载时立即执行，恢复倒计时
  initSendState()
})
// 监听activeTab变化，同步sendState
watch(
  activeTab,
  (newTab, oldTab) => {
    activeTab.value = newTab;
    console.log('activeTab.value', activeTab.value);
    // 只有“主动切换tab”（oldTab有值）时才处理，初始化时（oldTab为undefined）不触发
    if (oldTab === undefined) return

    if (newTab === 'email' || newTab === 'phone') {
      // 主动切换到邮箱/手机页时，同步当前类型的倒计时状态（不再无脑重置）
      updateSendState(newTab)
    } else if (newTab === 'code') {
      // 切换到验证码页时，根据存储的类型更新状态
      const currentType: string = getStorage('forgotType', 'session') || 'email'
      updateSendState(currentType)
    }
  },
  { immediate: false } // 关键：关闭立即执行，避免刷新时触发
)

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

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

  //把状态同步给子组件
  updateSendState(type)
}

// 登录
const handleChangePassword = async () => {
  if (!changePasswordFormRef.value) return;

  try {
    //信息校验
    await changePasswordFormRef.value.validate();

    // 重置密码参数
    const changePasswordParams = { 
      verify_type: activeTab.value === 'email' ? 1 : 2,
      code: changePasswordForm.value.code,
      login_password1: md5Encrypt(changePasswordForm.value.password),
      login_password2: md5Encrypt(changePasswordForm.value.confirmPassword),
    };
    console.log('changePasswordParams', changePasswordParams);
    await userStore.changePassword(changePasswordParams);
    changePasswordForm.value = {
      email: userInfo?.email || '',
      countryCode: '+86',
      phone: userInfo?.mobile || '',
      password: '',
      confirmPassword: '',
      code: ''
    };
  } catch (error) {
    console.error('表单校验失败：', error);
  }
}

//返回上一级页面
const handleBack = () => {
  router.back()
};

// 组件卸载时清除定时器（关键：防止内存泄漏）
onUnmounted(() => {
  clearCaptchaTimer(emailCaptchaState);
  clearCaptchaTimer(phoneCaptchaState);
});
</script>

<style scoped lang="scss">
.user-text {
  margin-bottom: 0;
}

.user-form {
  .form-submit {
    margin-top: 24px;
  }
}
</style>
