<template>
  <FilterBar 
    v-if="fieldsWithId.length > 0"
    :fields="fieldsWithId"
    :model-value="filters"
    @update:model-value="handleUpdateFilters"
    @filter-change="handleFilterChange"
  />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import FilterBar from '@/core/components/FilterBar.vue'

interface Props {
  fields: any[]
  filters: Record<string, any>
}

interface Emits {
  (e: 'update:filters', value: Record<string, any>): void
  (e: 'filter-change'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 确保ID字段在第一位
const fieldsWithId = computed(() => {
  const existingFields = props.fields || []
  
  // 检查是否已经有name字段
  const hasNameField = existingFields.some(f => f.fieldname === 'name')
  
  if (hasNameField) {
    // 如果已经有name字段，将其移到第一位
    const nameField = existingFields.find(f => f.fieldname === 'name')
    const otherFields = existingFields.filter(f => f.fieldname !== 'name')
    return [nameField, ...otherFields]
  } else {
    // 如果没有name字段，添加一个ID字段到第一位
    const idField = {
      fieldname: 'name',
      label: 'ID',
      fieldtype: 'Data',
      in_standard_filter: 1
    }
    return [idField, ...existingFields]
  }
})

function handleUpdateFilters(value: Record<string, any>) {
  emit('update:filters', value)
}

function handleFilterChange() {
  emit('filter-change')
}
</script>

<style scoped>
/* 过滤栏样式由 FilterBar 组件内部处理 */
</style>
