<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 (activeTab === 'local' ? newsList : projectList)"
            :key="item.reportId"
            :item="item"
          />
        </div> 
        <NewsPagination
          :total="activeTab === 'local' ? totalNews : totalProjects"
          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, getInvestigationProject } 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 totalProjects = ref(0)
const newsList = ref([])
const projectList = 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({ includeSearchText = false } = {}) {
  const params = {
    currentPage: currentPage.value - 1,
    pageSize,
    sortFun: sortBy.value === 'publishTimeAsc',
    industryIds: selectedDomains.value.includes('all') ? '' : JSON.stringify(selectedDomains.value),
    years: selectedTimes.value.includes('all') ? '' : JSON.stringify(selectedTimes.value),
  }
  if (includeSearchText) {
    params.searchText = searchText.value
  }
  return params
}

function updateSort(value) {
  sortBy.value = value
  currentPage.value = 1
  if (activeTab.value === 'local') {
    loadNews()
  } else {
    loadProjects()
  }
}

async function loadNews() {
  if (!personId.value) return
  loading.value = true
  try {
    const params = buildParams({ includeSearchText: true })
    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
  }
}

async function loadProjects() {
  if (!personId.value) return
  loading.value = true
  try {
    const params = buildParams()
    const res = await getInvestigationProject(personId.value, params)
    if (res.code === 200 && res.data) {
      projectList.value = (res.data.content || []).map(item => ({
        reportId: item.projectId,
        title: item.name,
        content: item.description,
        imageUrl: item.imageUrl,
        time: item.time,
        sourceName: item.sourceName,
        industryList: item.industryList,
      }))
      totalProjects.value = res.data.totalElements || 0
    } else {
      projectList.value = []
      totalProjects.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(searchText, () => {
  currentPage.value = 1
  if (activeTab.value === 'local') {
    loadNews()
  } else {
    loadProjects()
  }
})

watch(activeTab, (val) => {
  currentPage.value = 1
  if (val === 'local') {
    loadNews()
  } else {
    loadProjects()
  }
})

watch(
  () => [selectedDomains.value, selectedTimes.value],
  () => {
    currentPage.value = 1
    if (activeTab.value === 'local') {
      loadNews()
    } else {
      loadProjects()
    }
  },
  { deep: true }
)

watch(currentPage, () => {
  if (activeTab.value === 'local') {
    loadNews()
  } else {
    loadProjects()
  }
})

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>
