<template>
  <div class="advanced-filter">
    <div class="filter-toggle" @click="expanded = !expanded">
      <div class="filter-toggle__left">
        <FilterOutlined />
        <span>高级筛选</span>
        <a-badge v-if="activeFilterCount > 0" :count="activeFilterCount" :number-style="{ backgroundColor: '#1890ff' }" />
      </div>
      <div class="filter-toggle__right">
        <a-button v-if="activeFilterCount > 0" type="link" size="small" @click.stop="$emit('reset')">重置</a-button>
        <DownOutlined :class="{ 'icon-expanded': expanded }" />
      </div>
    </div>

    <!-- Active filter tags -->
    <div v-if="activeFilterTags.length > 0 && !expanded" class="active-tags">
      <a-tag
        v-for="tag in activeFilterTags"
        :key="tag.key"
        closable
        color="blue"
        @close="removeFilter(tag.key)"
      >
        {{ tag.label }}
      </a-tag>
      <a-button type="link" size="small" @click.stop="$emit('reset')">清除全部</a-button>
    </div>

    <transition name="filter-slide">
      <div v-show="expanded" class="filter-panel">
        <a-row :gutter="[16, 12]">
          <!-- Row 1: Classification -->
          <a-col :span="6">
            <div class="filter-field">
              <label>检索范围</label>
              <a-select
                v-model:value="filters.search_scope"
                :options="scopeOptions"
                @change="$emit('change')"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="filter-field">
              <label>知识分类</label>
              <a-select
                v-model:value="filters.knowledge_category"
                placeholder="选择分类"
                allow-clear
                :options="categoryOptions"
                @change="$emit('change')"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="filter-field">
              <label>文种</label>
              <a-select
                v-model:value="filters.doc_type"
                placeholder="选择文种"
                allow-clear
                :options="docTypeOptions"
                @change="$emit('change')"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="filter-field">
              <label>文档场景</label>
              <a-select
                v-model:value="filters.document_scene_type"
                placeholder="选择场景"
                allow-clear
                :options="sceneTypeOptions"
                @change="$emit('change')"
              />
            </div>
          </a-col>

          <!-- Row 2: Source / Author -->
          <a-col :span="6">
            <div class="filter-field">
              <label>发文机关</label>
              <a-select
                v-model:value="filters.issuing_org"
                placeholder="选择机关"
                allow-clear
                show-search
                :options="orgOptions"
                @change="$emit('change')"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="filter-field">
              <label>签发人</label>
              <a-input
                v-model:value="filters.signer"
                placeholder="输入签发人姓名"
                allow-clear
                @pressEnter="$emit('change')"
                @change="handleSignerChange"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="filter-field">
              <label>文号</label>
              <a-input
                v-model:value="filters.doc_number"
                placeholder="如 国办发〔2024〕"
                allow-clear
                @pressEnter="$emit('change')"
                @change="handleDocNumberChange"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="filter-field">
              <label>主题词</label>
              <a-select
                v-model:value="filters.subject_words"
                placeholder="选择或输入主题词"
                mode="tags"
                allow-clear
                show-search
                option-filter-prop="label"
                :options="subjectWordOptions"
                @change="$emit('change')"
              />
            </div>
          </a-col>

          <!-- Row 3: Date -->
          <a-col :span="5">
            <div class="filter-field">
              <label>年份</label>
              <a-select
                v-model:value="filters.publish_year"
                placeholder="选择年份"
                allow-clear
                :options="yearOptions"
                @change="handleYearChange"
              />
            </div>
          </a-col>
          <a-col :span="9">
            <div class="filter-field">
              <label>日期范围</label>
              <a-range-picker
                v-model:value="dateRange"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                @change="handleDateChange"
              />
            </div>
          </a-col>
          <a-col :span="10" class="filter-actions">
            <a-space>
              <a-button type="primary" @click="$emit('change')">应用筛选</a-button>
              <a-button @click="$emit('reset')">重置</a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { FilterOutlined, DownOutlined } from '@ant-design/icons-vue'
import type { SearchFilters } from '@/types/search'

const props = defineProps<{
  filters: SearchFilters
  orgOptions?: { label: string; value: string }[]
  categoryOptions?: { label: string; value: string }[]
  docTypeOptions?: { label: string; value: string }[]
  sceneTypeOptions?: { label: string; value: string }[]
  subjectWordOptions?: { label: string; value: string }[]
}>()

const emit = defineEmits<{
  (e: 'change'): void
  (e: 'reset'): void
}>()

const expanded = ref(false)

// Debounce timer for text inputs
let signerTimer: ReturnType<typeof setTimeout> | undefined
let docNumberTimer: ReturnType<typeof setTimeout> | undefined

function handleSignerChange() {
  clearTimeout(signerTimer)
  if (!props.filters.signer) {
    emit('change')
  } else {
    signerTimer = setTimeout(() => emit('change'), 600)
  }
}

function handleDocNumberChange() {
  clearTimeout(docNumberTimer)
  if (!props.filters.doc_number) {
    emit('change')
  } else {
    docNumberTimer = setTimeout(() => emit('change'), 600)
  }
}

const dateRange = computed({
  get: () => {
    if (props.filters.date_from && props.filters.date_to) {
      return [props.filters.date_from, props.filters.date_to]
    }
    return undefined
  },
  set: () => {},
})

const scopeOptions = [
  { label: '综合搜索', value: 'all' },
  { label: '仅标题', value: 'title' },
  { label: '仅正文', value: 'content' },
  { label: '仅文号', value: 'doc_number' },
]

