<template>
  <div class="research-strength-content">
    <!-- 悬浮提示框 -->
    <Teleport to="body">
      <div v-if="tooltipVisible" class="chart-tooltip"
        :style="{ left: tooltipPosition.x + 10 + 'px', top: tooltipPosition.y - 30 + 'px' }">
        <span class="tooltip-year">{{ tooltipContent.year }}年</span>
        <span class="tooltip-value">{{ tooltipContent.value }}</span>
      </div>
    </Teleport>
    <!-- 第一行 -->
    <div class="chart-row">
<!-- 专利数量统计 - 柱状图 -->
      <AnalysisBox title="专利数量统计" width="100%" height="500px" :show-all-btn="false" class="chart-box">
        <div class="chart-container">
          <div class="bar-chart">
            <div class="y-axis">
              <span v-for="tick in patentYAxisTicks" :key="tick">{{ tick }}</span>
            </div>
            <div class="chart-area">
              <div class="bars">
                <div v-for="(item, index) in patentData" :key="index" class="bar-item">
                  <span class="bar-label">{{ item.year }}</span>
                  <div class="bar" :style="{ height: `${item.value / patentMaxValue * 100}%`, background: getPatentBarGradient() }"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <ChartSummary text="哈佛大学近十年专利数量呈现稳定增长趋势，尤其在生物技术和人工智能领域表现突出，2025年达到历史新高。" />
      </AnalysisBox>

<!-- 论文数量统计 - 面积图 -->
      <AnalysisBox title="论文数量统计" width="100%" height="500px" :show-all-btn="false" class="chart-box">
        <div class="chart-container">
          <div class="area-chart">
            <div class="y-axis">
              <span v-for="tick in paperYAxisTicks" :key="tick">{{ tick }}</span>
            </div>
            <div class="chart-area">
              <svg class="area-svg" viewBox="0 0 700 240" preserveAspectRatio="none">
                <defs>
                  <linearGradient id="areaGradient1" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stop-color="rgba(255, 149, 77, 0.6)" />
                    <stop offset="100%" stop-color="rgba(255, 149, 77, 0.1)" />
                  </linearGradient>
                </defs>
                <path :d="paperAreaPath" fill="url(#areaGradient1)" />
                <path :d="paperLinePath" fill="none" stroke="#FF954D" stroke-width="2" />
                <!-- 小圆圈节点 -->
                <g class="data-points">
                  <circle v-for="(point, idx) in paperPoints" :key="idx"
                    :cx="point.x" :cy="point.y" r="4"
                    fill="#FFFFFF" stroke="#FF954D" stroke-width="2"
                    class="data-point"
                    @mouseenter="showTooltip($event, paperYears[idx], paperData[idx]?.value)"
                    @mouseleave="hideTooltip" />
                </g>
              </svg>
              <div class="x-labels">
                <span v-for="year in paperYears" :key="year">{{ year }}</span>
              </div>
            </div>
          </div>
        </div>
        <ChartSummary text="哈佛大学近十年论文发表数量持续增长，高质量论文占比显著提升，特别是在医学和工程领域。" />
      </AnalysisBox>
    </div>

    <!-- 第二行 -->
    <div class="chart-row">
      <!-- 领域实力分布 - 雷达图 -->
      <AnalysisBox title="领域实力分布" width="100%" height="500px" :show-all-btn="false" class="chart-box">
        <div class="chart-container radar-container">
          <div class="radar-chart">
            <svg class="radar-svg" viewBox="0 0 300 300">
              <!-- 六边形背景网格 -->
              <g class="radar-grid">
                <polygon v-for="(scale, i) in [1, 0.8, 0.6, 0.4, 0.2]" :key="i" 
                  :points="getHexagonPoints(150, 150, 100 * scale)" 
                  fill="none" 
                  stroke="#E5E7EB" 
                  stroke-width="1" />
              </g>
              <!-- 轴线 -->
              <g class="radar-axes">
                <line v-for="(_, i) in 6" :key="i" 
                  x1="150" y1="150" 
                  :x2="150 + 100 * Math.cos(Math.PI / 2 - i * Math.PI / 3)" 
                  :y2="150 - 100 * Math.sin(Math.PI / 2 - i * Math.PI / 3)" 
                  stroke="#E5E7EB" 
                  stroke-width="1" />
              </g>
              <!-- 数据区域 -->
              <polygon :points="radarDataPoints" fill="rgba(5, 95, 194, 0.2)" stroke="#055FC2" stroke-width="2" />
            </svg>
            <!-- 标签 -->
            <div class="radar-labels">
              <span class="label label-top">集成电路</span>
              <span class="label label-top-right">生物科技</span>
              <span class="label label-bottom-right">人工智能</span>
              <span class="label label-bottom">通信网络</span>
              <span class="label label-bottom-left">量子科技</span>
              <span class="label label-top-left">能源领域</span>
            </div>
          </div>
        </div>
        <ChartSummary text="哈佛大学在生物科技和人工智能领域实力最为突出，同时在量子科技和能源领域也有显著优势，体现了其跨学科研究能力。" />
      </AnalysisBox>

