<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { fetchGetObjectStatusModelPage } from '@/service/api';
import TableSearchFields, { type SearchField } from '@/components/custom/table-search-fields.vue';
import { personalItemStatusOptions } from './personal-item-shared';

defineOptions({ name: 'PersonalItemSearch' });

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

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

const searchModel = reactive<{
  keyword: string;
  statusCode?: Api.PersonalItem.PersonalItemStatusCode;
}>({
  keyword: '',
  statusCode: undefined
});

let syncingFromSource = false;
const statusOptions = ref<Array<{ label: string; value: string }>>([...personalItemStatusOptions]);

watch(
  () => [model.value.keyword, model.value.statusCode] as const,
  ([keyword, statusCode]) => {
    syncingFromSource = true;
    searchModel.keyword = keyword ?? '';
    searchModel.statusCode = statusCode;
    syncingFromSource = false;
  },
  { immediate: true, flush: 'sync' }
);

watch(
  () => [searchModel.keyword, searchModel.statusCode] as const,
  ([keyword, statusCode]) => {
    if (syncingFromSource) {
      return;
    }

    model.value.keyword = keyword.trim() || undefined;
    model.value.statusCode = statusCode;
  },
  { flush: 'sync' }
);

const fields = computed<SearchField[]>(() => [
  {
    key: 'keyword',
    label: '关键字',
    type: 'input',
    placeholder: '请输入标题或说明'
  },
  {
    key: 'statusCode',
    label: '状态',
    type: 'select',
    placeholder: '请选择状态',
    options: statusOptions.value
  }
]);

async function loadStatusOptions() {
  const { error, data } = await fetchGetObjectStatusModelPage({
    pageNo: 1,
    pageSize: 100,
    objectType: 'task',
    status: 0,
    initialFlag: undefined,
    terminalFlag: undefined,
    keyword: undefined
  });

  if (error || !data?.list?.length) {
    statusOptions.value = [...personalItemStatusOptions];
    return;
  }

  statusOptions.value = data.list
    .slice()
    .sort((left, right) => left.sort - right.sort)
    .map(item => ({
      label: item.statusName,
      value: item.statusCode
    }));
}

function handleReset() {
  emit('reset');
}

function handleSearch() {
  emit('search');
}

onMounted(() => {
  loadStatusOptions();
});
</script>

<template>
  <TableSearchFields v-model="searchModel" :fields="fields" :columns="3" @reset="handleReset" @search="handleSearch" />
</template>

<style scoped></style>
