<script setup lang="ts">
/**
 * 重置密码页面
 *
 * 提供旧密码验证 + 新密码设置的表单，
 * 调用 resetPassword API 完成密码重置。
 */
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast, showFailToast } from 'vant'
import { resetPassword } from '@/api'

const router = useRouter()

/** 表单加载状态 */
const loading = ref(false)

/** 密码表单数据 */
const pwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

/** 表单校验规则 */
const rules = {
  oldPassword: [{ required: true, message: '请输入旧密码' }],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, message: '新密码长度不能少于6位' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
  ],
}

/**
 * 返回上一页
 */
function goBack(): void {
  router.back()
}

/**
 * 自定义校验：确认密码是否一致
 */
function validateConfirm(): boolean {
  if (pwdForm.newPassword !== pwdForm.confirmPassword) {
    showFailToast('两次输入的新密码不一致')
    return false
  }
  return true
}

/**
 * 处理重置密码提交
 */
async function handleSubmit(): Promise<void> {
  if (!validateConfirm()) return

  loading.value = true
  try {
    await resetPassword({
      oldPassword: pwdForm.oldPassword,
      newPassword: pwdForm.newPassword,
    })
    showSuccessToast('修改成功')
    router.back()
  } catch (err) {
    const msg = err instanceof Error ? err.message : '修改失败，请重试'
    showFailToast(msg)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="reset-pwd-page">
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />

    <div class="reset-pwd-content">
      <van-form @submit="handleSubmit">
        <van-cell-group inset>
          <van-field
            v-model="pwdForm.oldPassword"
            name="oldPassword"
            type="password"
            label="旧密码"
            placeholder="请输入旧密码"
            :rules="rules.oldPassword"
          />
          <van-field
            v-model="pwdForm.newPassword"
            name="newPassword"
            type="password"
            label="新密码"
            placeholder="请输入新密码"
            :rules="rules.newPassword"
          />
          <van-field
            v-model="pwdForm.confirmPassword"
            name="confirmPassword"
            type="password"
            label="确认新密码"
            placeholder="请确认新密码"
            :rules="rules.confirmPassword"
          />
        </van-cell-group>
        <div style="margin: 20px 16px 0 16px;">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="修改中..."
          >
            修 改
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.reset-pwd-page {
  min-height: 100vh;
  background: var(--color-bg-page, #f4f7f8);
}

.reset-pwd-content {
  padding-top: 20px;
}
</style>