<!-- 大学经费增长情况 - 面积图 -->
      <AnalysisBox title="大学经费增长情况" width="100%" height="500px" :show-all-btn="false" class="chart-box">
        <div class="chart-container">
          <div class="area-chart">
            <div class="y-axis">
              <span v-for="tick in fundingYAxisTicks" :key="tick">{{ tick }}</span>
            </div>
            <div class="chart-area">
              <svg class="area-svg" viewBox="0 0 700 240" preserveAspectRatio="none">
                <defs>
                  <linearGradient id="areaGradient2" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stop-color="rgba(34, 197, 94, 0.6)" />
                    <stop offset="100%" stop-color="rgba(34, 197, 94, 0.1)" />
                  </linearGradient>
                </defs>
                <path :d="fundingAreaPath" fill="url(#areaGradient2)" />
                <path :d="fundingLinePath" fill="none" stroke="#22C55E" stroke-width="2" />
                <!-- 小圆圈节点 -->
                <g class="data-points">
                  <circle v-for="(point, idx) in fundingPoints" :key="idx"
                    :cx="point.x" :cy="point.y" r="4"
                    fill="#FFFFFF" stroke="#22C55E" stroke-width="2"
                    class="data-point"
                    @mouseenter="showTooltip($event, fundingYears[idx], fundingData[idx]?.value)"
                    @mouseleave="hideTooltip" />
                </g>
              </svg>
              <div class="x-labels">
                <span v-for="year in fundingYears" :key="year">{{ year }}</span>
              </div>
            </div>
          </div>
        </div>
        <ChartSummary text="哈佛大学经费近十年保持稳定增长，研究经费占比逐年提高，2023年总经费突破50亿美元。" />
      </AnalysisBox>
    </div>

    <!-- 第三行 -->
    <div class="chart-row">
      <!-- 经费来源分布 - 环形饼图 -->
      <AnalysisBox title="经费来源分布" width="100%" height="500px" :show-all-btn="false" class="chart-box">
        <div class="chart-container pie-container">
          <div class="pie-chart">
            <svg class="pie-svg" viewBox="0 0 200 200">
              <circle cx="100" cy="100" r="70" fill="none" stroke="#E5E7EB" stroke-width="30" />
              <!-- 各部分 -->
              <circle v-for="(item, index) in pieData" :key="index"
                cx="100" cy="100" r="70" fill="none"
                :stroke="item.color"
                stroke-width="30"
                :stroke-dasharray="`${item.percent * 4.4} 440`"
                :stroke-dashoffset="getPieOffset(index)"
                transform="rotate(-90 100 100)" />
            </svg>
          </div>
          <div class="pie-legend">
            <div v-for="(item, index) in pieData" :key="index" class="legend-item">
              <span class="legend-dot" :style="{ backgroundColor: item.color }"></span>
              <span class="legend-label">{{ item.name }}</span>
              <span class="legend-value">{{ item.percent }}%</span>
            </div>
          </div>
        </div>
        <ChartSummary text="哈佛大学经费主要来源于捐赠基金、政府拨款和企业合作项目，捐赠基金占比最大，体现了其强大的校友支持。" />
      </AnalysisBox>

      <!-- 学院经费分配排序 - 横向条形图 -->
      <AnalysisBox title="学院经费分配排序" width="100%" height="500px" :show-all-btn="false" class="chart-box">
        <div class="chart-container horizontal-bar-container">
          <div class="unit-label">（亿美元）</div>
          <div class="horizontal-bars">
            <div v-for="(item, index) in collegeData" :key="index" class="horizontal-bar-item">
              <span class="bar-name">{{ item.name }}</span>
              <div class="bar-wrapper">
                <div class="bar-fill" :style="{ width: `${item.value / 110 * 100}%`, background: getBarGradient(index) }"></div>
              </div>
              <span class="bar-value" :style="{ color: index < 2 ? '#CE4F51' : '#055FC2' }">{{ item.value }}</span>
            </div>
          </div>
        </div>
        <ChartSummary text="医学院和工程学院获得的经费分配最多，体现了学校对医学和工程学科的重点投入，这两个学院也是科研成果最丰富的学院。" />
      </AnalysisBox>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject, watch } from 'vue'
