<script setup lang="ts">
import { ref, watch } from 'vue';
import { Modal, Form, Input, message } from 'ant-design-vue';
import { updatePasswordApi, type ProfileApi } from '#/api/admin/profile';

const props = defineProps<{
  open: boolean;
}>();

const emit = defineEmits<{
  'update:open': [value: boolean];
}>();

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

const formData = ref<ProfileApi.UpdatePasswordParams>({
  old_password: '',
  new_password: '',
  confirm_password: '',
});

// 监听对话框打开
watch(
  () => props.open,
  (newVal) => {
    if (!newVal) {
      // 关闭时重置表单
      formRef.value?.resetFields();
      formData.value = {
        old_password: '',
        new_password: '',
        confirm_password: '',
      };
    }
  },
);

// 验证确认密码
function validateConfirmPassword(_rule: any, value: string) {
  if (!value) {
    return Promise.reject(new Error('请再次输入新密码'));
  }
  if (value !== formData.value.new_password) {
    return Promise.reject(new Error('两次输入的密码不一致'));
  }
  return Promise.resolve();
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value?.validate();
    loading.value = true;

    await updatePasswordApi(formData.value);
    message.success('密码修改成功');
    emit('update:open', false);
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单验证错误
      return;
    }
    message.error(error?.message || '修改密码失败');
  } finally {
    loading.value = false;
  }
}

function handleCancel() {
  emit('update:open', false);
}
</script>

<template>
  <Modal
    :open="open"
    title="修改密码"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="500px"
  >
    <Form
      ref="formRef"
      :model="formData"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <Form.Item
        label="当前密码"
        name="old_password"
        :rules="[{ required: true, message: '请输入当前密码' }]"
      >
        <Input.Password
          v-model:value="formData.old_password"
          placeholder="请输入当前密码"
        />
      </Form.Item>
      <Form.Item
        label="新密码"
        name="new_password"
        :rules="[
          { required: true, message: '请输入新密码' },
          { min: 6, message: '密码长度至少6位' },
        ]"
      >
        <Input.Password
          v-model:value="formData.new_password"
          placeholder="请输入新密码"
        />
      </Form.Item>
      <Form.Item
        label="确认密码"
        name="confirm_password"
        :rules="[{ validator: validateConfirmPassword }]"
      >
        <Input.Password
          v-model:value="formData.confirm_password"
          placeholder="请再次输入新密码"
        />
      </Form.Item>
    </Form>
  </Modal>
</template>

