<script setup lang="ts">
import { ref, computed } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import type { SearchModel } from '@/views/user-center/user/type';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const props = defineProps<{
  model: SearchModel;
}>();

const emit = defineEmits<{
  'updateModel': [value: SearchModel];
  'reset': [];
  'search': [];
}>();

const formRef = ref<FormInstance>();


// 修改计算属性的实现
const formModel = computed({
  get: () => ({
    username: props.model.username ?? '',
    email: props.model.email ?? ''
  }),
  set: (val: Partial<{ username: string; email: string }>) => {
    emit('updateModel', {
      ...props.model,
      username: val.username || undefined,
      email: val.email || undefined
    });
  }
});

const handleReset = () => {
  // 重置表单字段
  formRef.value?.resetFields();

  // 重置表单模型的值
  formModel.value = {
    username: '',
    email: ''
  };

  // 定义默认参数
  const defaultParams: SearchModel = {
    pageNum: 1,
    pageSize: 10,
    username: undefined,
    email: undefined
  };

  console.log('Emitting reset with params:', defaultParams);

  // 发送更新事件
  emit('updateModel', defaultParams);
  // 发送重置事件
  emit('reset');
};

const handleSearch = () => {
  console.log('Search form values:', formModel.value);

  // 确保所有必要的字段都存在
  const updatedParams: SearchModel = {
    pageNum: props.model.pageNum || 1,
    pageSize: props.model.pageSize || 10,
    username: formModel.value.username || undefined,
    email: formModel.value.email || undefined
  };

  console.log('Emitting updated params:', updatedParams);

  emit('updateModel', updatedParams);
  emit('search');
};
</script>

<template>
  <ACard :bordered="false">
    <AForm
      ref="formRef"
      :model="formModel"
      layout="inline"
      class="flex flex-wrap gap-16px items-center"
    >
      <AFormItem :label="t('page.user.username')" name="username">
        <AInput
          v-model:value="formModel.username"
          :placeholder="t('page.user.pleusername')"
          allow-clear
        />
      </AFormItem>
      <AFormItem :label="t('page.user.email')" name="email">
        <AInput
          v-model:value="formModel.email"
          :placeholder="t('page.user.pleemail')"
          allow-clear
        />
      </AFormItem>
      <AFormItem class="flex-1 justify-end mb-0">
        <ASpace>
          <AButton type="primary" ghost @click="handleSearch">
            <template #icon>
            <icon-mdi-search />
          </template>{{ t('page.user.search') }}</AButton>
          <AButton @click="handleReset">
            <template #icon>
            <icon-mdi-refresh />
          </template>{{ t('page.user.reset') }}</AButton>
        </ASpace>
      </AFormItem>
    </AForm>
  </ACard>
</template>
