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

    <div class="home-year-bar">
      <label class="home-year-bar__label">统计年份</label>
      <select
        v-model="statYear"
        class="home-year-bar__select"
        :disabled="loading"
        @change="onYearChange"
      >
        <option v-for="y in availableYears" :key="y" :value="String(y)">{{ y }}年</option>
      </select>
    </div> -->

    <div class="screen-page--home-column">
      <div class="screen-page--home-column-top">
        <div class="top_title">产值总览 ལས་རྩོམ་ཐོག་མའི་དོ་དམ།</div>
        <div class="top_content">
          <div class="content_1">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.inventoryTotal" /> 头
            </div>
            <div class="content_title"><div>牦牛存栏总量</div></div>
          </div>
          <div class="content_2">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.annualOutbound" /> 头
            </div>
            <div class="content_title"><div>牦牛年出栏量</div></div>
          </div>
          <div class="content_3">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.pastureCount" /> 个
            </div>
            <div class="content_title"><div>牧场数量</div></div>
          </div>
          <div class="content_4">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.grasslandCount" /> 个
            </div>
            <div class="content_title"><div>草场数量</div></div>
          </div>
        </div>
        <div class="top_content">
          <div class="content_1">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.grasslandAreaMu" format="area" /> 亩
            </div>
            <div class="content_title"><div>草场面积</div></div>
          </div>
          <div class="content_2">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.supplierCount" /> 个
            </div>
            <div class="content_title"><div>供应商数量</div></div>
          </div>
          <div class="content_3">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.distributorCount" /> 个
            </div>
            <div class="content_title"><div>承销商数量</div></div>
          </div>
          <div class="content_4">
            <div class="content_num">
              <ScreenScrollNumber :value="overview?.tradeMarketCount" /> 个
            </div>
            <div class="content_title"><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="inventoryChartOption" />
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">牦牛年龄结构 གཡག་རྒྱས་ཀྱི་གཏོང་གཞི།</div>
          <div class="flex_content">
            <ScreenChart :option="ageChartOption" />
          </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="outboundChartOption" />
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">草场类型占比 རྩྭ་གཞི་རིགས་ཀྱི་ཆ་ཤས་བརྒྱ་ཆ།</div>
          <div class="flex_content flex_content--grassland">
            <div class="grassland-stats">
              <div class="grassland-stat grassland-stat--available">
                <div class="grassland-stat__label">可用草场数</div>
                <div class="grassland-stat__value">{{ display(dashboardGrassland?.availableCount) }}</div>
              </div>
              <div class="grassland-stat grassland-stat--inuse">
                <div class="grassland-stat__label">已用草场数</div>
                <div class="grassland-stat__value">{{ display(dashboardGrassland?.inUseCount) }}</div>
              </div>
            </div>
            <div class="grassland-chart">
              <ScreenChart :option="grasslandChartOption" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="screen-page--home-column">
      <div class="screen-page--home-column-right">
        <div class="top_title">线下服务预约 ཕྱི་སྒྲིག་ཞབས་ཞུ་གསུམ་འདུག</div>
        <div class="top_flex">
          <div class="top_flex_left">
            <div class="yu">
              <div class="yu_title">兽医人员</div>
              <div class="yu_num">
                <strong>{{ display(appointment?.annualVetCount) }}</strong> 人
              </div>
            </div>
            <div class="yu">
              <div class="yu_title">专家人员</div>
              <div class="yu_num">
                <strong>{{ display(appointment?.annualExpertCount) }}</strong> 人
              </div>
            </div>
            <div class="yu">
              <div class="yu_title">诊疗机构</div>
              <div class="yu_num">
                <strong>{{ display(appointment?.annualOrgCount) }}</strong> 人
              </div>
            </div>
          </div>
          <div class="top_flex_right">
            <ScreenChart :option="appointmentChartOption" />
          </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="subsidyChartOption" />
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">养殖标准 གསོལ་སྐྱོང་གི་ཚད་གཞི།</div>
          <div class="flex_content flex_content--standards">
            <div class="std-board">
              <StandardScrollRow
                v-for="tab in STANDARD_TABS"
                :key="tab.category"
                :label="tab.label"
                :items="standardLists[tab.category] || []"
              />
            </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 flex_content--agri">
            <div class="agri-panel">
              <div class="agri-side">
                <span class="agri-side__icon" aria-hidden="true" />
                <div class="agri-side__label">课程视频</div>
                <div class="agri-side__num">{{ display(agriClassroom?.videoCourseCount) }}</div>
              </div>
              <div class="agri-center">
                <div class="agri-center__ring">
                  <span class="agri-ring agri-ring--outer" aria-hidden="true" />
                  <span class="agri-ring agri-ring--mid" aria-hidden="true" />
                  <span class="agri-ring agri-ring--inner" aria-hidden="true" />
                  <div class="agri-center__body">
                    <div class="agri-center__num">{{ display(agriClassroom?.trainingContentTotal) }}</div>
                    <div class="agri-center__label">培训内容</div>
                  </div>
                </div>
              </div>
              <div class="agri-side">
                <span class="agri-side__icon" aria-hidden="true" />
                <div class="agri-side__label">实战培训</div>
                <div class="agri-side__num">{{ display(agriClassroom?.practicalTrainingCount) }}</div>
              </div>
            </div>
            <p v-if="agriClassroom && !agriClassroom.hasAgriData" class="agri-hint">本年度暂无农技数据</p>
          </div>
        </div>
        <div class="screen-page--home-column-flex-item">
          <div class="flex_title">实战培训报名 དོན་ལས་དངོས་ཀྱི་སྦྱོང་སྦྱོང་ཐུན་མོང་།</div>
          <div class="flex_content">
            <ScreenChart :option="trainingChartOption" />
          </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 StandardScrollRow from '@/components/StandardScrollRow.vue'
