<template>
  <div class="news-tracker"> 
    <NewsTopBar
      v-model:searchText="searchText"
      v-model:activeTab="activeTab"
      :sort-by="sortBy"
      @update:sort="updateSort"
    /> 
    <div class="news-body">
      <NewsSidebar
        :domain-options="domainOptions"
        :time-options="timeOptions"
        :selected-domains="selectedDomains"
        :selected-times="selectedTimes"
        @toggle-domain="toggleDomain"
        @toggle-time="toggleTime"
      />
      <div class="news-main"> 
        <div class="news-grid">
          <NewsCard
            v-for="item in newsList"
            :key="item.reportId"
            :item="item"
          />
        </div> 
        <NewsPagination
          :total="totalNews"
          v-model:current-page="currentPage"
          :page-size="pageSize"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import NewsTopBar from './NewsTopBar.vue'
import NewsSidebar from './NewsSidebar.vue'
import NewsCard from './NewsCard.vue'
import NewsPagination from './NewsPagination.vue'
import { getIndustryKeyList } from '@/api/bill/billHome.js'
import { getFindingsReport } from '@/api/characterPage/characterPage.js'

const route = useRoute()
const personId = computed(() => route.params.personId || route.query.personId || '')

const searchText = ref('')
const activeTab = ref('local')
const currentPage = ref(1)
const pageSize = 12
const totalNews = ref(0)
const newsList = ref([])
const loading = ref(false)

const sortBy = ref('publishTimeDesc')

const domainOptions = ref([])
const timeOptions = ref([])
const selectedDomains = ref(['all'])
const selectedTimes = ref(['all'])

async function loadFilterOptions() {
  const res = await getIndustryKeyList()
  if (res.code === 200 && res.data) {
    domainOptions.value = [
      { id: 'all', label: '全部领域' },
      ...res.data.map(item => ({ id: item.id, label: item.name })),
    ]
  }
  const currentYear = new Date().getFullYear()
  timeOptions.value = [
    { id: 'all', label: '全部时间' },
    ...Array.from({ length: 5 }, (_, i) => {
      const year = currentYear - i
      return { id: String(year), label: `${year}年` }
    }),
  ]
}

function buildParams() {
  const params = {
    currentPage: currentPage.value - 1,
    pageSize,
    sortFun: sortBy.value === 'publishTimeAsc',
  }
  if (!selectedDomains.value.includes('all')) {
    params.industryIds = selectedDomains.value
  }
  if (!selectedTimes.value.includes('all')) {
    params.years = selectedTimes.value
  }
  return params
}

function updateSort(value) {
  sortBy.value = value
  currentPage.value = 1
  loadNews()
}

async function loadNews() {
  if (!personId.value) return
  loading.value = true
  try {
    const params = buildParams()
    const res = await getFindingsReport(personId.value, params)
    if (res.code === 200 && res.data) {
      newsList.value = res.data.content || []
      totalNews.value = res.data.totalElements || 0
    } else {
      newsList.value = []
      totalNews.value = 0
    }
  } finally {
    loading.value = false
  }
}

function toggleDomain(id) {
  if (id === 'all') {
    selectedDomains.value = ['all']
  } else {
    const without = selectedDomains.value.filter(d => d !== 'all')
    const idx = without.indexOf(id)
    if (idx > -1) without.splice(idx, 1)
    else without.push(id)
    selectedDomains.value = without.length > 0 ? without : ['all']
  }
}

function toggleTime(id) {
  if (id === 'all') {
    selectedTimes.value = ['all']
  } else {
    const without = selectedTimes.value.filter(d => d !== 'all')
    const idx = without.indexOf(id)
    if (idx > -1) without.splice(idx, 1)
    else without.push(id)
    selectedTimes.value = without.length > 0 ? without : ['all']
  }
}

watch(
  () => [selectedDomains.value, selectedTimes.value],
  () => {
    currentPage.value = 1
    loadNews()
  },
  { deep: true }
)

watch(currentPage, () => {
  loadNews()
})

onMounted(async () => {
  await loadFilterOptions()
  await loadNews()
})
</script>

<style scoped>
.news-tracker {
  width: 100%;
  background: rgba(247, 248, 249, 1);
  padding: 0;
}

.news-body {
  display: flex;
  flex-direction: row;
  gap: 14px;
  align-items: flex-start;
}

.news-main {
  flex: 1;
  min-width: 0;
}
 
.news-grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 16px;
  align-content: flex-start;
  align-items: flex-start;
}
</style>