import AnalysisBox from '@/components/base/boxBackground/analysisBox.vue'
import ChartSummary from '../components/ChartSummary.vue'
import { getPatentList, getPaperList, getStudyFieldList, getFundGrowth } from '@/api/innovationSubject/overview.js'

// 从父组件注入 orgId
const orgId = inject('orgId', ref(''))

// Tooltip 状态
const tooltipVisible = ref(false)
const tooltipContent = ref({ year: '', value: 0 })
const tooltipPosition = ref({ x: 0, y: 0 })

const showTooltip = (event, year, value) => {
  tooltipContent.value = { year, value }
  tooltipPosition.value = { x: event.clientX, y: event.clientY }
  tooltipVisible.value = true
}

const hideTooltip = () => {
  tooltipVisible.value = false
}

// 专利数据 - 柱状图
const patentData = ref([])

// 论文数据
const paperData = ref([])

// 图表年份（从论文数据中提取）
const chartYears = computed(() => paperData.value.map(item => String(item.year)))

// 经费数据
const fundingData = ref([])

// 领域实力分布数据
const studyFieldData = ref([])

// 加载数据
const loadData = async () => {
  if (!orgId.value) return
  
  try {
    // 并行请求所有数据
    const [patentRes, paperRes, fieldRes, fundRes] = await Promise.all([
      getPatentList(orgId.value),
      getPaperList(orgId.value),
      getStudyFieldList(orgId.value),
      getFundGrowth(orgId.value)
    ])
    
    if (patentRes.success && patentRes.data) {
      patentData.value = patentRes.data.map(item => ({
        year: String(item.year),
        value: item.countNum
      }))
    }
    
    if (paperRes.success && paperRes.data) {
      paperData.value = paperRes.data.map(item => ({
        year: item.year,
        value: item.countNum
      }))
    }
    
    if (fieldRes.success && fieldRes.data) {
      studyFieldData.value = fieldRes.data
    }
    
    if (fundRes.success && fundRes.data) {
      fundingData.value = fundRes.data.map(item => ({
        year: item.year,
        value: item.fundAmount
      }))
    }
  } catch (error) {
    console.error('加载科研实力数据失败:', error)
  }
}

// 监听 orgId 变化时重新加载数据
watch(orgId, (newVal) => {
  if (newVal) {
    loadData()
  }
}, { immediate: true })

// 计算面积图路径
const createAreaPath = (data, maxValue) => {
  if (!data || data.length === 0) return { linePath: '', areaPath: '' }
  
  const width = 700
  const height = 240
  const step = data.length > 1 ? width / (data.length - 1) : width
  const max = maxValue || Math.max(...data.map(d => d.value || d)) * 1.2 || 400
  
  const getValue = (item) => typeof item === 'object' ? item.value : item
  
  let linePath = `M 0 ${height - (getValue(data[0]) / max) * height}`
  let areaPath = `M 0 ${height} L 0 ${height - (getValue(data[0]) / max) * height}`
  
  data.forEach((item, index) => {
    const x = index * step
    const y = height - (getValue(item) / max) * height
    linePath += ` L ${x} ${y}`
    areaPath += ` L ${x} ${y}`
  })
  
  areaPath += ` L ${width} ${height} Z`
  
  return { linePath, areaPath }
}

// 论文图表路径
const paperLinePath = computed(() => createAreaPath(paperData.value).linePath)
const paperAreaPath = computed(() => createAreaPath(paperData.value).areaPath)

// 经费图表路径
const fundingLinePath = computed(() => createAreaPath(fundingData.value).linePath)
const fundingAreaPath = computed(() => createAreaPath(fundingData.value).areaPath)