import { getHomeDashboard, getHomeStandards } from '@/api/home'
import {
  buildAgeStructureOption,
  buildAppointmentStackedOption,
  buildGrasslandOption,
  buildInventoryTrendOption,
  buildOutboundOption,
  buildSubsidyOption,
  buildTrainingOption
} from './chartOptions'

/** 养殖标准五类（与后端 HomeScreenStandardCategory 一致，文案对齐设计稿） */
const STANDARD_TABS = [
  { category: 'BREEDING_MGMT', label: '养殖管理' },
  { category: 'FEEDING', label: '牦牛饲喂' },
  { category: 'EQUIPMENT', label: '设备实施' },
  { category: 'TREATMENT', label: '疾病诊疗' },
  { category: 'GROWTH', label: '生长出栏' }
]

const STANDARD_FETCH_PAGE_SIZE = 50

const loading = ref(false)
const loadError = ref('')
const statYear = ref(String(new Date().getFullYear()))
const availableYears = ref([])
const overview = ref(null)
const inventoryChange = ref(null)
const appointment = ref(null)
const subsidy = ref(null)
const agriClassroom = ref(null)
const trainingTrend = ref(null)

/** 五类标准列表（每类独立请求） */
const standardLists = ref({
  BREEDING_MGMT: [],
  FEEDING: [],
  EQUIPMENT: [],
  TREATMENT: [],
  GROWTH: []
})

const inventoryChartOption = computed(() =>
  buildInventoryTrendOption(inventoryChange.value?.monthlyTrend)
)
const ageChartOption = computed(() => buildAgeStructureOption(dashboardAge.value))
const outboundChartOption = computed(() => buildOutboundOption(dashboardOutbound.value))
const grasslandChartOption = computed(() => buildGrasslandOption(dashboardGrassland.value))
const appointmentChartOption = computed(() =>
  buildAppointmentStackedOption(appointment.value?.monthlyStacked)
)
const subsidyChartOption = computed(() =>
  buildSubsidyOption(subsidy.value?.typeStats, subsidy.value?.hasSubsidyData)
)
const trainingChartOption = computed(() => buildTrainingOption(trainingTrend.value))

const dashboardAge = ref([])
const dashboardOutbound = ref([])
const dashboardGrassland = ref(null)

function formatNum(val, fractionDigits) {
  if (val === null || val === undefined || val === '') {
    return '0'
  }
  const n = Number(val)
  if (Number.isNaN(n)) {
    return '0'
  }
  if (typeof fractionDigits === 'number') {
    return n.toLocaleString('zh-CN', {
      minimumFractionDigits: fractionDigits,
      maximumFractionDigits: fractionDigits
    })
  }
  return n.toLocaleString('zh-CN')
}

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

/** 应用看板主数据 */
function applyDashboard(data) {
  if (!data) {
    return
  }
  if (data.statYear) {
    statYear.value = String(data.statYear)
  }
  availableYears.value = data.availableYears?.length
    ? [...data.availableYears]
    : [Number(statYear.value)]
  overview.value = data.industryOverview || null
  inventoryChange.value = data.inventoryChange || null
  dashboardAge.value = data.ageStructure || []
  dashboardOutbound.value = data.outboundMonthly || []
  dashboardGrassland.value = data.grassland || null
  appointment.value = data.appointment || null
  subsidy.value = data.subsidy || null
  agriClassroom.value = data.agriClassroom || null
  trainingTrend.value = data.trainingTrend || null
}

