<template>
  <div class="potential-news-root"> 
    <div class="pn-analysis">
      <PotentialNewsAnalysis :keywords="keywords" />
    </div>
 
    <div class="pn-list">
      <PotentialNewsList
        :news-list="newsList"
        :total="total"
        :current-page="currentPage"
        :page-size="10"
        :keyword="searchKeyword"
        :loading="loading"
        @page-change="handlePageChange"
        @search="handleSearch"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import PotentialNewsList from './PotentialNewsList.vue'
import PotentialNewsAnalysis from './PotentialNewsAnalysis.vue'
import { getPotentialNewsList, getPotentialNewsKeywords } from '@/api/bill/billHome.js'

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

const newsList = ref([])
const total = ref(0)
const currentPage = ref(1)
const keywords = ref([])
const searchKeyword = ref('')
const loading = ref(false)

const COLORS = ['red', 'cyan', 'gold', 'blue', 'volcano']

async function loadNews(page = 1) {
  if (!personId.value) return
  loading.value = true
  currentPage.value = page
  const params = {
    currentPage: page - 1,
    pageSize: 10,
  }
  if (searchKeyword.value) {
    params.searchText = searchKeyword.value
  }
  try {
    const res = await getPotentialNewsList(personId.value, params)
    if (res.code === 200 && res.data) {
      newsList.value = res.data.content || []
      total.value = res.data.totalElements || 0
    } else {
      newsList.value = []
      total.value = 0
    }
  } finally {
    loading.value = false
  }
}

async function loadKeywords() {
  if (!personId.value) return
  const res = await getPotentialNewsKeywords(personId.value)
  if (res.code === 200 && res.data) {
    keywords.value = res.data.map((item, index) => ({
      label: item.clause,
      value: item.count,
      color: COLORS[index % COLORS.length],
    }))
  }
}

async function handlePageChange(page) {
  await loadNews(page)
}

async function handleSearch(keyword) {
  searchKeyword.value = keyword
  await loadNews(1)
}

onMounted(async () => {
  if (!personId.value) return
  await Promise.all([loadNews(), loadKeywords()])
})
</script>

<style scoped>
.potential-news-root {
  display: flex;
  gap: 16px;
  width: 100%;
  font-family: 'Source Han Sans CN', 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  color: rgba(59, 65, 75, 1);
}
 
.pn-analysis {
  width: 430px;
  flex-shrink: 0;
}
 
.pn-list {
  flex: 1;
  min-width: 0;
}
</style>