// 计算节点坐标
const getDataPoints = (data, maxValue) => {
  if (!data || data.length === 0) return []
  
  const width = 700
  const height = 240
  const step = data.length > 1 ? width / (data.length - 1) : width
  const max = maxValue || Math.max(...data.map(d => d.value || d)) * 1.2 || 400
  
  const getValue = (item) => typeof item === 'object' ? item.value : item
  
  return data.map((item, index) => ({
    x: index * step,
    y: height - (getValue(item) / max) * height
  }))
}

const paperPoints = computed(() => getDataPoints(paperData.value))
const fundingPoints = computed(() => getDataPoints(fundingData.value))

// 论文/经费年份
const paperYears = computed(() => paperData.value.map(item => String(item.year)))
const fundingYears = computed(() => fundingData.value.map(item => String(item.year)))

// 计算Y轴刻度
const calculateYAxisTicks = (data, valueKey = 'value') => {
  if (!data || data.length === 0) return [0, 100, 200, 300, 400].reverse()
  const values = data.map(d => d[valueKey] || d)
  const max = Math.max(...values)
  const niceMax = Math.ceil(max / 100) * 100 || 400
  const step = niceMax / 4
  return [niceMax, niceMax - step, niceMax - step * 2, niceMax - step * 3, 0]
}

// 专利Y轴刻度和最大值
const patentMaxValue = computed(() => {
  if (!patentData.value || patentData.value.length === 0) return 400
  const max = Math.max(...patentData.value.map(d => d.value))
  return Math.ceil(max / 100) * 100 || 400
})
const patentYAxisTicks = computed(() => calculateYAxisTicks(patentData.value))

// 论文Y轴刻度
const paperYAxisTicks = computed(() => calculateYAxisTicks(paperData.value))

// 经费Y轴刻度
const fundingYAxisTicks = computed(() => calculateYAxisTicks(fundingData.value))

// 雷达图数据和计算
const radarValues = [0.7, 0.9, 0.85, 0.6, 0.75, 0.65] // 各领域 

const getHexagonPoints = (cx, cy, r) => {
  const points = []
  for (let i = 0; i < 6; i++) {
    const angle = Math.PI / 2 - i * Math.PI / 3
    const x = cx + r * Math.cos(angle)
    const y = cy - r * Math.sin(angle)
    points.push(`${x},${y}`)
  }
  return points.join(' ')
}

const radarDataPoints = computed(() => {
  const cx = 150, cy = 150, maxR = 100
  const points = radarValues.map((v, i) => {
    const angle = Math.PI / 2 - i * Math.PI / 3
    const r = v * maxR
    return `${cx + r * Math.cos(angle)},${cy - r * Math.sin(angle)}`
  })
  return points.join(' ')
})

// 饼图数据
const pieData = [
  { name: '捐赠基金', percent: 27, color: '#60A5FA' },
  { name: '政府拨款', percent: 22, color: '#FBBF24' },
  { name: '企业合作', percent: 18, color: '#34D399' },
  { name: '学费收入', percent: 15, color: '#A78BFA' },
  { name: '其他来源', percent: 12, color: '#F87171' }
]

const getPieOffset = (index) => {
  let offset = 0
  for (let i = 0; i < index; i++) {
    offset += pieData[i].percent * 4.4
  }
  return -offset
}

// 学院经费数据
const collegeData = [
  { name: '医学院', value: 109 },
  { name: '工程学院', value: 95 },
  { name: '商学院', value: 79 },
  { name: '法学院', value: 25 },
  { name: '文理学院', value: 21 },
  { name: '教育学院', value: 21 },
  { name: '教育学院', value: 21 }
]

// 横向条形图渐变：左侧完全透明，右侧深色
const getBarGradient = (index) => {
  if (index < 2) {
    // 红色：左侧完全透明，右侧深红
    return 'linear-gradient(to right, rgba(239, 68, 68, 0), #EF4444)'
  }
  // 蓝色：左侧完全透明，右侧深蓝
  return 'linear-gradient(to right, rgba(59, 130, 246, 0), #3B82F6)'
}

// 专利柱状图渐变：底部透明，顶部深蓝（与学院经费条形图同样风格，方向转为纵向）
const getPatentBarGradient = () => {
  return 'linear-gradient(to top, rgba(59, 130, 246, 0), #3B82F6)'
}
</script>

<style lang="scss" scoped>
.research-strength-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 悬浮提示框（Teleport到body，需要去掉scoped）
:global(.chart-tooltip) {
  position: fixed;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  white-space: nowrap;
  pointer-events: none;
  display: flex;
  gap: 8px;

  .tooltip-year {
    color: #ccc;
  }

  .tooltip-value {
    font-weight: 700;
  }
}

