<template>
  <div v-if="filterableFields.length > 0" class="elegant-filter-bar">
    <!-- Filter content -->
    <div class="filter-content">
      <div class="filter-row">
        <div 
          v-for="field in filterableFields" 
          :key="field.fieldname" 
          class="filter-item"
          :class="{ 'has-value': filters[field.fieldname] }"
        >
          <!-- Text input -->
          <div v-if="isTextField(field.fieldtype)" class="filter-input">
            <n-input 
              v-model:value="filters[field.fieldname]" 
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @blur="onFilterChange"
              @update:value="onInputChange"
              @keyup.enter="onFilterChange"
            />
          </div>
          
          <!-- Select -->
          <div v-else-if="field.fieldtype === 'Select'" class="filter-input">
            <n-select 
              v-model:value="filters[field.fieldname]" 
              :options="getSelectOptions(field)"
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @update:value="onFilterChange"
              @clear="onFilterChange"
            />
          </div>
          
          <!-- Multi-select -->
          <div v-else-if="isMultiSelectField(field.fieldtype)" class="filter-input">
            <n-select 
              v-model:value="filters[field.fieldname]" 
              :options="getSelectOptions(field)"
              multiple
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @update:value="onFilterChange"
              @clear="onFilterChange"
            />
          </div>
          
          <!-- Checkbox -->
          <div v-else-if="field.fieldtype === 'Check'" class="filter-input">
            <n-select 
              v-model:value="filters[field.fieldname]" 
              :options="[
                { label: t('Yes'), value: 1 },
                { label: t('No'), value: 0 }
              ]"
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @update:value="onFilterChange"
              @clear="onFilterChange"
            />
          </div>
          
          <!-- Number input -->
          <div v-else-if="isNumberField(field.fieldtype)" class="filter-input">
            <n-input-number 
              v-model:value="filters[field.fieldname]" 
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @blur="onFilterChange"
              @update:value="onInputChange"
              @keyup.enter="onFilterChange"
            />
          </div>
          
          <!-- Date picker -->
          <div v-else-if="isDateField(field.fieldtype)" class="filter-input">
            <n-date-picker 
              v-model:value="filters[field.fieldname]" 
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @update:value="onFilterChange"
              @clear="onFilterChange"
            />
          </div>
          
          <!-- Link field: support search and dropdown -->
          <div v-else-if="field.fieldtype === 'Link' && field.options" class="filter-input link-filter-input">
            <div class="link-filter-container" :ref="(el) => setLinkContainerRef(field.fieldname, el)">
              <n-input
                :value="getLinkDisplayValueSync(field)"
                :placeholder="getFieldPlaceholder(field)"
                clearable
                size="small"
                @update:value="(val) => handleLinkInputChange(field, val)"
                @click="() => handleLinkInputClick(field)"
                @focus="() => handleLinkInputClick(field)"
                @clear="() => handleLinkClear(field)"
              />
              <!-- Dropdown options -->
              <div 
                v-if="linkDropdownStates[field.fieldname]?.show" 
                class="link-dropdown-menu"
              >
                <div class="link-dropdown-content">
                  <div
                    v-for="option in linkDropdownStates[field.fieldname]?.options || []"
                    :key="option.value"
                    class="link-dropdown-item"
                    :class="{ 'create-item': option.type === 'create' }"
                    @click="() => handleLinkOptionSelect(field, option)"
                  >
                    <span v-if="option.type === 'create'" class="create-icon">
                      <i class="fa fa-plus"></i>
                    </span>
                    <span class="item-label">{{ option.label }}</span>
                  </div>
                  
                  <div v-if="(linkDropdownStates[field.fieldname]?.options || []).length === 0 && !linkDropdownStates[field.fieldname]?.loading" class="link-empty-state">
                    {{ t('No Data') }}
                  </div>
                  
                  <div v-if="linkDropdownStates[field.fieldname]?.loading" class="link-loading-state">
                    {{ t('Loading') }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Other field types use text input -->
          <div v-else class="filter-input">
            <n-input 
              v-model:value="filters[field.fieldname]" 
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @blur="onFilterChange"
              @update:value="onInputChange"
              @keyup.enter="onFilterChange"
            />
          </div>
        </div>
        
        <!-- Sort selector & Action buttons (right side) -->
        <div class="filter-right-actions">
          <div v-if="showSort" class="sort-item">
            <button 
              class="sort-order-btn"
              :title="sortOrder === 'desc' ? t('Descending') : t('Ascending')"
              @click="toggleSortOrder"
            >
              <Icon 
                :icon="sortOrder === 'desc' ? 'mdi:sort-ascending' : 'mdi:sort-descending'" 
                :width="16" 
                :height="16"
              />
            </button>
            <n-dropdown 
              :options="sortOptions" 
              @select="handleSortFieldSelect"
              trigger="click"
              placement="bottom-end"
            >
              <button class="sort-field-btn">
                <span>{{ currentSortLabel }}</span>
                <i class="fa fa-chevron-down"></i>
              </button>
            </n-dropdown>
          </div>
          
          <button 
            v-if="hasActiveFilters" 
            class="action-btn clear-btn" 
            @click="clearAllFilters"
            :title="t('Clear all filters')"
          >
            <i class="fa fa-times"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { NInput, NSelect, NInputNumber, NDatePicker, NDropdown } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import axios from 'axios'
import { getRecords, getPageTypeMeta } from '@/shared/api/common'

interface FilterField {
  fieldname: string
  label: string
  fieldtype: string
  options?: string
  in_list_view?: boolean
  in_standard_filter?: boolean
}

interface SortOption {
  fieldname: string
  label: string
}

interface Props {
  fields: FilterField[]
  modelValue: Record<string, any>
  showSort?: boolean
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
  sortOptions?: SortOption[]
  pageMeta?: any
}

interface Emits {
  (e: 'update:modelValue', value: Record<string, any>): void
  (e: 'filter-change', filters: Record<string, any>): void
  (e: 'update:sortBy', value: string): void
  (e: 'update:sortOrder', value: 'asc' | 'desc'): void
  (e: 'sortChange', sortBy: string, sortOrder: 'asc' | 'desc'): void
}

const props = withDefaults(defineProps<Props>(), {
  showSort: false,
  sortBy: 'modified',
  sortOrder: 'desc',
  sortOptions: undefined,
  pageMeta: undefined
})
const emit = defineEmits<Emits>()

// Filter values
const filters = ref<Record<string, any>>({ ...props.modelValue })

// Link field dropdown state (each field independent)
interface LinkDropdownState {
  show: boolean
  options: Array<{ label: string; value: string; title?: string; type?: string }>
  loading: boolean
  searchQuery: string
  displayValue: string
  pageTypeConfig: any
}

const linkDropdownStates = ref<Record<string, LinkDropdownState>>({})
const linkContainerRefs = ref<Record<string, HTMLElement | null>>({})

// Filterable fields: exclude separator fields, only show in_standard_filter fields
const filterableFields = computed(() => {
  const isFilterable = (f: FilterField) => !['Section Break', 'Column Break', 'Tab Break'].includes(f.fieldtype)
  const filterable = props.fields.filter(isFilterable)
  
  // Only show in_standard_filter fields
  const standardFilterFields = filterable.filter(f => f.in_standard_filter)
  
  return standardFilterFields.slice(0, 8) // Limit to 8 filter fields
})

// Active filter count
const activeFilterCount = computed(() => {
  return Object.values(filters.value).filter(value => 
    value !== null && value !== undefined && value !== '' && 
    !(Array.isArray(value) && value.length === 0)
  ).length
})

// Whether has active filters
const hasActiveFilters = computed(() => activeFilterCount.value > 0)

// Compute sort options based on pagetype metadata
const sortOptions = computed(() => {
  if (props.sortOptions && props.sortOptions.length > 0) {
    return props.sortOptions.map(opt => ({
      label: t(opt.label),
      key: opt.fieldname
    }))
  }
  
  // Default options
  const defaultOptions: SortOption[] = [
    { fieldname: 'modified', label: 'Modified' },
    { fieldname: 'name', label: 'ID' },
    { fieldname: 'creation', label: 'Created' },
    { fieldname: 'idx', label: 'Most Used' }
  ]
  
  // Add title_field if available
  if (props.pageMeta?.title_field && props.pageMeta.title_field !== 'name') {
    const titleFieldLabel = props.pageMeta.title_field.charAt(0).toUpperCase() + props.pageMeta.title_field.slice(1)
    defaultOptions.splice(1, 0, { fieldname: props.pageMeta.title_field, label: titleFieldLabel })
  }
  
  // Add sort_field if configured in PageType
  if (props.pageMeta?.sort_field && props.pageMeta.sort_field !== 'modified') {
    const sortFieldLabel = props.pageMeta.sort_field.charAt(0).toUpperCase() + props.pageMeta.sort_field.slice(1)
    defaultOptions.splice(1, 0, { fieldname: props.pageMeta.sort_field, label: sortFieldLabel })
  }
  
  // Add fields that are in_list_view, mandatory, or bold
  if (props.pageMeta?.fields) {
    props.pageMeta.fields.forEach((field: any) => {
      if ((field.in_list_view || field.mandatory || field.bold || field.reqd) && 
          isValueField(field.fieldtype) &&
          !defaultOptions.find(opt => opt.fieldname === field.fieldname)) {
        defaultOptions.push({ 
          fieldname: field.fieldname, 
          label: field.label || field.fieldname 
        })
      }
    })
  }
  
  // De-duplicate
  const uniqueOptions = Array.from(
    new Map(defaultOptions.map(opt => [opt.fieldname, opt])).values()
  )
  
  return uniqueOptions.map(opt => ({
    label: t(opt.label),
    key: opt.fieldname
  }))
})

// Get current sort field label
const currentSortLabel = computed(() => {
  const option = sortOptions.value.find(opt => opt.key === props.sortBy)
  return option?.label || t('Modified')
})

// Check if field is value field
function isValueField(fieldtype: string): boolean {
  const valueTypes = [
    'Data', 'Text', 'Small Text', 'Long Text', 'Link', 'Dynamic Link',
    'Date', 'Datetime', 'Time', 'Check', 'Select', 'Int', 'Float', 'Currency',
    'Percent', 'Duration', 'Rating', 'Code', 'Text Editor', 'HTML Editor',
    'Markdown Editor', 'Barcode', 'Geolocation', 'Color', 'Icon', 'Attach Image'
  ]
  return valueTypes.includes(fieldtype)
}

// Toggle sort order
function toggleSortOrder() {
  const newOrder = props.sortOrder === 'desc' ? 'asc' : 'desc'
  emit('update:sortOrder', newOrder)
  emit('sortChange', props.sortBy, newOrder)
}

// Handle sort field selection
function handleSortFieldSelect(key: string) {
  emit('update:sortBy', key)
  emit('sortChange', key, props.sortOrder)
}

// Field type check functions
function isTextField(fieldtype: string): boolean {
  return ['Data', 'Text', 'Long Text', 'Comment'].includes(fieldtype)
}

function isMultiSelectField(fieldtype: string): boolean {
  return ['MultiSelect', 'MultiSelect Pills', 'MultiSelect List'].includes(fieldtype)
}

function isNumberField(fieldtype: string): boolean {
  return ['Int', 'Float', 'Currency', 'Percent'].includes(fieldtype)
}

function isDateField(fieldtype: string): boolean {
  return ['Date', 'Datetime'].includes(fieldtype)
}

// 获取字段占位符文本
function getFieldPlaceholder(field: FilterField): string {
  const label = field.label || field.fieldname
  return t(label)
}

// 获取选择框选项
function getSelectOptions(field: FilterField) {
  if (!field.options) return []
  const options = field.options.split('\n').filter((s: string) => s.trim() !== '')
  return options.map((opt: string) => ({ label: t(opt), value: opt }))
}

// 过滤条件变化
function onFilterChange() {
  emit('update:modelValue', { ...filters.value })
  emit('filter-change', { ...filters.value })
}

// 输入框值变化处理（用于清除按钮）
function onInputChange(value: any) {
  // 如果值被清空（null, undefined, 空字符串），立即触发过滤
  if (value === null || value === undefined || value === '') {
    onFilterChange()
  }
}

// 清除所有过滤条件
function clearAllFilters() {
  filters.value = {}
  onFilterChange()
}

// 初始化Link字段的下拉状态
function initLinkDropdownState(fieldName: string) {
  if (!linkDropdownStates.value[fieldName]) {
    linkDropdownStates.value[fieldName] = {
      show: false,
      options: [],
      loading: false,
      searchQuery: '',
      displayValue: '',
      pageTypeConfig: {}
    }
  }
}

// 设置Link容器引用
function setLinkContainerRef(fieldName: string, el: any) {
  if (el) {
    linkContainerRefs.value[fieldName] = el as HTMLElement
  }
}

// 获取Link字段的同步显示值（用于模板）
function getLinkDisplayValueSync(field: FilterField): string {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  const currentValue = filters.value[fieldName]
  if (!currentValue) {
    return linkDropdownStates.value[fieldName].searchQuery || ''
  }
  
  // 如果有缓存的显示值，直接返回
  if (linkDropdownStates.value[fieldName].displayValue && 
      linkDropdownStates.value[fieldName].displayValue !== currentValue) {
    return linkDropdownStates.value[fieldName].displayValue
  }
  
  // 如果没有显示值，返回当前值（异步加载会在后台进行）
  return currentValue
}

// 异步加载Link字段的显示值（title_field）
async function loadLinkDisplayValue(field: FilterField) {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  const currentValue = filters.value[fieldName]
  if (!currentValue || !field.options) {
    return
  }
  
  // 如果已经有显示值且不等于当前值，说明已经加载过
  if (linkDropdownStates.value[fieldName].displayValue && 
      linkDropdownStates.value[fieldName].displayValue !== currentValue) {
    return
  }
  
  try {
    const config = await getLinkPageTypeConfig(field.options)
    const titleField = config.title_field || 'name'
    
    if (titleField === 'name') {
      linkDropdownStates.value[fieldName].displayValue = currentValue
      return
    }
    
    // 获取记录的title_field值
    const response = await axios.get(`/api/data/${encodeURIComponent(field.options)}/${encodeURIComponent(currentValue)}`)
    
    const recordData = response.data?.data || {}
    const titleValue = recordData[titleField] || currentValue
    linkDropdownStates.value[fieldName].displayValue = titleValue
  } catch (error) {
    // 失败时保持当前值
    console.warn('加载Link字段显示值失败:', error)
  }
}

// 获取Link字段的页面类型配置
async function getLinkPageTypeConfig(pagetype: string) {
  const fieldName = `_config_${pagetype}`
  if (!linkDropdownStates.value[fieldName]) {
    linkDropdownStates.value[fieldName] = {
      show: false,
      options: [],
      loading: false,
      searchQuery: '',
      displayValue: '',
      pageTypeConfig: {}
    }
  }
  
  if (Object.keys(linkDropdownStates.value[fieldName].pageTypeConfig).length > 0) {
    return linkDropdownStates.value[fieldName].pageTypeConfig
  }
  
  try {
    const result = await getPageTypeMeta(pagetype)
    
    const config = result.success && result.data ? result.data : {}
    linkDropdownStates.value[fieldName].pageTypeConfig = config
    return config
  } catch (error) {
    console.error('获取页面类型配置失败:', error)
    return {}
  }
}

// 搜索Link选项
async function searchLinkOptions(field: FilterField, query: string = '') {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  if (!field.options) return
  
  linkDropdownStates.value[fieldName].loading = true
  
  try {
    const config = await getLinkPageTypeConfig(field.options)
    const titleField = config.title_field || 'name'
    
    // 构建要获取的字段列表
    const fields = ['name']
    if (titleField !== 'name') {
      fields.push(titleField)
    }
    
    // 构建搜索过滤器
    const searchFilters: any[] = []
    if (query.trim()) {
      // 如果有搜索查询，优先搜索标题字段
      if (titleField !== 'name') {
        searchFilters.push([titleField, 'like', `%${query}%`])
      } else {
        searchFilters.push(['name', 'like', `%${query}%`])
      }
    }
    
    // 使用标准API获取记录列表
    const result = await getRecords(field.options, searchFilters, fields, 'modified desc', 0, 20)
    
    if (result.success && result.data) {
      // 处理记录数据，优先显示标题字段
      const processedRecords = result.data.map((item: any) => {
        const title = titleField === 'name' ? item.name : (item[titleField] || item.name)
        return {
          label: title,
          value: item.name,
          title: title
        }
      })
      
      linkDropdownStates.value[fieldName].options = processedRecords
    } else {
      linkDropdownStates.value[fieldName].options = []
    }
  } catch (error) {
    console.error('搜索Link选项失败:', error)
    linkDropdownStates.value[fieldName].options = []
  } finally {
    linkDropdownStates.value[fieldName].loading = false
  }
}

// 处理Link输入变化
function handleLinkInputChange(field: FilterField, value: string) {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  linkDropdownStates.value[fieldName].searchQuery = value || ''
  
  // 如果下拉框已显示，实时搜索
  if (linkDropdownStates.value[fieldName].show) {
    searchLinkOptions(field, value)
  }
  
  // 如果输入被清空，清除过滤值
  if (!value) {
    filters.value[fieldName] = ''
    onFilterChange()
  }
}

// 处理Link输入框点击/聚焦
async function handleLinkInputClick(field: FilterField) {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  // 如果已经显示，不重复调用
  if (linkDropdownStates.value[fieldName].show) return
  
  // 先加载数据，再显示下拉框
  await searchLinkOptions(field, linkDropdownStates.value[fieldName].searchQuery)
  linkDropdownStates.value[fieldName].show = true
}

// 处理Link选项选择
function handleLinkOptionSelect(field: FilterField, option: any) {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  if (option.type === 'create') {
    // 创建新记录（暂时不处理，过滤场景不需要）
    linkDropdownStates.value[fieldName].show = false
    return
  }
  
  filters.value[fieldName] = option.value
  linkDropdownStates.value[fieldName].displayValue = option.title || option.label
  linkDropdownStates.value[fieldName].searchQuery = ''
  linkDropdownStates.value[fieldName].show = false
  
  onFilterChange()
}

// 清除Link字段值
function handleLinkClear(field: FilterField) {
  const fieldName = field.fieldname
  initLinkDropdownState(fieldName)
  
  filters.value[fieldName] = ''
  linkDropdownStates.value[fieldName].displayValue = ''
  linkDropdownStates.value[fieldName].searchQuery = ''
  linkDropdownStates.value[fieldName].show = false
  
  onFilterChange()
}

// 点击外部关闭下拉框
function handleClickOutside(event: Event) {
  const target = event.target as HTMLElement
  Object.keys(linkDropdownStates.value).forEach(fieldName => {
    const container = linkContainerRefs.value[fieldName]
    if (container && !container.contains(target)) {
      linkDropdownStates.value[fieldName].show = false
    }
  })
}

// 组件挂载时添加事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  
  // 初始化所有Link字段的状态
  props.fields.forEach(field => {
    if (field.fieldtype === 'Link' && field.options) {
      initLinkDropdownState(field.fieldname)
    }
  })
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 监听外部传入的过滤条件变化
watch(() => props.modelValue, (newValue) => {
  filters.value = { ...newValue }
  
  // 异步加载Link字段的显示值
  props.fields.forEach(field => {
    if (field.fieldtype === 'Link' && field.options && newValue[field.fieldname]) {
      initLinkDropdownState(field.fieldname)
      // 重置显示值，重新加载
      linkDropdownStates.value[field.fieldname].displayValue = ''
      // 异步加载title_field值
      loadLinkDisplayValue(field)
    } else if (field.fieldtype === 'Link' && field.options && !newValue[field.fieldname]) {
      // 如果值被清空，重置状态
      initLinkDropdownState(field.fieldname)
      linkDropdownStates.value[field.fieldname].displayValue = ''
      linkDropdownStates.value[field.fieldname].searchQuery = ''
    }
  })
}, { deep: true })

// 组件挂载后，加载已有Link字段的显示值
watch(() => filterableFields.value, (fields) => {
  fields.forEach(field => {
    if (field.fieldtype === 'Link' && field.options && filters.value[field.fieldname]) {
      loadLinkDisplayValue(field)
    }
  })
}, { immediate: true })
</script>

<style scoped>
.elegant-filter-bar {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin-bottom: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.filter-content {
  padding: 8px 16px;
}

.empty-state {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #6b7280;
  font-size: 13px;
  padding: 8px 0;
}

.empty-state i {
  color: #9ca3af;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  padding: 3px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
  min-width: 0;
}

.filter-item.has-value {
  background: #f0f9ff;
}

.filter-item:hover {
  background: #f3f4f6;
}

.filter-input {
  min-width: 120px;
  max-width: 200px;
}

.filter-input :deep(.n-input),
.filter-input :deep(.n-select),
.filter-input :deep(.n-date-picker),
.filter-input :deep(.n-input-number) {
  border: none;
  background: transparent;
  box-shadow: none;
}

.filter-input :deep(.n-input:focus),
.filter-input :deep(.n-select:focus),
.filter-input :deep(.n-date-picker:focus),
.filter-input :deep(.n-input-number:focus) {
  border: none;
  box-shadow: none;
}

.filter-right-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
  flex-shrink: 0;
}

.action-btn {
  width: 24px;
  height: 24px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background: white;
  color: #6b7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.clear-btn:hover {
  background: #fef2f2;
  border-color: #fca5a5;
  color: #dc2626;
}

/* Sort selector styles */
.sort-item {
  display: flex;
  align-items: center;
  gap: 0;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  background: white;
  transition: all 0.2s ease;
}

.sort-item:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
}