/** 拉取看板 + 标准列表（切换年份时） */
async function fetchDashboard() {
  loading.value = true
  loadError.value = ''
  try {
    const res = await getHomeDashboard(statYear.value)
    applyDashboard(res.data)
    await fetchAllStandards()
  } catch (e) {
    loadError.value = e?.message || '看板数据加载失败'
  } finally {
    loading.value = false
  }
}

/** 五类养殖标准并行请求（每类一页，供各行独立轮播） */
async function fetchAllStandards() {
  const empty = {
    BREEDING_MGMT: [],
    FEEDING: [],
    EQUIPMENT: [],
    TREATMENT: [],
    GROWTH: []
  }
  try {
    const results = await Promise.all(
      STANDARD_TABS.map((tab) =>
        getHomeStandards({
          statYear: statYear.value,
          category: tab.category,
          pageNum: 1,
          pageSize: STANDARD_FETCH_PAGE_SIZE
        })
          .then((res) => ({ category: tab.category, rows: res.rows || [] }))
          .catch(() => ({ category: tab.category, rows: [] }))
      )
    )
    const next = { ...empty }
    for (const { category, rows } of results) {
      next[category] = rows
    }
    standardLists.value = next
  } catch (e) {
    standardLists.value = empty
    if (!loadError.value) {
      loadError.value = e?.message || '标准列表加载失败'
    }
  }
}

function onYearChange() {
  fetchDashboard()
}

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

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

.screen-page--home.is-loading {
  opacity: 0.92;
}

.home-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;
}

.home-year-bar {
  position: absolute;
  top: 8px;
  right: 24px;
  z-index: 5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.home-year-bar__label {
  font-size: 12px;
  color: var(--screen-text-secondary, #a8d4c8);
}

.home-year-bar__select {
  min-width: 88px;
  height: 28px;
  padding: 0 8px;
  font-size: 13px;
  color: #e8eef5;
  background: rgba(4, 48, 40, 0.85);
  border: 1px solid var(--screen-line-dim, rgba(61, 217, 176, 0.42));
  border-radius: 4px;
  outline: none;
}

.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;
  background: url('../../assets/home/big_box.png') no-repeat center center;
  background-size: 100% 100%;
}

.screen-page--home-column-right {
  width: 617px;
  height: 201px;
  background: url('../../assets/home/box_right.png') no-repeat center center;
  background-size: 100% 100%;
}

.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;
}

.top_content {
  width: 100%;
  height: 75px;
  display: flex;
  flex-direction: row;
}

.content_1 {
  width: 180px;
  height: 100%;
}

.content_2 {
  width: 116px;
  height: 100%;
}

.content_3 {
  width: 190px;
  height: 100%;
}

.content_4 {
  width: 116px;
  height: 100%;
}

.content_num {
  text-align: center;
  font-size: 16px;
  color: #fff;
  line-height: 30px;
  margin: 10px 0;
}

.content_num :deep(.screen-scroll-number) {
  font-size: 20px;
}

.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 strong {
  font-size: 20px;
  background: linear-gradient(to bottom, #98e9aa, #ecd27b);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.content_title {
  text-align: center;
  font-size: 12px;
  color: #fff;
}

.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: 2px 4px;
}

.flex_content :deep(.screen-chart) {
  min-height: 0;
  height: 100%;
}

