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

defineOptions({ name: 'StateTransitionSearch' });

interface Props {
  targetStatusOptions: Array<{ label: string; value: string }>;
}

const props = defineProps<Props>();

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

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

const searchModel = reactive<{
  keyword: string;
  toStatusCode?: string;
  status?: Api.Infra.CommonStatus;
}>({
  keyword: '',
  toStatusCode: undefined,
  status: undefined
});

let syncingFromSource = false;

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

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

    const keywordText = keywordValue.trim() || undefined;
    model.value.actionName = keywordText;
    model.value.actionCode = keywordText;
    model.value.toStatusCode = toStatusCode;
    model.value.status = status;
  },
  { flush: 'sync' }
);

const fields = computed<SearchField[]>(() => [
  {
    key: 'keyword',
    label: '动作名称',
    type: 'input',
    placeholder: '请输入动作名称或动作编码'
  },
  {
    key: 'toStatusCode',
    label: '目标状态',
    type: 'select',
    placeholder: '请选择目标状态',
    options: props.targetStatusOptions
  },
  {
    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>
