<template>
  <div class="screen-page lr-page" :class="{ 'is-loading': loading }">
    <div v-if="loadError" class="lr-error">{{ loadError }}</div>

    <!-- 左栏：核心总览 + 活跃/用户/分类/模型 -->
    <div class="screen-page--home-column">
      <div class="screen-page--home-column-top">
        <div class="top_title">核心数据总览 གཙོ་བོའི་གནས་ཚད་བསྡུས་གསལ།</div>
        <div class="lr-overview-grid">
          <div
            v-for="item in overviewItems"
            :key="item.key"
            class="lr-overview-cell"
          >
            <div class="content_title"><div>{{ item.label }}</div></div>
            <div class="content_num">
              <ScreenScrollNumber
                class="content_num__value"
                :value="item.rawValue"
                :format="item.format"
              />
              <span v-if="item.unit" class="content_num__unit">{{ item.unit }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="screen-page--home-column-flex">
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">活跃度趋势 འགྲོ་འདུག་གོམ་སྟངས་རྒྱུན་སྟངས།</div>
          <div class="flex_content">
            <ScreenChart :option="activityTrendOption" />
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">用户结构分析 སྤྱོད་མིའི་གོ་སྐབས་དཔྱད་པ།</div>
          <div class="flex_content flex_content--user">
            <div class="lr-rings">
              <div class="lr-ring">
                <div class="lr-ring__figure">
                  <div class="lr-ring__outer">
                    <div class="lr-ring__inner">
                      <div class="lr-ring__val">
                        <strong>{{ userStructureDisplay.newCount }}</strong>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="lr-ring__label">新用户人数</div>
                <div v-if="userStructureDisplay.newRatio" class="lr-ring__ratio">
                  占比 {{ userStructureDisplay.newRatio }}
                </div>
              </div>
              <div class="lr-ring">
                <div class="lr-ring__figure">
                  <div class="lr-ring__outer">
                    <div class="lr-ring__inner">
                      <div class="lr-ring__val">
                        <strong>{{ userStructureDisplay.oldCount }}</strong>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="lr-ring__label">老用户人数</div>
                <div v-if="userStructureDisplay.oldRatio" class="lr-ring__ratio">
                  占比 {{ userStructureDisplay.oldRatio }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="screen-page--home-column-flex">
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">提问分类占比 དྲིས་ལན་དབྱེ་རྩིས་བགོ་སྟངས།</div>
          <div class="flex_content">
            <ScreenChart :option="categoryShareOption" />
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">模型调用分析 དཔེ་གཞི་འབྲི་རྩོམ་དཔྱད་པ།</div>
          <div class="flex_content">
            <ScreenChart :option="modelCallOption" />
          </div>
        </div>
      </div>
    </div>

    <!-- 右栏：分时热度 + 分布/榜单/词云 -->
    <div class="screen-page--home-column">
      <div class="screen-page--home-column-right lr-heat-panel">
        <div class="top_title">分时使用热度 དུས་སྐོར་སྤྱོད་སྟོབས་ཚད།</div>
        <div class="lr-heat-chart">
          <ScreenChart :option="hourlyHeatOption" />
        </div>
      </div>

      <div class="screen-page--home-column-flex">
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">会话提问数量分布 གོ་སྐབས་དྲིས་གྲངས་ཁྱབ་སྤེལ།</div>
          <div class="flex_content">
            <ScreenChart :option="sessionReplyOption" />
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">会话状态分布 གོ་སྐབས་གནས་སྟངས་ཁྱབ་སྤེལ།</div>
          <div class="flex_content">
            <ScreenChart :option="replyStatusOption" />
          </div>
        </div>
      </div>

      <div class="screen-page--home-column-flex">
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">热门问题榜单 ཡོངས་གྲགས་དྲིས་ལན་གསལ་ཐོ།</div>
          <div class="flex_content flex_content--list">
            <ul v-if="hotTopics.length" class="lr-hot-list">
              <li v-for="(item, idx) in hotTopics" :key="item.categoryCode + '-' + idx" class="lr-hot-list__row">
                <span class="lr-hot-list__rank" :class="'lr-hot-list__rank--' + (idx + 1)">{{ idx + 1 }}</span>
                <span class="lr-hot-list__name" :title="item.categoryName">{{ item.categoryName }}</span>
                <span class="lr-hot-list__meta">
                  <strong>{{ formatNum(item.count) }}</strong>
                  <em v-if="item.ratio != null">{{ formatRatio(item.ratio) }}%</em>
                </span>
              </li>
            </ul>
            <span v-else class="lr-empty">暂无榜单数据</span>
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">高频关键词 མང་དུ་སྦྱོང་བའི་ཚིག་གཙོ།</div>
          <div class="flex_content">
            <ScreenChart :option="wordCloudOption" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import ScreenChart from '@/components/ScreenChart.vue'
import ScreenScrollNumber from '@/components/ScreenScrollNumber.vue'
import { getLivestockResourceDashboard } from '@/api/livestockResources'
import {
  buildActivityTrendOption,
  buildCategoryShareOption,
  buildHourlyHeatOption,
  buildModelCallOption,
  buildReplyStatusOption,
  buildSessionReplyOption,
  buildWordCloudOption
} from './chartOptions'

const loading = ref(false)
const loadError = ref('')
const statYear = ref(String(new Date().getFullYear()))

const overview = ref(null)
const activityTrend = ref(null)
const userStructure = ref(null)
const categoryShare = ref(null)
const modelCallAnalysis = ref([])
const hourlyHeat = ref(null)
const sessionReplyDistribution = ref([])
const replyStatusDistribution = ref(null)
const hotTopics = ref([])
const topKeywords = ref([])

const activityTrendOption = computed(() => buildActivityTrendOption(activityTrend.value))
const categoryShareOption = computed(() => buildCategoryShareOption(categoryShare.value))
const modelCallOption = computed(() => buildModelCallOption(modelCallAnalysis.value))
const hourlyHeatOption = computed(() => buildHourlyHeatOption(hourlyHeat.value))
const sessionReplyOption = computed(() => buildSessionReplyOption(sessionReplyDistribution.value))
const replyStatusOption = computed(() => buildReplyStatusOption(replyStatusDistribution.value))
const wordCloudOption = computed(() => buildWordCloudOption(topKeywords.value))

/** 核心总览 8 项（布局对齐交易总览，4 列 × 2 行） */
const overviewItems = computed(() => {
  const o = overview.value
  return [
    { key: 'totalUsers', label: '累计使用用户', unit: '人', rawValue: o?.totalUsers, format: 'int' },
    { key: 'todayActiveUsers', label: '今日活跃用户', unit: '人', rawValue: o?.todayActiveUsers, format: 'int' },
    { key: 'todayNewUsers', label: '日新增用户', unit: '人', rawValue: o?.todayNewUsers, format: 'int' },
    { key: 'totalSessions', label: '累计会话数', unit: '次', rawValue: o?.totalSessions, format: 'int' },
    { key: 'todaySessions', label: '今日会话数', unit: '次', rawValue: o?.todaySessions, format: 'int' },
    { key: 'totalQuestionCount', label: '累计提问量', unit: '次', rawValue: o?.totalQuestionCount, format: 'int' },
    { key: 'todayQuestionCount', label: '今日提问量', unit: '次', rawValue: o?.todayQuestionCount, format: 'int' },
    {
      key: 'avgResponseSeconds',
      label: '平均响应时长',
      unit: '秒',
      rawValue: o?.avgResponseSeconds,
      format: 'area'
    }
  ]
})

/** 用户结构双圆环：人数 + 占比（对齐共同富裕「数字赋能」圆环样式） */
const userStructureDisplay = computed(() => {
  const u = userStructure.value
  const newRatio = u?.newUserRatio != null ? `${formatRatio(u.newUserRatio)}%` : ''
  const oldRatio = u?.oldUserRatio != null ? `${formatRatio(u.oldUserRatio)}%` : ''
  return {
    newCount: display(u?.newUserCount),
    oldCount: display(u?.oldUserCount),
    newRatio,
    oldRatio
  }
})

function formatNum(val) {
  if (val === null || val === undefined || val === '') {
    return '0'
  }
  const n = Number(val)
  if (Number.isNaN(n)) {
    return '0'
  }
  return n.toLocaleString('zh-CN')
}

function display(val) {
  return formatNum(val)
}

function formatRatio(val) {
  const n = Number(val)
  if (Number.isNaN(n)) {
    return '0.0'
  }
  return n.toFixed(1)
}

/** 兼容拦截器返回 AjaxResult，或直接返回 data 本体 */
function resolveDashboard(res) {
  if (!res) {
    return null
  }
  const payload = res.data !== undefined ? res.data : res
  if (payload && payload.data && payload.overview == null && payload.data.overview) {
    return payload.data
  }
  return payload
}

function normalizeActivityTrend(raw) {
  if (!raw) {
    return null
  }
  if (Array.isArray(raw)) {
    return { dailySeries: raw }
  }
  return raw
}

function normalizeHourlyHeat(raw) {
  if (!raw) {
    return null
  }
  if (Array.isArray(raw)) {
    return { hourlySeries: raw }
  }
  return raw
}

function normalizeReplyStatus(raw) {
  if (!raw) {
    return null
  }
  if (Array.isArray(raw)) {
    return { items: raw }
  }
  return raw
}

function pickHotTopics(data, categoryItems) {
  if (data.hotTopics?.length) {
    return data.hotTopics
  }
  return [...(categoryItems || [])]
    .filter((item) => toNum(item?.count) > 0)
    .sort((a, b) => toNum(b.count) - toNum(a.count))
    .slice(0, 5)
}

function toNum(val) {
  const n = Number(val)
  return Number.isNaN(n) ? 0 : n
}

function applyDashboard(data) {
  if (!data) {
    return
  }
  if (data.statYear) {
    statYear.value = String(data.statYear)
  }
  overview.value = data.overview || null
  activityTrend.value = normalizeActivityTrend(data.activityTrend)
  userStructure.value = data.userStructure || null
  categoryShare.value = data.categoryShare || null
  const categoryItems = data.categoryShare?.items || []
  modelCallAnalysis.value = data.modelCallAnalysis?.length
    ? data.modelCallAnalysis
    : categoryItems
  hourlyHeat.value = normalizeHourlyHeat(data.hourlyHeat)
  sessionReplyDistribution.value = data.sessionReplyDistribution || []
  replyStatusDistribution.value = normalizeReplyStatus(data.replyStatusDistribution)
  hotTopics.value = pickHotTopics(data, categoryItems)
  topKeywords.value = data.topKeywords || []
}

async function fetchDashboard() {
  loading.value = true
  loadError.value = ''
  try {
    const res = await getLivestockResourceDashboard(statYear.value)
    applyDashboard(resolveDashboard(res))
  } catch (e) {
    loadError.value = e?.message || '看板数据加载失败'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchDashboard()
})
</script>

<style scoped>
.lr-page {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.lr-page.is-loading {
  opacity: 0.92;
}

.lr-error {
  position: absolute;
  top: 4px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  padding: 4px 12px;
  font-size: 12px;
  color: #ffb4b4;
  background: rgba(80, 20, 20, 0.75);
  border-radius: 4px;
}

.screen-page--home-column {
  width: 617px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.screen-page--home-column-top {
  width: 617px;
  height: 201px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: url('../../assets/live/live.png') no-repeat center center;
  background-size: 100% 100%;
}

.screen-page--home-column-right {
  width: 617px;
  height: 201px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: url('../../assets/pro/pro.png') no-repeat center center;
  background-size: 100% 100%;
}

.lr-heat-panel {
  overflow: hidden;
}

.lr-heat-chart {
  flex: 1;
  min-height: 0;
  box-sizing: border-box;
  padding: 0 8px 8px;
}

.screen-page--home-column-flex {
  width: 617px;
  height: 223px;
  display: flex;
  justify-content: space-between;
}

.screen-page--home-column-flex-item {
  width: 304px;
  height: 223px;
  background: url('../../assets/home/mini_box.png') no-repeat center center;
  background-size: 100% 100%;
}

.top_title {
  width: 100%;
  height: 35px;
  box-sizing: border-box;
  font-size: 18px;
  color: #fff;
  line-height: 35px;
  padding-left: 100px;
  margin-bottom: 8px;
  flex-shrink: 0;
}

/* 核心总览：4 列 × 2 行，对齐交易总览样式 */
.lr-overview-grid {
  flex: 1;
  min-height: 0;
  box-sizing: border-box;
  padding: 4px 20px 12px 28px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 2px 16px;
}

.lr-overview-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  min-height: 0;
  width: 100%;
  text-align: right;
  box-sizing: border-box;
  padding-right: 6px;
}

.lr-overview-cell .content_title {
  width: 100%;
  text-align: right;
}

.lr-overview-cell .content_num {
  width: 100%;
  display: flex;
  align-items: baseline;
  justify-content: flex-end;
  gap: 4px;
  margin: 2px 0 0;
  line-height: 1.2;
}

.content_num__value {
  flex: 1;
  min-width: 0;
  text-align: right;
  font-size: 20px;
  font-weight: 600;
  background: linear-gradient(to bottom, #98e9aa, #ecd27b);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.content_num :deep(.screen-scroll-number) {
  flex: 1;
  min-width: 0;
  justify-content: flex-end;
  font-size: 20px;
  font-weight: 600;
}

.content_num :deep(.screen-scroll-number__strip),
.content_num :deep(.screen-scroll-number__sep) {
  background: linear-gradient(to bottom, #98e9aa, #ecd27b);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.content_num__unit {
  flex-shrink: 0;
  font-size: 11px;
  color: #a8d4c8;
  line-height: 1.2;
}

.content_title {
  font-size: 10px;
  color: #a8d4c8;
  line-height: 1.25;
}

.flex_title {
  width: 100%;
  box-sizing: border-box;
  height: 35px;
  font-size: 16px;
  color: #fff;
  line-height: 35px;
  padding-left: 45px;
  margin-bottom: 5px;
}

.flex_content {
  width: 100%;
  height: 180px;
  box-sizing: border-box;
  padding: 5px;
}

.flex_content--user {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px 8px;
}

/* 用户结构双圆环（对齐 commonProsperity 数字赋能 cp-ring） */
.lr-rings {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  gap: 8px;
}

.lr-ring {
  flex: 1;
  min-width: 0;
  max-width: 130px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.lr-ring__figure {
  width: 104px;
  height: 104px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lr-ring__outer {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border: 2px solid rgba(236, 210, 123, 0.22);
  background: transparent;
}

.lr-ring__inner {
  position: relative;
  width: 82%;
  height: 82%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
}

.lr-ring__inner::before {
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 50%;
  padding: 3px;
  background: linear-gradient(160deg, #45f0b8 0%, #1d9a7a 42%, #ecd27b 100%);
  -webkit-mask:
    linear-gradient(#fff 0 0) content-box,
    linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask:
    linear-gradient(#fff 0 0) content-box,
    linear-gradient(#fff 0 0);
  mask-composite: exclude;
  pointer-events: none;
}

.lr-ring__val {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 0 4px;
  box-sizing: border-box;
  text-align: center;
  line-height: 1.15;
  color: #e8eef5;
}

.lr-ring__val strong {
  font-size: 22px;
  font-weight: 600;
  letter-spacing: 0.02em;
  color: #ecd27b;
}

.lr-ring__label {
  margin-top: 6px;
  width: 100%;
  padding: 0 2px;
  box-sizing: border-box;
  font-size: 10px;
  color: #a8d4c8;
  text-align: center;
  line-height: 1.35;
}

.lr-ring__ratio {
  margin-top: 2px;
  font-size: 9px;
  color: #5ef0c8;
  text-align: center;
  line-height: 1.3;
}

.flex_content--list {
  padding: 6px 10px;
  overflow: hidden;
}

.lr-hot-list {
  list-style: none;
  margin: 0;
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.lr-hot-list__row {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 30px;
  padding: 0 4px;
  border-bottom: 1px solid rgba(61, 217, 176, 0.12);
}

.lr-hot-list__row:last-child {
  border-bottom: none;
}

.lr-hot-list__rank {
  flex-shrink: 0;
  width: 18px;
  height: 18px;
  border-radius: 3px;
  background: rgba(61, 217, 176, 0.25);
  color: #a8d4c8;
  font-size: 11px;
  line-height: 18px;
  text-align: center;
}

.lr-hot-list__rank--1 {
  background: linear-gradient(135deg, #ecd27b, #c9a030);
  color: #1a2e28;
}

.lr-hot-list__rank--2 {
  background: rgba(236, 210, 123, 0.55);
  color: #fff;
}

.lr-hot-list__rank--3 {
  background: rgba(110, 181, 255, 0.45);
  color: #fff;
}

.lr-hot-list__name {
  flex: 1;
  min-width: 0;
  font-size: 11px;
  color: #e8eef5;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.lr-hot-list__meta {
  flex-shrink: 0;
  display: flex;
  align-items: baseline;
  gap: 6px;
  font-size: 10px;
  color: #a8d4c8;
}

.lr-hot-list__meta strong {
  font-size: 12px;
  color: #5ef0c8;
  font-weight: 600;
}

.lr-hot-list__meta em {
  font-style: normal;
  color: #ecd27b;
}

.lr-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 13px;
  color: rgba(168, 212, 200, 0.75);
}
</style>
