<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import http, { apiError, clearAuth } from "@/api/http";
import AppIcon from "@/components/AppIcon.vue";
import PageHeader from "@/components/PageHeader.vue";
import { useAuthStore } from "@/stores/auth";
import { useToastStore } from "@/stores/toast";

const router = useRouter();
const auth = useAuthStore();
const toast = useToastStore();
const formRef = ref<FormInstance>();
const saving = ref(false);
const form = reactive({ currentPassword: "", newPassword: "", confirmPassword: "" });

const rules: FormRules = {
  currentPassword: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 8, max: 20, message: "密码长度必须为 8～20 位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (_rule, value, callback) =>
        value === form.newPassword ? callback() : callback(new Error("两次输入的新密码不一致")),
      trigger: "blur",
    },
  ],
};

async function submit() {
  if (!(await formRef.value?.validate().catch(() => false))) return;
  saving.value = true;
  try {
    await http.put("/auth/password", {
      current_password: form.currentPassword,
      new_password: form.newPassword,
      confirm_password: form.confirmPassword,
    });
    clearAuth();
    auth.profile = null;
    toast.success("密码已修改，请使用新密码重新登录");
    await router.replace("/login");
  } catch (error) {
    const detail = apiError(error);
    toast.error(detail.message, detail.copyText);
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <div class="page-stack security-page">
    <PageHeader title="账号安全" />

    <section class="panel security-panel">
      <div class="security-intro">
        <span class="security-icon"
          ><AppIcon
            name="Lock"
            :size="22"
        /></span>
        <div>
          <h3>修改管理员密码</h3>
          <p>需验证当前密码。修改成功后将退出当前账号，请使用新密码重新登录。</p>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="password-form"
      >
        <el-form-item
          label="当前密码"
          prop="currentPassword"
        >
          <el-input
            v-model="form.currentPassword"
            type="password"
            autocomplete="current-password"
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>
        <el-form-item
          label="新密码"
          prop="newPassword"
        >
          <el-input
            v-model="form.newPassword"
            type="password"
            autocomplete="new-password"
            show-password
            placeholder="请输入 8～20 位新密码"
          />
        </el-form-item>
        <el-form-item
          label="确认新密码"
          prop="confirmPassword"
        >
          <el-input
            v-model="form.confirmPassword"
            type="password"
            autocomplete="new-password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
        <div class="form-actions">
          <el-button
            type="primary"
            :loading="saving"
            @click="submit"
            >确认修改</el-button
          >
        </div>
      </el-form>
    </section>
  </div>
</template>

<style scoped>
.security-page {
  max-width: 760px;
}
.security-panel {
  padding: 24px;
}
.security-intro {
  display: flex;
  align-items: flex-start;
  gap: 14px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--color-border-light);
}
.security-icon {
  width: 42px;
  height: 42px;
  flex: 0 0 42px;
  display: grid;
  place-items: center;
  color: var(--color-primary);
  background: var(--color-primary-soft);
  border-radius: var(--radius-md);
}
.security-intro h3 {
  font-size: 16px;
}
.security-intro p {
  margin-top: 5px;
  color: var(--color-text-secondary);
  font-size: 14px;
}
.password-form {
  max-width: 480px;
  margin-top: 22px;
}
.form-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 4px;
}
@media (max-width: 767px) {
  .security-panel {
    padding: 18px;
  }
  .password-form {
    max-width: none;
  }
  .form-actions .el-button {
    width: 100%;
  }
}
</style>