.chart-row {
  display: flex;
  gap: 16px;

  .chart-box {
    flex: 1;
    min-width: 0;
    position: relative;
  }
}

.chart-container {
  padding: 16px 24px;
  height: calc(100% - 80px);
  display: flex;
  flex-direction: column;
}

// 柱状图
.bar-chart {
  display: flex;
  flex: 1;
  gap: 12px;

  .y-axis {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    font-size: 14px;
    color: #84888E;
    text-align: right;
    padding-right: 8px;
  }

  .chart-area {
    flex: 1;
    display: flex;
    flex-direction: column;

      .bars {
        flex: 1;
        display: flex;
        align-items: flex-end;
        gap: 24px;
        padding-bottom: 8px;
        border-bottom: 1px solid #E5E7EB;

        .bar-item {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          height: 100%;
          // 柱子从下对齐，年份在顶部
          justify-content: flex-end;

          .bar-label {
            font-size: 14px;
            color: #84888E;
            margin-bottom: 8px;
          }

          .bar {
            width: 100%;
            max-width: 40px;
            // 竖向柱：底部完全透明，顶部深蓝的渐变
            background: linear-gradient(to top, rgba(59, 130, 246, 0), #3B82F6);
            border-radius: 4px 4px 0 0;
            transition: height 0.3s ease;
          }
        }
      }
  }
}

// 面积图
.area-chart {
  display: flex;
  flex: 1;
  gap: 12px;

  .y-axis {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    font-size: 14px;
    color: #84888E;
    text-align: right;
    padding-right: 8px;
  }

  .chart-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;

    .area-svg {
      flex: 1;
      width: 100%;
      overflow: visible;

      .data-point {
        cursor: pointer;
        transition: r 0.2s ease;

        &:hover {
          r: 7;
        }
      }
    }

    .x-labels {
      display: flex;
      justify-content: space-between;
      padding-top: 8px;
      border-top: 1px solid #E5E7EB;
      font-size: 14px;
      color: #84888E;
    }
  }
}

// 雷达图
.radar-container {
  justify-content: center;
  align-items: center;
}

.radar-chart {
  position: relative;
  width: 300px;
  height: 300px;

  .radar-svg {
    width: 100%;
    height: 100%;
  }

  .radar-labels {
    position: absolute;
    inset: 0;

    .label {
      position: absolute;
      font-size: 14px;
      color: #3B414B;
      white-space: nowrap;

      &.label-top { top: 0; left: 50%; transform: translateX(-50%); }
      &.label-top-right { top: 25%; right: 0; }
      &.label-bottom-right { bottom: 25%; right: 0; }
      &.label-bottom { bottom: 0; left: 50%; transform: translateX(-50%); }
      &.label-bottom-left { bottom: 25%; left: 0; }
      &.label-top-left { top: 25%; left: 0; }
    }
  }
}

// 饼图
.pie-container {
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 48px;
}

.pie-chart {
  width: 200px;
  height: 200px;

  .pie-svg {
    width: 100%;
    height: 100%;
  }
}

.pie-legend {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .legend-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .legend-dot {
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }

    .legend-label {
      font-size: 14px;
      color: #3B414B;
      min-width: 60px;
    }

    .legend-value {
      font-size: 14px;
      color: #84888E;
    }
  }
}

// 横向条形图
.horizontal-bar-container {
  padding-top: 8px;
}

.unit-label {
  text-align: right;
  font-size: 14px;
  color: #84888E;
  margin-bottom: 8px;
}

.horizontal-bars {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .horizontal-bar-item {
    display: flex;
    align-items: center;
    gap: 12px;

    .bar-name {
      width: 60px;
      font-size: 14px;
      color: #3B414B;
      text-align: right;
      flex-shrink: 0;
    }

    .bar-wrapper {
      flex: 1;
      height: 20px;
      background: transparent;
      border-radius: 2px;
      overflow: hidden;

      .bar-fill {
        height: 100%;
        border-radius: 2px;
        transition: width 0.3s ease;
      }
    }

    .bar-value {
      width: 40px;
      font-size: 16px;
      font-weight: 700;
      text-align: right;
      flex-shrink: 0;
    }
  }
}

// 图表底部摘要

</style>
