<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';

const props = defineProps<{
  model: SearchModel;
}>();

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

const formRef = ref<FormInstance>();
const localSearchParams = ref<SearchModel>({
  pageNum: props.model.pageNum,
  pageSize: props.model.pageSize,
  username: props.model.username,
  email: props.model.email
});

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

const handleReset = () => {
  formRef.value?.resetFields();
  localSearchParams.value = {
    pageNum: 1,
    pageSize: 10,
    username: undefined,
    email: undefined
  };
  emit('update:model', localSearchParams.value);
  emit('reset');
};

const handleSearch = () => {
  // 确保搜索时更新所有参数
  const updatedParams: SearchModel = {
    ...props.model,
    pageNum: 1,
    pageSize: 10,
    username: formModel.value.username,
    email: formModel.value.email
  };

  console.log('Search triggered with params:', updatedParams);

  // 直接更新父组件的参数
  emit('update:model', 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="用户名" name="username">
        <AInput
          v-model:value="formModel.username"
          placeholder="请输入用户名"
          allow-clear
        />
      </AFormItem>
      <AFormItem label="邮箱" name="email">
        <AInput
          v-model:value="formModel.email"
          placeholder="请输入邮箱"
          allow-clear
        />
      </AFormItem>
      <AFormItem class="flex-1 justify-end mb-0">
        <ASpace>
          <AButton @click="handleReset">重置</AButton>
          <AButton type="primary" @click="handleSearch">搜索</AButton>
        </ASpace>
      </AFormItem>
    </AForm>
  </ACard>
</template>
