<template>
  <el-form ref="pwdRef" :model="user" :rules="rules" label-width="160px">
    <el-form-item :label="$t('profile.resetPwdForm.oldPassword')" prop="oldPassword">
      <el-input v-model="user.oldPassword" :placeholder="$t('profile.resetPwdForm.oldPasswordPlaceholder')" type="password" show-password />
    </el-form-item>
    <el-form-item :label="$t('profile.resetPwdForm.newPassword')" prop="newPassword">
      <el-input v-model="user.newPassword" :placeholder="$t('profile.resetPwdForm.newPasswordPlaceholder')" type="password" show-password />
    </el-form-item>
    <el-form-item :label="$t('profile.resetPwdForm.confirmPassword')" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" :placeholder="$t('profile.resetPwdForm.confirmPasswordPlaceholder')" type="password" show-password />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">{{ $t('profile.resetPwdForm.save') }}</el-button>
      <el-button type="danger" @click="close">{{ $t('profile.resetPwdForm.close') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { updateUserPwd } from '@/api/system/user';
import type { ResetPwdForm } from '@/api/system/user/types';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const pwdRef = ref<ElFormInstance>();
const user = ref<ResetPwdForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const equalToPassword = (rule: any, value: string, callback: any) => {
  if (user.value.newPassword !== value) {
    callback(new Error(t('profile.rule.passwordMismatch')));
  } else {
    callback();
  }
};
const rules = ref({
  oldPassword: [{ required: true, message: t('profile.rule.oldPasswordRequired'), trigger: 'blur' }],
  newPassword: [
    { required: true, message: t('profile.rule.newPasswordRequired'), trigger: 'blur' },
    {
      min: 6,
      max: 20,
      message: t('profile.rule.passwordLength'),
      trigger: 'blur'
    },
    { pattern: /^[^<>"'|\\]+$/, message: t('profile.rule.passwordPattern'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('profile.rule.confirmPasswordRequired'), trigger: 'blur' },
    {
      required: true,
      validator: equalToPassword,
      trigger: 'blur'
    }
  ]
});

/** 提交按钮 */
const submit = () => {
  pwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await updateUserPwd(user.value.oldPassword, user.value.newPassword);
      proxy?.$modal.msgSuccess(t('profile.message.updateSuccess'));
    }
  });
};
/** 关闭按钮 */
const close = () => {
  proxy?.$tab.closePage();
};
</script>
