<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import type { UpdatePasswordParam } from '@/api/profile/types';

import { ElMessage } from 'element-plus';
import { userUpdatePassword } from '@/api/profile';
import { useUserStore } from '@/stores';

const formRef = ref<FormInstance>();
const loading = ref(false);
const userStore = useUserStore();

const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

function validateConfirmPassword(rule: any, value: any, callback: any) {
  if (value !== formData.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  }
  else {
    callback();
  }
}

const rules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' },
  ],
};

async function handleSubmit() {
  if (!formRef.value)
    return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const params: UpdatePasswordParam = {
          oldPassword: formData.oldPassword,
          newPassword: formData.newPassword,
        };
        const res = await userUpdatePassword(params);
        // hook-fetch 会将 afterResponse 的 reject 转为 resolve 返回 Error
        if (res instanceof Error)
          return;
        ElMessage.success('密码修改成功，请重新登录');
        // 清空表单和用户状态
        resetForm();
        userStore.logout();
      }
      catch {
        // 拦截器已显示错误信息
      }
      finally {
        loading.value = false;
      }
    }
  });
}

function resetForm() {
  formData.oldPassword = '';
  formData.newPassword = '';
  formData.confirmPassword = '';
  formRef.value?.clearValidate();
}
</script>

<template>
  <div class="security-setting">
    <el-card class="setting-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">修改密码</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="formData.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="formData.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            修改密码
          </el-button>
          <el-button @click="resetForm">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.security-setting {
  padding: 16px 0;
}

.setting-card {
  border: 1px solid var(--color-border);
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;

  .title {
    font-size: 16px;
    font-weight: 600;
    color: var(--color-text-primary);
  }
}

.password-form {
  max-width: 500px;
  margin-top: 24px;
}
</style>
