<template>
  <el-form ref="pwdRef" :model="user" :rules="rules" label-width="80px">
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" show-password />
    </el-form-item>

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

      <!-- 使用密码强度指示器组件 -->
      <PasswordStrengthIndicator
        :strength-score="strengthScore"
        :strength-level="strengthLevel"
        :strength-color="strengthColor"
        :password-rules="passwordRules"
        :current-password="user.newPassword"
        :config-loaded="configLoaded"
        :show-strength-meter="true"
        :show-rules="true"
      />
    </el-form-item>

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

    <el-form-item>
      <el-button
        type="primary"
        @click="submit"
        :loading="loading"
        :disabled="!allBasicRulesMet || !configLoaded"
      >
        {{ loading ? '保存中...' : '保存' }}
      </el-button>
      <el-button type="danger" @click="close" :disabled="loading">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { changePassword } from '@/api/system/security';
import type { PasswordChangeRequest } from '@/api/system/security/types';
import type { ComponentInternalInstance } from 'vue';
import { computed, getCurrentInstance, ref, watch } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { usePasswordStrength } from '../composables/usePasswordStrength';
import PasswordStrengthIndicator from '@/components/User/PasswordStrengthIndicator.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const pwdRef = ref<ElFormInstance>();

// 添加 loading 状态
const loading = ref(false);

// 密码修改表单数据
const user = ref<{
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 用户名
const username = computed(() => userStore.name || '');

// 使用统一的密码强度检查 composable
const {
  strengthScore,
  strengthLevel,
  strengthColor,
  passwordRules,
  allBasicRulesMet,
  configLoaded,
  checkPasswordStrengthForUI,
  createBasicPasswordRules,
  resetPasswordStrength
} = usePasswordStrength({
  username: username,
  showStrengthMeter: true,
  showTooltip: false 
});

// 处理密码输入
const handlePasswordInput = () => {
  checkPasswordStrengthForUI(user.value.newPassword);
};

// 监听密码变化
watch(
  () => user.value.newPassword,
  () => {
    handlePasswordInput();
  }
);

const equalToPassword = (rule: any, value: string, callback: any) => {
  if (user.value.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const rules = ref({
  oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
  newPassword: createBasicPasswordRules({ fieldName: '新密码' }),
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      validator: equalToPassword,
      trigger: 'blur'
    }
  ]
});

// 清空密码表单
const clearPasswordForm = () => {
  user.value.oldPassword = '';
  user.value.newPassword = '';
  user.value.confirmPassword = '';
  // 清空密码强度检查状态
  resetPasswordStrength();
  // 清空表单验证状态
  pwdRef.value?.clearValidate();
};

/** 提交按钮 */
const submit = () => {
  pwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true; // 开始加载
      try {
        const changeRequest: PasswordChangeRequest = {
          oldPassword: user.value.oldPassword,
          newPassword: user.value.newPassword,
          confirmPassword: user.value.confirmPassword
        };

        await changePassword(changeRequest);
        proxy?.$modal.msgSuccess('密码修改成功');
        // 密码修改成功后清空表单
        clearPasswordForm();
      } catch (error) {
        // 如果修改失败，不清空表单，方便用户重新尝试
      } finally {
        loading.value = false; // 结束加载
      }
    }
  });
};

/** 关闭按钮 */
const close = () => {
  proxy?.$tab.closePage();
};
</script>

<style scoped>
</style>
