<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { postTypeOptions } from '@/constants/business';
import TableSearchFields, { type SearchField } from '@/components/custom/table-search-fields.vue';

defineOptions({ name: 'PostSearch' });

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

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

const statusOptions = [
  { label: '启用', value: 0 as const },
  { label: '停用', value: 1 as const }
];

const searchModel = reactive<{
  keyword: string;
  postType?: Api.SystemManage.PostType | null;
  status?: Api.SystemManage.CommonStatus;
}>({
  keyword: '',
  postType: undefined,
  status: undefined
});

let syncingFromSource = false;

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

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

    const keywordText = keywordValue.trim() || undefined;
    model.value.name = keywordText;
    model.value.code = keywordText;
    model.value.postType = postType;
    model.value.status = status;
  },
  { flush: 'sync' }
);

const fields = computed<SearchField[]>(() => [
  {
    key: 'keyword',
    label: '岗位名称',
    type: 'input',
    placeholder: '请输入岗位名称或岗位编码'
  },
  {
    key: 'postType',
    label: '岗位类型',
    type: 'select',
    placeholder: '请选择岗位类型',
    options: postTypeOptions
  },
  {
    key: 'status',
    label: '岗位状态',
    type: 'select',
    placeholder: '请选择岗位状态',
    options: statusOptions
  }
]);

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

function search() {
  emit('search');
}
</script>

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

<style scoped></style>