.top_flex {
  width: 100%;
  height: 155px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.top_flex_left {
  width: 160px;
  height: 100%;
  box-sizing: border-box;
  padding: 8px 0;
}

.top_flex_right {
  width: 457px;
  height: 100%;
  box-sizing: border-box;
  padding: 0 2px;
}

.top_flex_right :deep(.screen-chart) {
  min-height: 0;
  height: 100%;
}

.yu {
  width: 100%;
  height: 48px;
  text-align: center;
}

.yu_title {
  font-size: 14px;
  color: #fff;
  line-height: 20px;
}

.yu_num {
  text-align: center;
  font-size: 12px;
  color: #fff;
}

.yu_num strong {
  font-size: 20px;
  background: linear-gradient(to bottom, #98e9aa, #ecd27b);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.flex_content--standards {
  display: flex;
  flex-direction: column;
  padding: 2px 4px;
  overflow: hidden;
  box-sizing: border-box;
}

.std-board {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 0;
  min-height: 0;
  max-height: 100%;
  padding: 2px 4px;
  overflow: hidden;
  border: 1px solid rgba(61, 217, 176, 0.22);
  background: linear-gradient(
    180deg,
    rgba(8, 36, 30, 0.5) 0%,
    rgba(4, 18, 16, 0.35) 100%
  );
}

.std-board :deep(.std-row:not(:last-child)) {
  border-bottom: 1px solid rgba(61, 217, 176, 0.1);
}

.flex_content--agri {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: center;
  padding: 4px 8px;
  box-sizing: border-box;
}

.agri-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 4px;
  min-height: 0;
  padding: 6px 10px;
  position: relative;
  border: 1px solid rgba(61, 217, 176, 0.28);
  background: linear-gradient(
    180deg,
    rgba(8, 36, 30, 0.55) 0%,
    rgba(4, 20, 18, 0.35) 100%
  );
}

.agri-panel::before,
.agri-panel::after {
  content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  border-color: rgba(69, 240, 184, 0.75);
  border-style: solid;
  pointer-events: none;
}

.agri-panel::before {
  top: -1px;
  left: -1px;
  border-width: 2px 0 0 2px;
}

.agri-panel::after {
  bottom: -1px;
  right: -1px;
  border-width: 0 2px 2px 0;
}

.agri-side {
  flex: 1;
  min-width: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.agri-side__icon {
  display: block;
  width: 0;
  height: 0;
  margin-bottom: 6px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 7px solid #45f0b8;
  filter: drop-shadow(0 0 5px rgba(69, 240, 184, 0.85));
}

.agri-side__label {
  font-size: 12px;
  color: #fff;
  line-height: 18px;
  letter-spacing: 0.5px;
}

.agri-side__num {
  margin-top: 4px;
  font-size: 26px;
  font-weight: 700;
  color: #fff;
  line-height: 1.1;
  text-shadow: 0 0 12px rgba(69, 240, 184, 0.35);
}

.agri-center {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.agri-center__ring {
  position: relative;
  width: 92px;
  height: 92px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.agri-ring {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  border: 1px solid rgba(69, 240, 184, 0.45);
  box-shadow: 0 0 10px rgba(69, 240, 184, 0.25);
  pointer-events: none;
}

.agri-ring--outer {
  width: 92px;
  height: 92px;
  border-color: rgba(69, 240, 184, 0.2);
  border-width: 2px;
  box-shadow: 0 0 18px rgba(69, 240, 184, 0.35);
}

.agri-ring--mid {
  width: 76px;
  height: 76px;
  border-style: dashed;
  opacity: 0.75;
}

.agri-ring--inner {
  width: 62px;
  height: 62px;
  border-color: rgba(69, 240, 184, 0.55);
}

.agri-center__body {
  position: relative;
  z-index: 1;
  text-align: center;
}

.agri-center__num {
  font-size: 28px;
  font-weight: 700;
  color: #fff;
  line-height: 1.1;
  text-shadow: 0 0 14px rgba(69, 240, 184, 0.45);
}

.agri-center__label {
  margin-top: 2px;
  font-size: 11px;
  color: #fff;
  letter-spacing: 0.5px;
}

.agri-hint {
  flex-shrink: 0;
  width: 100%;
  margin: 4px 0 0;
  text-align: center;
  font-size: 11px;
  color: #6a9f90;
}

.flex_content--grassland {
  display: flex;
  flex-direction: column;
  padding: 2px 6px 4px;
}

.grassland-stats {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
  margin-bottom: 2px;
}

.grassland-stat {
  flex: 1;
  text-align: center;
  padding: 3px 4px;
  background: linear-gradient(
    180deg,
    rgba(12, 52, 44, 0.75) 0%,
    rgba(6, 32, 28, 0.45) 100%
  );
  border-radius: 2px;
}

.grassland-stat--available .grassland-stat__label {
  color: #6eb5ff;
}

.grassland-stat--inuse .grassland-stat__label {
  color: #ecd27b;
}

.grassland-stat__label {
  font-size: 11px;
  line-height: 16px;
}

.grassland-stat__value {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  line-height: 22px;
}

.grassland-chart {
  flex: 1;
  min-height: 0;
}

.grassland-chart :deep(.screen-chart) {
  min-height: 0;
  height: 100%;
}
</style>
