<script setup lang="ts">
import { ref, watch } from 'vue';
import { $t } from '@/locales';
import { useNaiveForm } from '@/hooks/common/form';

defineOptions({
  name: 'FormulateSearch'
});

interface Emits {
  (e: 'reset'): void;
  (e: 'search'): void;
}

const emit = defineEmits<Emits>();

const { formRef, validate, restoreValidation } = useNaiveForm();

const model = defineModel<Api.InventoryTask.InventorySearchParams>('model', { required: true });

const range = ref<[string, string] | null>(null);

async function reset() {
  range.value = null;
  await restoreValidation();
  emit('reset');
  emit('search');
}

async function search() {
  await validate();
  emit('search');
}

// 监听 range 变化并同步到 model
watch(range, newRange => {
  if (newRange !== null) {
    model.value.CreateTimeStart = newRange[0];
    model.value.CreateTimeEnd = newRange[1];
  }
});
</script>

<template>
  <NCard :bordered="false" size="small" class="card-wrapper">
    <NCollapse>
      <NCollapseItem :title="$t('common.search')" name="code-search">
        <NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
          <NGrid responsive="screen" item-responsive>
            <NFormItemGi :label-width="100" span="24 s:12 m:6" label="创建用户" path="CreateUser" class="pr-24px">
              <NInput v-model:value="model.CreateUser" placeholder="请输入用户名" />
            </NFormItemGi>

            <NFormItemGi :label-width="100" span="24 s:12 m:6" label="创建时间" path="CreateTime" class="pr-24px">
              <NDatePicker
                v-model:formatted-value="range"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                clearable
              />
            </NFormItemGi>

            <!-- 操作按钮 -->
            <NFormItemGi span="24 s:12 m:6" class="pr-24px">
              <NSpace class="w-full" justify="end">
                <NButton @click="reset">
                  <template #icon>
                    <icon-ic-round-refresh class="text-icon" />
                  </template>
                  {{ $t('common.reset') }}
                </NButton>
                <NButton type="primary" ghost @click="search">
                  <template #icon>
                    <icon-ic-round-search class="text-icon" />
                  </template>
                  {{ $t('common.search') }}
                </NButton>
              </NSpace>
            </NFormItemGi>
          </NGrid>
        </NForm>
      </NCollapseItem>
    </NCollapse>
  </NCard>
</template>

<style scoped></style>
