<template>
  <div class="elegant-filter-bar">
    <!-- 过滤条件内容 -->
    <div class="filter-content">
      <div v-if="filterableFields.length === 0" class="empty-state">
        <i class="fa fa-filter"></i>
        <span>{{ t('暂无可过滤的字段') }}</span>
      </div>
      
      <div v-else class="filter-row">
        <div 
          v-for="field in filterableFields" 
          :key="field.fieldname" 
          class="filter-item"
          :class="{ 'has-value': filters[field.fieldname] }"
        >
          <!-- 文本输入框 -->
          <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"
            />
          </div>
          
          <!-- 选择框 -->
          <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>
          
          <!-- 多选框 -->
          <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>
          
          <!-- 复选框 -->
          <div v-else-if="field.fieldtype === 'Check'" class="filter-input">
            <n-select 
              v-model:value="filters[field.fieldname]" 
              :options="[
                { label: t('是'), value: 1 },
                { label: t('否'), value: 0 }
              ]"
              :placeholder="getFieldPlaceholder(field)"
              clearable
              size="small"
              @update:value="onFilterChange"
              @clear="onFilterChange"
            />
          </div>
          
          <!-- 数字输入框 -->
          <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"
            />
          </div>
          
          <!-- 日期选择器 -->
          <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>
          
          <!-- 其他字段类型使用文本输入 -->
          <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"
            />
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="filter-actions">
          <button 
            v-if="hasActiveFilters" 
            class="action-btn clear-btn" 
            @click="clearAllFilters"
            :title="t('清除所有过滤条件')"
          >
            <i class="fa fa-times"></i>
          </button>
          <button 
            class="action-btn save-btn" 
            @click="showSaveDialog = true"
            :title="t('保存当前过滤条件')"
          >
            <i class="fa fa-bookmark"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 保存过滤条件对话框 -->
    <n-modal v-model:show="showSaveDialog">
      <n-card 
        style="width: 400px" 
        :title="t('保存筛选条件')" 
        :bordered="false" 
        size="huge"
        role="dialog" 
        aria-modal="true"
      >
        <n-form :model="saveForm" ref="saveFormRef">
          <n-form-item :label="t('过滤器名称')" path="name">
            <n-input 
              v-model:value="saveForm.name" 
              :placeholder="t('请输入过滤器名称')"
              size="small"
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <div class="dialog-footer">
            <n-button @click="showSaveDialog = false" size="small">
              {{ t('取消') }}
            </n-button>
            <n-button type="primary" @click="saveFilter" size="small">
              {{ t('保存') }}
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { NInput, NSelect, NInputNumber, NDatePicker, NModal, NCard, NForm, NFormItem, NButton, useMessage } from 'naive-ui'
import { t } from '@/shared/i18n'

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

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

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

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

const message = useMessage()
const showSaveDialog = ref(false)
const saveForm = ref({ name: '' })
const saveFormRef = ref()

// 过滤条件
const filters = ref<Record<string, any>>({ ...props.modelValue })

// 可过滤的字段：排除分隔符字段，只显示 in_standard_filter 的字段
const filterableFields = computed(() => {
  const isFilterable = (f: FilterField) => !['Section Break', 'Column Break', 'Tab Break'].includes(f.fieldtype)
  const filterable = props.fields.filter(isFilterable)
  
  // 只显示 in_standard_filter 的字段
  const standardFilterFields = filterable.filter(f => f.in_standard_filter)
  
  return standardFilterFields.slice(0, 8) // 限制最多8个过滤字段
})

// 活跃过滤条件数量
const activeFilterCount = computed(() => {
  return Object.values(filters.value).filter(value => 
    value !== null && value !== undefined && value !== '' && 
    !(Array.isArray(value) && value.length === 0)
  ).length
})

// 是否有活跃的过滤条件
const hasActiveFilters = computed(() => activeFilterCount.value > 0)

// 字段类型判断函数
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()
}

// 保存过滤条件
function saveFilter() {
  if (!saveForm.value.name.trim()) {
    message.warning(t('请输入过滤器名称'))
    return
  }
  
  // 这里可以保存到本地存储或发送到服务器
  const savedFilters = JSON.parse(localStorage.getItem('savedFilters') || '{}')
  savedFilters[saveForm.value.name] = { ...filters.value }
  localStorage.setItem('savedFilters', JSON.stringify(savedFilters))
  
  message.success(t('过滤条件已保存'))
  showSaveDialog.value = false
  saveForm.value.name = ''
}

// 监听外部传入的过滤条件变化
watch(() => props.modelValue, (newValue) => {
  filters.value = { ...newValue }
}, { deep: true })
</script>

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

.filter-content {
  padding: 12px 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: 12px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  padding: 4px 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-actions {
  display: flex;
  gap: 4px;
  margin-left: auto;
}

.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;
}

.save-btn:hover {
  background: #f0f9ff;
  border-color: #93c5fd;
  color: #2563eb;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 响应式设计 */
@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-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%;
}
</style>
