<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { NInput, NButton, NDatePicker, NCheckbox, NCheckboxGroup, NSelect, NIcon, NRadio, NRadioGroup } from 'naive-ui'
import { SearchOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const props = defineProps<{
  show?: boolean
  loading?: boolean
  tags?: any[]
}>()

const emit = defineEmits<{
  search: [params: { query: string; field: string; date_from: string | null; date_to: string | null; journal_tiers: string[]; tag_ids: string[]; retracted: string; negative_result: string; precision_mode: string; sort: string }]
}>()

const toast = useToast()
const query = ref('')
const dateFrom = ref<number | null>(null)
const dateTo = ref<number | null>(null)
const selectedTiers = ref<string[]>([])
const selectedTags = ref<string[]>([])
const retracted = ref('')
const negativeResult = ref('')
const precisionMode = ref('majr')
const sort = ref('date')
const field = ref('all')
const fieldOptions = [
  { label: '全部', value: 'all' },
  { label: '标题', value: 'title' },
  { label: '摘要', value: 'abstract' },
  { label: '作者', value: 'author' },
  { label: '机构', value: 'affiliation' },
  { label: '期刊', value: 'journal' },
]
const tagOptions = ref<any[]>([])

const fieldPlaceholder: Record<string, string> = {
  all: '标题、摘要、作者、机构、PMID、DOI...',
  title: '搜索标题...',
  abstract: '搜索摘要...',
  author: '搜索作者（英文名）...',
  affiliation: '搜索机构（英文名）...',
  journal: '搜索期刊名称...',
}

onMounted(async () => {
  if (props.tags && props.tags.length) {
    tagOptions.value = (props.tags as any[]).filter((t: any) => t.level === 2 && t.is_selectable).slice(0, 12)
  } else {
    try {
      const { data } = await api.get('/public/tags')
      tagOptions.value = (data.tags || []).filter((t: any) => t.level === 2 && t.is_selectable).slice(0, 12)
    } catch (e) { toast.apiError(e, '加载标签失败') }
  }
})

function fmtDate(ts: number | null): string {
  if (!ts) return ''
  return new Date(ts).toLocaleDateString('sv')
}

function handleSearch() {
  emit('search', {
    query: query.value,
    field: field.value,
    date_from: fmtDate(dateFrom.value),
    date_to: fmtDate(dateTo.value),
    journal_tiers: selectedTiers.value,
    tag_ids: selectedTags.value,
    retracted: retracted.value,
    negative_result: negativeResult.value,
    precision_mode: precisionMode.value,
    sort: sort.value,
  })
}

function resetFilters() {
  query.value = ''
  field.value = 'all'
  dateFrom.value = null
  dateTo.value = null
  selectedTiers.value = []
  selectedTags.value = []
  retracted.value = ''
  negativeResult.value = ''
  precisionMode.value = 'majr'
  sort.value = 'date'
}

</script>

<template>
  <div v-if="show" class="adv-filter-panel" @mousedown.stop>
    <div class="filter-row">
      <label class="filter-label">🔍 关键词</label>
      <div class="filter-field-row">
        <NSelect v-model:value="field" :options="fieldOptions" size="small" style="width:100px;flex-shrink:0" />
        <NInput v-model:value="query" :placeholder="fieldPlaceholder[field] || fieldPlaceholder['all']" size="small" clearable @keyup.enter="handleSearch" />
      </div>
    </div>
    <div class="filter-row">
      <label class="filter-label">📆 日期范围</label>
      <div class="filter-inline">
        <NDatePicker v-model:value="dateFrom" type="date" placeholder="起始日期" clearable style="flex:1" />
        <span class="filter-sep">至</span>
        <NDatePicker v-model:value="dateTo" type="date" placeholder="截止日期" clearable style="flex:1" />
      </div>
    </div>
    <div class="filter-row">
      <label class="filter-label">📰 期刊等级</label>
      <NCheckboxGroup v-model:value="selectedTiers">
        <div class="checkbox-row">
          <NCheckbox value="1" size="small">四大综合</NCheckbox>
          <NCheckbox value="2" size="small">肿瘤顶刊</NCheckbox>
          <NCheckbox value="3" size="small">专科顶刊</NCheckbox>
          <NCheckbox value="4" size="small">其他SCI</NCheckbox>
        </div>
      </NCheckboxGroup>
    </div>
    <div class="filter-row">
      <label class="filter-label">🏷️ 热门标签</label>
      <div class="tag-grid">
        <NCheckbox v-for="t in tagOptions" :key="t.id" :value="t.id" size="small">{{ t.name_zh }}</NCheckbox>
      </div>
    </div>
    <div class="filter-row">
      <div class="filter-inline" style="flex-wrap:wrap;gap:24px">
        <div>
          <label class="filter-label">⚠️ 撤稿</label>
          <NRadioGroup v-model:value="retracted" name="retracted">
            <NRadio value="" size="small">全部</NRadio>
            <NRadio value="only" size="small">仅撤稿</NRadio>
            <NRadio value="no" size="small">未撤稿</NRadio>
          </NRadioGroup>
        </div>
        <div>
          <label class="filter-label">📊 结果类型</label>
          <NRadioGroup v-model:value="negativeResult" name="resultType">
            <NRadio value="" size="small">全部</NRadio>
            <NRadio value="no" size="small">阳性结果</NRadio>
            <NRadio value="only" size="small">阴性结果</NRadio>
          </NRadioGroup>
        </div>
        <div>
          <label class="filter-label">🎯 精度模式</label>
          <NRadioGroup v-model:value="precisionMode" name="precision">
            <NRadio value="" size="small">全部</NRadio>
            <NRadio value="majr" size="small">🎯 高精度 (Major Topic)</NRadio>
            <NRadio value="mesh" size="small">📚 高召回 (MeSH)</NRadio>
          </NRadioGroup>
        </div>
        <div>
          <label class="filter-label">📊 排序</label>
          <NSelect v-model:value="sort" :options="[
            {label:'日期排序',value:'date'},
            {label:'被引次数',value:'cited'},
            {label:'相关度',value:'relevance'},
          ]" size="small" style="width:140px" />
        </div>
      </div>
    </div>
    <div class="filter-row" style="margin-bottom:0">
      <div class="filter-actions">
        <NButton size="small" type="primary" class="sky-btn" :loading="loading" @click="handleSearch"><template #icon><NIcon size="14"><SearchOutline /></NIcon></template>搜索</NButton>
        <NButton size="small" text @click="resetFilters">重置</NButton>
      </div>
    </div>
  </div>
</template>

<style scoped>
.adv-filter-panel {
  margin-top: 10px;
  padding: 16px;
  background: var(--preview-ai-bg);
  border-radius: 8px;
  border: 1px solid var(--border-color, #eee);
}
.filter-row { margin-bottom: 14px; }
.filter-row:last-child { margin-bottom: 0; }
.filter-label { display: block; font-size: 14px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; }
.filter-inline { display: flex; align-items: center; gap: 8px; }
.filter-field-row { display: flex; align-items: center; gap: 8px; }
.filter-sep { font-size: 12px; color: var(--text-muted); flex-shrink: 0; }
.checkbox-row { display: flex; flex-wrap: wrap; gap: 8px 16px; }
.tag-grid { display: flex; flex-wrap: wrap; gap: 6px 12px; max-height: 200px; overflow-y: auto; }
.filter-actions { display: flex; gap: 8px; }
</style>
