<template>
  <div class="desc-tab">
    <!-- 上半部分：基本信息和经费来源 -->
    <div class="top-section">
      <!-- 左侧：基本信息卡片 -->
      <div class="basic-info-card">
        <CardTitle title="基本信息" />
        <div class="tank-image">
          <img src="https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?ixlib=rb-4.0.3&q=85&fm=jpg&crop=entropy&cs=srgb&w=400" alt="智库建筑" />
        </div>
        <div class="info-content">
          <div class="info-row">
            <span class="label">国家：</span>
            <span class="value">{{ thinkTankInfo.country }}</span>
          </div>
          <div class="info-row">
            <span class="label">成立时间：</span>
            <span class="value">{{ thinkTankInfo.foundingDate }}</span>
          </div>
          <div class="info-row">
            <span class="label">总部位置：</span>
            <span class="value">{{ thinkTankInfo.position }}</span>
          </div>
          <div class="info-row">
            <span class="label">机构性质：</span>
            <span class="value">{{ thinkTankInfo.nature }}</span>
          </div>
          <div class="info-row">
            <span class="label">员工数量：</span>
            <span class="value">{{ thinkTankInfo.memnum }}</span>
          </div>
          <div class="info-row">
            <span class="label">年度预算：</span>
            <span class="value">{{ thinkTankInfo.budget }}</span>
          </div>
        </div>
        
        <div class="additional-info">
          <CardTitle title="全球分支机构" />
          <div class="branch-list">
            <div class="branch-item" v-for="(item, key) in branchInfo" :key="key">
              <span class="location">{{ key }}：</span>
              <span class="desc">{{ item.join('、') }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：经费来源 -->
      <div class="funding-section">
        <FundingSource  style="margin-bottom: 20px"/>
        <!-- 中间部分：研究领域演变 -->
        <div class="timeline-section">
          <div class="section-header">
            <CardTitle title="研究领域演变" />
            <el-icon class="expand-icon"><MoreFilled /></el-icon>
          </div>
          
          <div class="timeline-container">
            <div class="timeline-periods">
              <div class="period-item active" v-for="value in researchAreas" :key="value.id">
                <div class="period-title">{{ value.time }}</div>
                <div class="period-desc">{{ value.describe }}</div>
              </div>
            </div>
            
            <div class="timeline-line">
              <div class="timeline-progress"></div>
              <div class="timeline-dots">
                <div class="dot active" v-for="value in researchAreas" :key="value.id"></div>
              </div>
            </div>
          </div>   
        </div>

        <!-- 底部：核心研究人员 -->
        <div class="core-researchers-section">
          <div class="section-header">
            <CardTitle title="核心研究人员" />
            <el-icon class="more-icon"><MoreFilled /></el-icon>
          </div>
          
          <div class="researchers-content">
            <!-- 左侧：树状图 -->
            <div class="researchers-treemap">
              <div ref="researcherChart" class="researcher-chart"></div>
            </div>
            
            <!-- 右侧：人员列表 -->
            <div class="researchers-list">
              <div 
                v-for="researcher in coreResearchers" 
                :key="researcher.id"
                class="researcher-item"
              >
                <div class="researcher-avatar">
                  <el-image :src="$withFallbackImage(researcher.avatar, researcher.name)" :alt="researcher.name" />
                </div>
                <div class="researcher-info">
                  <h4 class="researcher-name">{{ researcher.name }}</h4>
                  <div class="researcher-previous" v-if="researcher.previousRoles && researcher.previousRoles.length">
                    <span class="previous-label">之前：</span>
                    <span class="previous-roles">{{ researcher.previousRoles.join('、') }}</span>
                  </div>
                  <p class="researcher-position">{{ researcher.currentPosition }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { MoreFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import CardTitle from '@/components/CardTitle.vue'
import FundingSource from './FundingSource.vue'

import {
  getThinkTankBasicInfo,
  getThinkTankBranchInfo,
  getThinkTankFundsSource,
  getThinkTankFundsTotal,
  getThinkTankResearchArea,
  getThinkTankPersonList
} from '@/api'
import { useRoute } from 'vue-router'
import {
  mockRandBasicInfo,
  mockRandBranchInfo,
  mockRandFundsSource,
  mockRandFundsByType,
  mockRandFundsByEntity,
  mockRandFundTotal,
  mockRandResearchAreas,
  mockRandCoreResearchers,
  mockRandResearcherCategories
} from '../mockData'

// 组件状态
const activeTimelinePeriod = ref(0)
const fundingChart = ref(null)
const researcherChart = ref(null)
const route = useRoute()

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

// 初始化经费饼图
const initFundingChart = () => {
  if (!fundingChart.value) return
  
  const chart = echarts.init(fundingChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}万 ({d}%)'
    },
    series: [
      {
        name: '经费来源',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 2,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: fundingData.value.map(item => ({
          value: item.value,
          name: item.name,
        }))
      }
    ]
  }
  
  chart.setOption(option)
  
  const handleResize = () => {
    chart.resize()
  }
  window.addEventListener('resize', handleResize)
  
  return () => {
    window.removeEventListener('resize', handleResize)
    chart.dispose()
  }
}

// 初始化研究人员树状图
const initResearcherChart = () => {
  if (!researcherChart.value) return
  
  const chart = echarts.init(researcherChart.value)
  
  // 将分类数据转换为树状图格式
  const treemapData = []
  Object.keys(mockRandResearcherCategories).forEach(category => {
    const children = Object.keys(mockRandResearcherCategories[category]).map(item => ({
      name: item,
      value: mockRandResearcherCategories[category][item]
    }))
    treemapData.push({
      name: category,
      value: children.reduce((sum, item) => sum + item.value, 0),
      children: children
    })
  })
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人'
    },
    series: [
      {
        type: 'treemap',
        data: treemapData,
        roam: false,
        nodeClick: false,
        breadcrumb: {
          show: false
        },
        label: {
          show: true,
          formatter: '{b}\n{c}人',
          fontSize: 12
        },
        upperLabel: {
          show: true,
          height: 30
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
          gapWidth: 2
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  const handleResize = () => {
    chart.resize()
  }
  window.addEventListener('resize', handleResize)
  
  return () => {
    window.removeEventListener('resize', handleResize)
    chart.dispose()
  }
}

// 研究领域数据
const researchAreas = ref([])

const thinkTankInfo = ref({})
const getThinkTankInfo = async () => {
  thinkTankInfo.value = mockRandBasicInfo
}

const branchInfo = ref({})
const getBranchInfo = async () => {
  branchInfo.value = mockRandBranchInfo
}

const getFundsSource = async () => {
  fundingData.value = mockRandFundsSource.map(item => ({
    value: item.amount,
    name: item.institution,
  }))
  fundsByType.value = mockRandFundsByType
  fundsByEntity.value = mockRandFundsByEntity
  nextTick(() => {
    initFundingChart()
  })
}

const fundTotal = ref({
  totalJe: 0,
  zfJe: 0,
  otherJe: 0
})
const getFundTotal = async () => {
  fundTotal.value = mockRandFundTotal
}

const getResearchArea = async () => {
  researchAreas.value = mockRandResearchAreas
}

const getPersonList = async () => {
  coreResearchers.value = mockRandCoreResearchers
  nextTick(() => {
    initResearcherChart()
  })
}

// 初始化
onMounted(async () => {
  getThinkTankInfo()
  getBranchInfo()
  getFundsSource()
  getFundTotal()
  getResearchArea()
  getPersonList()
})

// 核心研究人员数据
const coreResearchers = ref([])

// 格式化货币显示
const formatCurrency = (amount) => {
  if (!amount) return '0美元'
  const formatted = (amount / 100000000).toFixed(2)
  return `${formatted}亿美元`
}

// 格式化金额（万美元）
const formatAmount = (amount) => {
  return `${amount}万`
}
</script>

<style scoped lang="scss">
.desc-tab {
  min-height: 100vh;
}

/* 上半部分布局 */
.top-section {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  margin-bottom: 20px;
}

/* 基本信息卡片 */
.basic-info-card {
  min-width: 360px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  height: auto;
}

.tank-image {
  margin-bottom: 20px;
  margin-top: 10px;
}

.tank-image img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
}

.info-content {
  margin-bottom: 24px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.info-row .label {
  font-weight: 500;
  color: #374151;
  min-width: 80px;
  font-size: 14px;
}

.info-row .value {
  color: #111827;
  font-size: 14px;
}

.additional-info {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.branch-list {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  gap: 8px;
}

.branch-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.branch-item .location {
  font-weight: 500;
  color: #374151;
}

.branch-item .desc {
  color: #6b7280;
}

/* 经费来源区域 */
.funding-section {
  flex: 1;
}

.funding-overview {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.expand-icon {
  color: #9ca3af;
  cursor: pointer;
  font-size: 18px;
}

/* 经费汇总 */
.funding-summary {
  display: flex;
  gap: 30px;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.summary-item {
  flex: 1;
}

.summary-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.summary-amount {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
}

/* 经费详情 */
.funding-details {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.funding-table-left,
.funding-table-right {
  flex: 0 0 200px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.table-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.table-item:last-child {
  border-bottom: none;
}

.table-name {
  font-size: 13px;
  color: #374151;
  line-height: 1.4;
}

.table-amount {
  font-size: 14px;
  font-weight: 600;
  color: #111827;
}

.table-percent {
  font-size: 12px;
  color: #6b7280;
}

.funding-chart-wrapper {
  flex: 1;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.funding-chart {
  width: 100%;
  height: 300px;
  min-height: 300px;
}

/* 研究领域演变 */
.timeline-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
}

.timeline-container {
  position: relative;
}

.timeline-periods {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
}

.period-item {
  flex: 1;
  padding: 0 16px;
  text-align: center;
}

.period-item.active .period-title {
  color: #3b82f6;
  font-weight: 600;
}

.period-title {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.period-desc {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

.timeline-line {
  position: relative;
  height: 4px;
  background-color: #e5e7eb;
  border-radius: 2px;
  margin: 0 60px;
}

.timeline-progress {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: linear-gradient(90deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 2px;
}

.timeline-dots {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
}

.dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #e5e7eb;
  border: 2px solid white;
  box-shadow: 0 0 0 2px #e5e7eb;
}

.dot.active {
  background-color: #3b82f6;
  box-shadow: 0 0 0 2px #3b82f6;
}

/* 核心研究人员 */
.core-researchers-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 30px;
}

.more-icon {
  color: #6b7280;
  cursor: pointer;
  font-size: 18px;
}

.more-icon:hover {
  color: #374151;
}

.researchers-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.researchers-treemap {
  flex: 1;
  min-height: 400px;
}

.researcher-chart {
  width: 100%;
  height: 400px;
  min-height: 400px;
}

.researchers-list {
  flex: 0 0 400px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.researcher-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.researcher-item:last-child {
  border-bottom: none;
}

.researcher-avatar {
  flex-shrink: 0;
}

.researcher-avatar .el-image {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f3f4f6;
}

.researcher-info {
  flex: 1;
  min-width: 0;
}

.researcher-name {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
  margin: 0 0 6px 0;
  line-height: 1.3;
}

.researcher-previous {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 4px;
}

.previous-label {
  color: #9ca3af;
}

.previous-roles {
  color: #6b7280;
}

.researcher-position {
  font-size: 13px;
  color: #374151;
  margin: 0;
  line-height: 1.4;
  word-wrap: break-word;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .top-section {
    flex-direction: column;
  }
  
  .funding-details {
    flex-direction: column;
  }
  
  .funding-table-left,
  .funding-table-right {
    flex: none;
    width: 100%;
  }
  
  .funding-chart-wrapper {
    min-height: 250px;
  }
  
  .funding-chart {
    height: 250px;
    min-height: 250px;
  }
  
  .timeline-periods {
    flex-direction: column;
    gap: 20px;
  }
  
  .timeline-line {
    display: none;
  }
  
  .researchers-content {
    flex-direction: column;
  }
  
  .researchers-list {
    flex: none;
    width: 100%;
  }
}

@media (max-width: 768px) {
  .desc-tab {
    padding: 16px;
  }
  
  .basic-info-card,
  .funding-overview,
  .timeline-section,
  .core-researchers-section {
    padding: 16px;
  }
  
  .researcher-item {
    gap: 10px;
    padding: 8px 0;
  }
  
  .researcher-avatar .el-image {
    width: 40px;
    height: 40px;
  }
  
  .researcher-name {
    font-size: 14px;
  }
  
  .researcher-position {
    font-size: 12px;
  }
}
</style>