<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { changePassword } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'

const auth = useAuthStore()
const router = useRouter()

const form = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' })
const loading = ref(false)

async function submit() {
  if (!form.oldPassword || !form.newPassword) {
    ElMessage.warning('请输入旧密码和新密码')
    return
  }
  if (form.newPassword.length < 6) {
    ElMessage.warning('新密码至少 6 位')
    return
  }
  if (form.newPassword !== form.confirmPassword) {
    ElMessage.warning('两次输入的新密码不一致')
    return
  }
  loading.value = true
  try {
    await changePassword(form.oldPassword, form.newPassword)
    ElMessage.success('密码修改成功')
    auth.clearRequirePasswordChange()
    router.replace('/scores')
  } catch {
    // axios 拦截器已弹错
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login">
    <div class="card">
      <h2>修改密码</h2>
      <p class="hint">首次登录或管理员重置密码后，请修改密码。</p>
      <el-form @submit.prevent="submit" label-width="0">
        <el-form-item>
          <el-input
            v-model="form.oldPassword"
            type="password"
            placeholder="旧密码"
            show-password
            autocomplete="current-password"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.newPassword"
            type="password"
            placeholder="新密码"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="确认新密码"
            show-password
            autocomplete="new-password"
            @keyup.enter="submit"
          />
        </el-form-item>
        <el-button type="primary" :loading="loading" style="width: 100%" @click="submit">
          确认修改
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1f2d3d 0%, #3a506b 100%);
  overflow: hidden;
  padding: 16px;
}
.card {
  width: 360px;
  max-width: 100%;
  padding: 36px 32px;
  background: var(--el-bg-color);
  color: var(--el-text-color-primary);
  border-radius: 8px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.18);
}
.card h2 {
  margin: 0 0 8px;
  text-align: center;
}
.hint {
  margin: 0 0 24px;
  color: var(--el-text-color-secondary);
  font-size: 12px;
  text-align: center;
}
@media (max-width: 768px) {
  .card {
    padding: 28px 20px;
  }
}
</style>
