<template>
  <el-container>
    <el-main>
      <el-form ref="formRef" :model="form.model" :rules="form.rules" :label-width="formLabelWidth" v-loading="loading"
        :element-loading-text="t('common.submitting')">
        <el-form-item :label="t('modules.user.newPassword')" prop="password">
          <el-input v-model="form.model.password" type="password" :placeholder="t('form.inputNewPassword')"
            show-password></el-input>
        </el-form-item>

        <el-form-item :label="t('modules.user.confirmPassword')" prop="confirmPassword">
          <el-input v-model="form.model.confirmPassword" type="password" :placeholder="t('form.inputConfirmPassword')"
            show-password></el-input>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button type="primary" @click="onConfirm">{{ t('common.update') }}</el-button>
    </el-footer>
  </el-container>
</template>

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

const { t } = useI18n();
const { formLabelWidth } = useFormConfig({ enWidth: '160px' });
const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
    default: () => ({}),
  },
});

const formRef = ref();
const loading = ref(false);

const form = reactive({
  model: {
    password: '',
    confirmPassword: '',
  },
  rules: {
    password: [
      { required: true, get message() { return t('form.passwordRequired'); }, trigger: 'blur' },
      { min: 6, max: 20, get message() { return t('form.passwordLength'); }, trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, get message() { return t('form.confirmPasswordRequired'); }, trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== form.model.password) {
            callback(new Error(t('form.passwordMismatch')));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
  },
});

// 提交表单
const onConfirm = async () => {
  try {
    await formRef.value.validate();

    loading.value = true;
    const { code } = await api.list.edit({
      id: props.modal.params.id,
      pwd: form.model.password,
    });

    if (code == '200') {
      ElMessage.success(t('message.passwordUpdateSuccess'));
      emit('modalCallBack', { event: 'confirm' });
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    return false;
  } finally {
    loading.value = false;
  }
};

defineExpose({
  onConfirm,
});
</script>
