<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" v-if="activeTab !== 'hearing'">
        <template v-if="(activeTab === 'local' ? newsList : projectList).length > 0">
          <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"
          />
        </template>
        <el-empty v-else description="暂无数据" :image-size="80" class="empty-aligned" />
      </div>

      <!-- 听证会 -->
      <div class="hearing-right" v-else>
        <div class="hearing-card-box">
          <div class="hearing-card-content">
            <template v-if="hearingList.length > 0">
              <div v-for="(item, index) in hearingList" :key="item.id">
                <div class="hearing-card-item">
                  <img class="hearing-card-img" :src="item.coverImgUrl" alt="" />
                  <div class="hearing-card-text">
                    <div class="hearing-card-title">{{ item.titleZh }}</div>
                    <div class="hearing-card-time">
                      {{ item.testimonyDate + ' · ' + item.thinkTankName + ' · ' + item.committeeZh }}
                    </div>
                    <div class="hearing-card-tags" v-if="item.domains && item.domains.length">
                      <AreaTag v-for="(tag, i) in item.domains" :key="i" :tagName="tag" />
                    </div>
                  </div>
                </div>
                <div class="hearing-divider" v-if="index !== hearingList.length - 1"></div>
              </div>
            </template>
            <el-empty v-else description="暂无数据" :image-size="80" class="empty-aligned" />
          </div>
        </div>
        <div class="hearing-footer" v-if="hearingList.length > 0">
          <div class="hearing-footer-info">共 {{ hearingTotal }} 篇国会听证会</div>
          <el-pagination
            :page-size="hearingPageSize"
            background
            layout="prev, pager, next"
            :total="hearingTotal"
            @current-change="handleHearingPageChange"
            :current-page="hearingCurrentPage"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import NewsTopBar from './NewsTopBar.vue'
import NewsSidebar from './NewsSidebar.vue'
import NewsCard from './NewsCard.vue'
import NewsPagination from './NewsPagination.vue'
import AreaTag from '@/components/base/AreaTag/index.vue'
import { getIndustryKeyList } from '@/api/bill/billHome.js'
import { getFindingsReport, getInvestigationProject, getPersonTestimonies } from '@/api/characterPage/characterPage.js'

const props = defineProps({
  personId: { type: String, default: '' }
})

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'])

// ====== 听证会数据 ======
const hearingCurrentPage = ref(1)
const hearingPageSize = 10
const hearingTotal = ref(0)
const hearingList = ref([])

async function loadHearings() {
  if (!props.personId) return
  hearingList.value = []
  hearingTotal.value = 0
  try {
    const params = {
      personId: props.personId,
      pageNum: hearingCurrentPage.value,
      pageSize: hearingPageSize,
      sortField: 'createTime',
      sortOrder: 'desc',
    }
    if (!selectedDomains.value.includes('all')) {
      params.domainIds = selectedDomains.value
    }
    if (!selectedTimes.value.includes('all')) {
      params.years = selectedTimes.value.map(Number)
    }
    const res = await getPersonTestimonies(params)
    if (res.code === 200 && res.data && res.data.content) {
      hearingList.value = res.data.content
      hearingTotal.value = res.data.totalElements || 0
    }
  } catch (error) {
    console.error('获取听证会数据失败:', error)
  }
}

function handleHearingPageChange(page) {
  hearingCurrentPage.value = page
  loadHearings()
}

// ====== 原有逻辑 ======
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') ? '' : selectedDomains.value,
    years: selectedTimes.value.includes('all') ? '' : selectedTimes.value.map(Number),
  }
  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 (!props.personId) return
  newsList.value = []
  totalNews.value = 0
  loading.value = true
  try {
    const params = buildParams({ includeSearchText: true })
    const res = await getFindingsReport(props.personId, params)
    if (res.code === 200 && res.data && res.data.content) {
      newsList.value = res.data.content.map(item => ({
        reportId: item.reportId || item.id,
        name: item.name || item.reportName || item.title || '',
        content: item.content || item.description || '',
        imageUrl: item.imageUrl || '',
        time: item.time || item.publishTime || item.publishDate || '',
        sourceName: item.sourceName || '',
        industryList: item.industryList || [],
      }))
      totalNews.value = res.data.totalElements || 0
    }
  } finally {
    loading.value = false
  }
}

async function loadProjects() {
  if (!props.personId) return
  projectList.value = []
  totalProjects.value = 0
  loading.value = true
  try {
    const params = buildParams()
    const res = await getInvestigationProject(props.personId, params)
    if (res.code === 200 && res.data && res.data.content) {
      projectList.value = res.data.content.map(item => ({
        reportId: item.projectId || item.id,
        name: item.name || item.projectName || item.title || '',
        content: item.description || item.content || '',
        imageUrl: item.imageUrl || '',
        time: item.time || item.publishTime || item.publishDate || '',
        sourceName: item.sourceName || '',
        industryList: item.industryList || [],
      }))
      totalProjects.value = res.data.totalElements || 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 if (val === 'capital') {
    loadProjects()
  } else if (val === 'hearing') {
    loadHearings()
  }
})

watch(
  () => [selectedDomains.value, selectedTimes.value],
  () => {
    currentPage.value = 1
    hearingCurrentPage.value = 1
    if (activeTab.value === 'local') {
      loadNews()
    } else if (activeTab.value === 'capital') {
      loadProjects()
    } else if (activeTab.value === 'hearing') {
      loadHearings()
    }
  },
  { 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;
}

/* ====== 听证会布局 ====== */
.hearing-right {
  flex: 1;
  min-width: 0;
}

.hearing-card-box {
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(234, 236, 238, 1);
  border-radius: 10px;
  box-shadow: 0px 0px 20px 0px rgba(94, 95, 95, 0.1);
}

.hearing-card-content {
  padding: 33px 36px 27px 37px;
}

.hearing-card-item {
  width: 100%;
  display: flex;
}

.hearing-card-img {
  width: 56px;
  height: 77px;
  margin-right: 22px;
  flex-shrink: 0;
  background: rgba(234, 236, 238, 1);
  border-radius: 4px;
  object-fit: cover;
}

.hearing-card-text {
  display: flex;
  flex-direction: column;
}

.hearing-card-title {
  color: rgb(59, 65, 75);
  font-size: 18px;
  font-weight: 700;
  line-height: 22px;
  margin-bottom: 2px;
  cursor: pointer;
}

.hearing-card-time {
  color: rgb(95, 101, 108);
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;
  margin-bottom: 7px;
}

.hearing-card-tags {
  display: flex;
  gap: 8px;
  height: 24px;
}

.hearing-divider {
  height: 1px;
  background: rgb(234, 236, 238);
  margin: 16px 0;
}

.hearing-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hearing-footer-info {
  color: rgba(132, 136, 142, 1);
  font-size: 14px;
  font-weight: 400;
  line-height: 18px;
}

/* 成果分析 & 听证会 empty 对齐左侧筛选栏，预留底部翻页空间 */
.news-main .empty-aligned {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 33px;
  height: calc(100% - 76px);
}
.hearing-card-content .empty-aligned {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 0;
}
</style>