const currentYear = new Date().getFullYear()
const yearOptions = Array.from({ length: currentYear - 1989 }, (_, index) => {
  const year = currentYear - index
  return { label: `${year}年`, value: year }
})

/** Count active (non-default) filters */
const activeFilterCount = computed(() => {
  let count = 0
  const f = props.filters
  if (f.issuing_org) count++
  if (f.doc_type) count++
  if (f.knowledge_category) count++
  if (f.document_scene_type) count++
  if (f.signer?.trim()) count++
  if (f.publish_year) count++
  if (f.doc_number?.trim()) count++
  if (f.date_from && f.date_to) count++
  if (f.subject_words?.length) count++
  if (f.search_scope && f.search_scope !== 'all') count++
  return count
})

/** Build human-readable tags for active filters */
const activeFilterTags = computed(() => {
  const tags: { key: string; label: string }[] = []
  const f = props.filters
  if (f.search_scope && f.search_scope !== 'all') {
    const scopeLabel = scopeOptions.find(o => o.value === f.search_scope)?.label || f.search_scope
    tags.push({ key: 'search_scope', label: `范围: ${scopeLabel}` })
  }
  if (f.issuing_org) {
    const org = Array.isArray(f.issuing_org) ? f.issuing_org.join(', ') : f.issuing_org
    tags.push({ key: 'issuing_org', label: `机关: ${org}` })
  }
  if (f.doc_type) {
    const dt = Array.isArray(f.doc_type) ? f.doc_type.join(', ') : f.doc_type
    tags.push({ key: 'doc_type', label: `文种: ${dt}` })
  }
  if (f.knowledge_category) {
    const kc = Array.isArray(f.knowledge_category) ? f.knowledge_category.join(', ') : f.knowledge_category
    tags.push({ key: 'knowledge_category', label: `分类: ${kc}` })
  }
  if (f.document_scene_type) {
    const dst = Array.isArray(f.document_scene_type) ? f.document_scene_type.join(', ') : f.document_scene_type
    tags.push({ key: 'document_scene_type', label: `场景: ${dst}` })
  }
  if (f.signer?.trim()) tags.push({ key: 'signer', label: `签发人: ${f.signer}` })
  if (f.publish_year) tags.push({ key: 'publish_year', label: `年份: ${f.publish_year}` })
  if (f.doc_number?.trim()) tags.push({ key: 'doc_number', label: `文号: ${f.doc_number}` })
  if (f.date_from && f.date_to) tags.push({ key: 'date_range', label: `日期: ${f.date_from} ~ ${f.date_to}` })
  if (f.subject_words?.length) tags.push({ key: 'subject_words', label: `主题词: ${f.subject_words.join(', ')}` })
  return tags
})

function removeFilter(key: string) {
  switch (key) {
    case 'issuing_org': props.filters.issuing_org = undefined; break
    case 'doc_type': props.filters.doc_type = undefined; break
    case 'knowledge_category': props.filters.knowledge_category = undefined; break
    case 'document_scene_type': props.filters.document_scene_type = undefined; break
    case 'signer': props.filters.signer = undefined; break
    case 'publish_year': props.filters.publish_year = undefined; break
    case 'doc_number': props.filters.doc_number = undefined; break
    case 'date_range':
      props.filters.date_from = undefined
      props.filters.date_to = undefined
      break
    case 'subject_words': props.filters.subject_words = undefined; break
    case 'search_scope': props.filters.search_scope = 'all'; break
  }
  emit('change')
}

function handleDateChange(dates: [string, string] | null) {
  if (dates) {
    props.filters.publish_year = undefined
    props.filters.date_from = dates[0]
    props.filters.date_to = dates[1]
  } else {
    props.filters.date_from = undefined
    props.filters.date_to = undefined
  }
  emit('change')
}

function handleYearChange(value: number | undefined) {
  props.filters.publish_year = value
  if (value) {
    props.filters.date_from = undefined
    props.filters.date_to = undefined
  }
  emit('change')
}
</script>

<style scoped lang="less">
.advanced-filter {
  margin-bottom: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: #fafafa;
  margin-top: 20px;

  .filter-toggle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    cursor: pointer;
    user-select: none;

    &:hover {
      background: #f0f7ff;
      border-radius: 8px;
    }

    &__left {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      color: #595959;
      font-weight: 500;
    }

    &__right {
      display: flex;
      align-items: center;
      gap: 4px;

      .anticon-down {
        font-size: 12px;
        color: #8c8c8c;
        transition: transform 0.25s;

        &.icon-expanded {
          transform: rotate(180deg);
        }
      }
    }
  }

  .active-tags {
    padding: 0 16px 10px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 4px;
  }

  .filter-panel {
    padding: 15px 16px 16px;
    border-top: 1px solid #f0f0f0;
  }

  .filter-field {
    display: flex;
    flex-direction: column;
    gap: 4px;

    label {
      font-size: 12px;
      color: #8c8c8c;
      line-height: 1;
    }

    :deep(.ant-select),
    :deep(.ant-input),
    :deep(.ant-picker) {
      width: 100%;
    }
  }

  .filter-actions {
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
  }

  .filter-slide-enter-active,
  .filter-slide-leave-active {
    transition: all 0.25s ease;
    overflow: hidden;
  }

  .filter-slide-enter-from,
  .filter-slide-leave-to {
    opacity: 0;
    max-height: 0;
    padding-top: 0;
    padding-bottom: 0;
  }

  .filter-slide-enter-to,
  .filter-slide-leave-from {
    opacity: 1;
    max-height: 300px;
  }
}
</style>
