<template>
  <div class="filter-panel">
    <div class="filter-row">
      <span class="filter-label">文档类型</span>
      <div class="filter-tags">
        <span
          v-for="t in docTypes"
          :key="t"
          class="filter-tag"
          :class="{ active: docType === t }"
          @click="selectDocType(t)"
        >{{ t }}</span>
      </div>
    </div>
    <!-- 发布日期（暂时注释，后面可能用到）
    <div class="filter-row">
      <span class="filter-label">发布日期</span>
      <div class="filter-content">
        <el-date-picker
          :model-value="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="年 /月 /日"
          end-placeholder="年 /月 /日"
          size="default"
          value-format="YYYY-MM-DD"
          @update:model-value="onDateRangeChange"
          class="date-picker"
        />
      </div>
    </div>
    -->
    <div class="filter-row">
      <span class="filter-label">发布单位</span>
      <!-- 按钮模式 -->
      <div v-if="!showSearch" class="filter-tags">
        <span
          class="filter-tag"
          :class="{ active: issuingAuthority === '全部' }"
          @click="selectAuthority({ shortName: '全部', fullName: '全部', count: 0 })"
        >全部</span>
        <span
          v-for="d in topAuthorities"
          :key="d.fullName"
          class="filter-tag"
          :class="{ active: issuingAuthority === d.fullName }"
          :title="d.fullName"
          @click="selectAuthority(d)"
        >{{ d.shortName }}</span>
        <span
          v-if="!showSearch"
          class="filter-tag more-tag"
          @click="toggleSearch"
        >更多</span>
      </div>
      <!-- 搜索模式 -->
      <div v-else class="filter-content">
        <div class="search-inline">
          <el-input
            v-model="searchInput"
            placeholder="输入发布单位名称，如发改委"
            size="default"
            clearable
            prefix-icon="Search"
            class="authority-search"
            @input="onSearchInput"
          />
          <span class="collapse-btn" @click="toggleSearch">收起</span>
        </div>
        <div v-if="searchResults.length > 0" class="search-results">
          <div
            v-for="item in searchResults"
            :key="item.fullName"
            class="search-result-item"
            :class="{ active: issuingAuthority === item.fullName }"
            @click="selectAuthority(item)"
          >
            <span class="result-short">{{ item.shortName }}</span>
            <span class="result-full">{{ item.fullName }}</span>
          </div>
        </div>
        <div v-if="hasSearched && searchInput && searchResults.length === 0" class="search-empty">
          未找到匹配的发布单位
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { getIssuingAuthorities } from '@/api/retrieval'

interface Authority {
  shortName: string
  fullName: string
  count: number
}

const docTypes = ['全部', '法规制度', '技术标准', '操作指南', '通知公告', '工作报告']

// 所有发布单位（从后端 API 获取）
const allAuthorities = ref<Authority[]>([])
const authoritiesLoading = ref(false)

// 加载全部发布单位（无关键词，取前50个）
async function loadAuthorities(keyword = '') {
  authoritiesLoading.value = true
  try {
    const res = await getIssuingAuthorities(keyword)
    const items = (res.data?.authorities || []) as Array<{ full_name: string; count: number }>
    allAuthorities.value = items.slice(0, 50).map((a) => ({
      shortName: a.full_name.length > 12 ? a.full_name.substring(0, 12) + '…' : a.full_name,
      fullName: a.full_name,
      count: a.count,
    }))
  } catch (e) {
    console.warn('[FilterPanel] 加载发布单位失败:', e)
    allAuthorities.value = []
  } finally {
    authoritiesLoading.value = false
  }
}

// 前5发布单位（用于按钮展示）
const topAuthorities = computed(() => allAuthorities.value.slice(0, 5))

// 页面加载时获取发布单位列表
onMounted(() => {
  loadAuthorities('')
})

const props = defineProps<{
  docType: string
  department: string
  dateRange: [string, string] | null
}>()

const emit = defineEmits<{
  'update:docType': [value: string]
  'update:department': [value: string]
  'update:dateRange': [value: [string, string] | null]
  change: [params: {
    docType: string
    department: string
    publishDateFrom: string
    publishDateTo: string
  }]
}>()

// 发布单位状态
const issuingAuthority = ref('全部')
const showSearch = ref(false)
const searchInput = ref('')
const searchResults = ref<Authority[]>([])
const hasSearched = ref(false)
// 同步父组件传入的 department（如从详情页返回时恢复筛选条件）
watch(() => props.department, (newVal) => {
  if (newVal && newVal !== issuingAuthority.value) {
    issuingAuthority.value = newVal
    searchInput.value = newVal
  }
}, { immediate: true })

let debounceTimer: ReturnType<typeof setTimeout> | null = null
let isSelectingFromList = false