.sort-order-btn,
.sort-field-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 4px 8px;
  height: 26px;
  border: none;
  background: transparent;
  color: #6b7280;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.sort-order-btn {
  border-right: 1px solid #e5e7eb;
}

.sort-order-btn:hover {
  background: #f3f4f6;
  color: #3b82f6;
}

.sort-field-btn:hover {
  background: #f3f4f6;
  color: #3b82f6;
}

/* Responsive design */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    width: 100%;
    justify-content: center;
  }
  
  .filter-input {
    min-width: 150px;
    max-width: none;
  }
  
  .filter-right-actions {
    margin-left: 0;
    justify-content: flex-end;
    margin-top: 8px;
  }
}

/* 确保输入框完全显示 */
.filter-input :deep(.n-input),
.filter-input :deep(.n-select),
.filter-input :deep(.n-date-picker),
.filter-input :deep(.n-input-number) {
  width: 100%;
}

/* Link字段过滤样式 */
.link-filter-input {
  position: relative;
}

.link-filter-container {
  position: relative;
  width: 100%;
}

.link-dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  margin-top: 4px;
}

.link-dropdown-content {
  background: white;
  border: 1px solid #e0e0e6;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: 200px;
  overflow-y: auto;
}

.link-dropdown-item {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.link-dropdown-item:last-child {
  border-bottom: none;
}

.link-dropdown-item:hover {
  background-color: #f5f5f5;
}

.link-dropdown-item.create-item {
  color: #18a058;
  font-weight: 500;
}

.create-icon {
  color: #18a058;
}

.item-label {
  flex: 1;
}

.link-empty-state,
.link-loading-state {
  padding: 12px;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>
