<template>
  <div class="innovation-analysis">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="nav-tabs">
        <button
          class="nav-tab"
          :class="{ active: currentView === 'ranking' }"
          @click="switchView('ranking')"
        >
          创新主体排名
        </button>
        <button
          class="nav-tab"
          :class="{ active: currentView === 'layout' }"
          @click="switchView('layout')"
        >
          研究布局
        </button>
      </div>
      
      <div class="filters">
        <CustomSelect
          v-if="currentView === 'layout'"
          v-model="selectedCategory"
          :options="categoryOptions"
        />
        <CustomSelect
          v-model="releaseTime"
          :options="releaseTimeList"
        />
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 排名视图 -->
      <template v-if="currentView === 'ranking'">
        <div class="section-card">
          <div class="section-header">
            <div class="section-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <rect x="3" y="3" width="4" height="18" rx="1"/>
                <rect x="10" y="8" width="4" height="13" rx="1"/>
                <rect x="17" y="13" width="4" height="8" rx="1"/>
              </svg>
            </div>
            <h3 class="section-title">创新主体综合排名</h3>
          </div>
          
          <RankingTable :data="innoItemList" :loading="loading" />
        </div>
        
        <div class="analysis-section">
          <AnalysisText :text="rankingAnalysis" show-arrow />
        </div>
      </template>

      <!-- 布局视图 -->
      <template v-else>
        <div class="section-card">
          <div class="section-header">
            <div class="section-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <rect x="3" y="3" width="4" height="18" rx="1"/>
                <rect x="10" y="8" width="4" height="13" rx="1"/>
                <rect x="17" y="13" width="4" height="8" rx="1"/>
              </svg>
            </div>
            <h3 class="section-title">研究领域布局情况</h3>
          </div>
          
          <div class="charts-grid">
            <div class="chart-item">
              <DonutChart :data="barOptionData" :loading="loading" />
            </div>
            <div class="chart-item">
              <RadarChart
                :data="raderOptionData"
                :loading="loading"
              />
            </div>
          </div>
        </div>
        
        <div class="analysis-section dual">
          <AnalysisText :text="fieldAnalysis" show-arrow />
          <AnalysisText :text="radarAnalysis" show-arrow />
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { getOverallRanking, getResearchField, getResearchFieldSubjectType } from '@/api/innovationSubject/overview.js'
import RankingTable from './RankingTable.vue'
import DonutChart from './DonutChart.vue'
import RadarChart from './RadarChart.vue'
import AnalysisText from './AnalysisText.vue'
import CustomSelect from './CustomSelect.vue'

// 接收父组件传入的 activeCate1（主体类型ID）
const props = defineProps<{
  activeCate1: string | number
}>()

// 当前视图：'ranking' 创新主体排名, 'layout' 研究布局
const currentView = ref('ranking')

// 年份选择
const releaseTime = ref('2022')
const releaseTimeList = ref([
  { label: '2022', value: '2022' },
  { label: '2023', value: '2023' },
  { label: '2024', value: '2024' },
  { label: '2025', value: '2025' }
])

// 类别选择（研究布局视图）
const selectedCategory = ref('rd_output')
const categoryOptions = ref([
  { label: '研发产出投入', value: 'rd_output' },
  { label: '人才投入', value: 'talent' },
  { label: '专利产出', value: 'patent' }
])

// 数据状态
const loading = ref(false)

// 排名视图数据
const innoItemList = ref({
  headerlist: [],
  datalist: []
})
const rankingAnalysis = ref('研究型大学在综合排名中占据主导地位，特别是在论文和影响力指标上表现突出；科技企业在专利指数上领先，但在论文产出方面相对较弱；国家实验室和国防承包商在特定领域(如国家安全、能源)有显著优势，但在综合排名中相对靠后。')

// 布局视图数据 - 饼图
const barOptionData = ref({
  names: [],
  values: [],
  total: 0
})

// 布局视图数据 - 雷达图
const raderOptionData = ref([])

// 分析文本
const fieldAnalysis = ref('人工智能与信息技术占据最大份额，反映了数字经济的核心地位;生物医学与健康是第二大研发领域，特别是在疫情后投入显著增加;能源与环境技术和先进制造与材料作为基础支撑领域保持稳定投入;国家安全与国防和航空航天作为战略领域保持专项投入。')
const radarAnalysis = ref('研究型大学在基础科学领域(生物医学、材料科学)占据主导地位；科技企业高度集中于人工智能和信息技术领域；国家实验室在能源技术和国家安全相关领域有显著优势；国防承包商的研究高度集中于航空航天和国家安全领域。')