function selectDocType(type: string) {
  emit('update:docType', type)
  emitChange(type)
}

function selectAuthority(item: Authority) {
  isSelectingFromList = true
  hasSearched.value = false
  if (debounceTimer) clearTimeout(debounceTimer)
  issuingAuthority.value = item.fullName
  searchInput.value = item.fullName
  searchResults.value = []
  emit('update:department', item.fullName)
  emitChange(undefined, item.fullName)
  setTimeout(() => {
    isSelectingFromList = false
  }, 50)
}

function toggleSearch() {
  showSearch.value = !showSearch.value
  if (!showSearch.value) {
    searchInput.value = ''
    searchResults.value = []
    hasSearched.value = false
  }
}

function onSearchInput(val: string) {
  if (isSelectingFromList) return
  hasSearched.value = val.trim() !== ''
  if (debounceTimer) clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => {
    const kw = val.trim()
    if (!kw) {
      searchResults.value = []
      return
    }
    // 调用后端 API 搜索发布单位
    loadSearchResults(kw)
  }, 300)
}

async function loadSearchResults(keyword: string) {
  try {
    const res = await getIssuingAuthorities(keyword)
    const items = (res.data?.authorities || []) as Array<{ full_name: string; count: number }>
    searchResults.value = items.slice(0, 50).map((a) => ({
      shortName: a.full_name.length > 12 ? a.full_name.substring(0, 12) + '…' : a.full_name,
      fullName: a.full_name,
      count: a.count,
    }))
  } catch (e) {
    console.warn('[FilterPanel] 搜索发布单位失败:', e)
    searchResults.value = []
  }
}

function onDateRangeChange(val: [string, string] | null) {
  emit('update:dateRange', val)
  emitChange(undefined, undefined, val)
}

function emitChange(
  docType?: string,
  department?: string,
  dateRange?: [string, string] | null
) {
  emit('change', {
    docType: docType ?? props.docType,
    department: department ?? props.department,
    publishDateFrom: (dateRange ?? props.dateRange)?.[0] || '',
    publishDateTo: (dateRange ?? props.dateRange)?.[1] || '',
  })
}
</script>

<style scoped>
.filter-panel {
  background: #fff;
  border-radius: 12px;
  padding: 24px 32px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
  margin-bottom: 8px;
}
.filter-row {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
}
.filter-row:last-child {
  border-bottom: none;
}
.filter-label {
  width: 80px;
  flex-shrink: 0;
  font-size: 14px;
  color: #909399;
  font-weight: 400;
  margin-top: 6px;
}
.filter-content {
  flex: 1;
}
.filter-tags {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.filter-tag {
  padding: 6px 18px;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  background: #f5f7fa;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
  border: 1px solid transparent;
  min-width: 60px;
  text-align: center;
}
.filter-tag:hover {
  color: #f5a623;
  background: #fff8f0;
  border-color: #f5d9b0;
}
.filter-tag.active {
  color: #fff;
  background: #f5a623;
  border-color: #f5a623;
  box-shadow: 0 2px 8px rgba(245, 166, 35, 0.3);
  font-weight: 500;
}
.more-tag {
  color: #f5a623;
  background: #fff8f0;
  border-color: #f5d9b0;
}
.more-tag:hover {
  color: #fff;
  background: #f5a623;
  border-color: #f5a623;
}

/* 搜索模式 */
.search-inline {
  display: flex;
  align-items: center;
  gap: 8px;
}
.authority-search {
  flex: 1;
  max-width: 360px;
}
.collapse-btn {
  font-size: 13px;
  color: #f5a623;
  cursor: pointer;
  white-space: nowrap;
  padding: 6px 14px;
  border-radius: 4px;
  border: 1px solid #f5d9b0;
  background: #fff8f0;
  transition: all 0.2s;
}
.collapse-btn:hover {
  color: #fff;
  background: #f5a623;
  border-color: #f5a623;
}
.search-results {
  margin-top: 4px;
  max-height: 220px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}
.search-result-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: background 0.15s;
  display: flex;
  align-items: center;
  gap: 16px;
}
.search-result-item:hover {
  background: #f5f7fa;
}
.search-result-item.active {
  background: #fff8f0;
}
.result-short {
  font-size: 13px;
  font-weight: 500;
  min-width: 100px;
  color: #303133;
}
.search-result-item.active .result-short {
  color: #f5a623;
}
.result-full {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.search-empty {
  padding: 16px;
  text-align: center;
  color: #c0c4cc;
  font-size: 13px;
}

.date-picker {
  width: 100%;
  max-width: 460px;
}
.date-picker :deep(.el-input__wrapper) {
  border-radius: 4px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}
</style>
