<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" :label-width="formLabelWidth">
        <el-form-item :label="t('modules.auth.username')">
          <el-input v-model="props.modal.params.name" disabled></el-input>
        </el-form-item>
        <el-form-item :label="t('modules.auth.newPassword')" prop="password">
          <el-input v-model="form.model.password" type="password" :placeholder="t('modules.auth.passwordRequired')"
            show-password></el-input>
        </el-form-item>
        <el-form-item :label="t('modules.auth.confirmPassword')" prop="confirmPassword">
          <el-input v-model="form.model.confirmPassword" type="password"
            :placeholder="t('modules.auth.confirmPasswordRequired')" show-password></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button type="primary" @click="confirm">{{ t('modules.auth.changePassword') }}</el-button>
    </el-footer>
  </el-container>
</template>

<script setup>
import { reactive, ref, unref } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useFormConfig } from '@/hooks/useFormConfig';
import admin from '@/app/admin/api';

const { t } = useI18n();

// 使用表单配置hooks
const { formLabelWidth } = useFormConfig({ enWidth: '150px' });

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});

// 表单
const formRef = ref(null);
const form = reactive({
  model: {
    password: '',
    confirmPassword: '',
  },
  rules: {
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请再次输入新密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== form.model.password) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
  },
});

// 提交修改
function confirm() {
  unref(formRef).validate(async (valid) => {
    if (!valid) return;

    try {
      const { code } = await admin.auth.user.restpwd({
        pwd: form.model.password,
        userId: props.modal.params.id,
      });

      if (code == 200) {
        emit('modalCallBack', { event: 'confirm' });
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      ElMessage.error(t('message.changePasswordFailed'));
    }
  });
}
</script>

<style lang="scss" scoped>
.el-form {
  max-width: 400px;
}
</style>