// 切换视图
function switchView(view: string) { 
  if (currentView.value !== view) {
    currentView.value = view
    if (view === 'ranking') { 
      handleGetOverallRanking()
    } else { 
      handleGetResearchField()
      handleGetResearchFieldSubjectType()
    }
  }
}

// 获取综合排名数据
const handleGetOverallRanking = async () => {
  loading.value = true
  try {
    const params = {
      subjectTypeId: props.activeCate1,
      year: releaseTime.value
    }
    const res = await getOverallRanking(params) 
    if (res.code === 200 && res.data) {
      innoItemList.value = res.data
    }
  } catch (error) {
    console.error('获取综合排名error', error)
  } finally {
    loading.value = false
  }
}

// 获取研究领域布局情况（饼图数据）
const handleGetResearchField = async () => {
  try {
    const params = {
      year: releaseTime.value
    }
    const res = await getResearchField(params) 
    if (res.code === 200 && res.data) {
      const names = res.data.map(item => item.areaName)
      const values = res.data.map(item => item.amount)
      const total = res.data.reduce((sum, item) => sum + item.amount, 0)
      barOptionData.value = {
        names,
        values,
        total
      }
    }
  } catch (error) {
    console.error('获取研究领域布局情况error', error)
  }
}

// 获取研究领域主体类型（雷达图数据）
const handleGetResearchFieldSubjectType = async () => {
  try {
    const params = {
      year: releaseTime.value
    }
    const res = await getResearchFieldSubjectType(params) 
    if (res.code === 200 && res.data) {
      raderOptionData.value = res.data
    }
  } catch (error) {
    console.error('获取研究领域主体类型error', error)
  }
}

// 监听年份变化
watch(releaseTime, () => {
  if (currentView.value === 'ranking') {
    handleGetOverallRanking()
  } else {
    handleGetResearchField()
    handleGetResearchFieldSubjectType()
  }
})

// 监听 activeCate1 变化（父组件切换主体类型时重新加载排名数据）
watch(() => props.activeCate1, () => {
  if (currentView.value === 'ranking') {
    handleGetOverallRanking()
  }
})

// 初始化加载
onMounted(() => {
  handleGetOverallRanking()
})
</script>

<style scoped>
.innovation-analysis {
  width: 1600px;
  margin: 0 auto;
  font-family: 'Source Han Sans CN', 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 42px;
  margin-top: 30px;
  margin-bottom: 24px;
}

.nav-tabs {
  display: flex;
  align-items: center;
  gap: 4px;
}

.nav-tab {
  height: 42px;
  padding: 4px 24px;
  font-size: 18px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-weight: 400;
  color: rgba(59, 65, 75, 1);
  background: transparent;
  border: none;
  border-radius: 21px;
  cursor: pointer;
  transition: all 0.2s;
  line-height: 24px;
}

.nav-tab:hover {
  color: rgba(5, 95, 194, 1);
}

.nav-tab.active {
  color: #fff;
  background-color: rgba(5, 95, 194, 1);
  font-weight: 700;
}

.filters {
  display: flex;
  align-items: center;
  gap: 16px;
}

.content {
  min-height: 528px;
  background-color: #fff;
  border: 1px solid rgba(230, 231, 232, 1);
  border-radius: 10px;
  box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
  overflow: hidden;
}

.section-card {
  padding: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 4px;
  height: 48px;
  padding: 0 24px;
  border-bottom: 1px solid rgba(234, 236, 238, 1);
}

.section-icon {
  width: 24px;
  height: 24px;
  color: rgba(5, 95, 194, 1);
}

.section-icon svg {
  width: 100%;
  height: 100%;
}

.section-title {
  margin: 0;
  font-size: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-weight: 700;
  color: rgba(5, 95, 194, 1);
  line-height: 26px;
}

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  padding: 24px;
  position: relative;
}

.charts-grid::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 24px;
  bottom: 24px;
  width: 1px;
  background-color: rgba(234, 236, 238, 1);
  transform: translateX(-50%);
}

.chart-item {
  min-height: 300px;
}

.analysis-section {
  padding: 0 24px 24px;
}

.analysis-section.dual {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 26px;
  padding: 0 24px 24px;
}
</style>
