<template>
  <div class="evaluation-page">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="logo">
        <img src="../assets/logo1.png" alt="北京理工大学" @click="jumpToDashboard" style="cursor: pointer;" />
        <img src="../assets/logo2.png" alt="北京理工大学" @click="jumpToDashboard" style="cursor: pointer;" />
        <h1 class="main-title">
          <div class="title-line"></div>
          <span class="title-text">智慧科研评估系统</span>
          <div class="title-line"></div>
        </h1>
      </div>
    </header>

    <!-- 主内容区域 -->
    <div class="content-container">
     

      <!-- 右侧内容区 -->
      <div class="main-content">
        <!-- 搜索和操作栏 -->
        <div class="action-bar" style="margin-left: 170px;">
          <div class="search-box">
            <input
                type="text"
                placeholder="请输入工程研究中心名称或ID号"
                v-model="searchQuery"
                @input="handleSearch"
            />
            <button class="search-button">
              <svg class="search-icon" viewBox="0 0 24 24" width="20" height="20">
                <path fill="white" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
              </svg>
            </button>
          </div>

          <button class="add-evaluation-btn" @click="openAddEvaluationDrawer" style="margin-right: 170px;">
            新增评估
          </button>
        </div>

        <!-- 工程研究中心卡片列表 -->
        <div class="lab-card-grid custom-scrollbar">
          <img src="../assets/实验室贴图.png" alt="工程研究中心列表" class="lab-list-image" />
        </div>
      </div>
    </div>
  </div>

  <LabDrawerDetail
      v-model:visible="drawerVisible"
      :is-edit="isEditMode"
      :dimensions="dimensions"
      :lab-data="selectedLab"
      @save="handleSaveEvaluation"
  />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts/core';
import { RadarChart } from 'echarts/charts';
import LabDrawerDetail from './LabDrawerDetail.vue';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { getApiBaseUrl } from '../../config';

// 注册必要的 echarts 组件
echarts.use([
  RadarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer
]);

const drawerVisible = ref(false);
const isEditMode = ref(false);
const selectedLab = ref(null);

// 打开添加评估抽屉
const openAddEvaluationDrawer = () => {
  isEditMode.value = false;
  selectedLab.value = null;
  drawerVisible.value = true;
};

// 处理保存评估
const handleSaveEvaluation = (data) => {
  if (isEditMode.value) {
    // 更新现有工程研究中心数据
    const index = labs.value.findIndex(l => l.id === data.id);
    if (index !== -1) {
      labs.value[index] = { ...data };
    }
  } else {
    // 添加新工程研究中心
    labs.value.push({ ...data });
  }

  // 更新过滤的工程研究中心
  handleSearch();
};
// 向父组件发送页面切换事件
const emit = defineEmits(['navigate']);

// 跳转到仪表盘页面
const jumpToDashboard = () => {
  console.log('正在尝试跳转到仪表盘...');
  // 检查是否正确定义了emit
  if (typeof emit !== 'function') {
    console.error('emit 不是一个函数，无法触发事件');
    return;
  }
  
  // 确保事件名称正确
  emit('navigate', 'dashboard');
  
  // 添加调试信息
  console.log('已触发 navigate 事件，参数为:', 'dashboard');
  
  // 注意：确保父组件中有监听此事件的处理程序
  // 例如：<LabDetail @navigate="handleNavigate" />
};

// 评估维度数据
const dimensions = ref([
  { name: '工程技术研发能力与水平 (30%)', weight: 30, enabled: true },
  { name: '创新水平', weight: 10, enabled: true },
  { name: '人才与队伍', weight: 10, enabled: true },
  { name: '装备与场地', weight: 10, enabled: true },
  { name: '成果转化与行业贡献 (30%)', weight: 30, enabled: true },
  { name: '学科发展与人才培养 (20%)', weight: 20, enabled: true },
  { name: '开放与运行管理 (20%)', weight: 20, enabled: true }
]);

// 搜索功能
const searchQuery = ref('');

// 获取token函数
const getToken = () => {
  return localStorage.getItem('token');
};

// 工程研究中心数据现在从API获取
const labs = ref([]);
const filteredLabs = ref([]);
const loading = ref(true);

// 从API获取工程研究中心数据
const fetchLabs = async () => {
  try {
    const response = await fetch(`${getApiBaseUrl()}/labs`, {
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      labs.value = data;
      handleSearch(); // 初始化filteredLabs
    } else {
      console.error('获取工程研究中心数据失败:', response.statusText);
    }
  } catch (error) {
    console.error('获取工程研究中心数据出错:', error);
  } finally {
    loading.value = false;
  }
};

// 生命周期钩子 - 组件挂载后获取数据
onMounted(() => {
  fetchLabs();
});

// 搜索功能实现
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    filteredLabs.value = [...labs.value];
    return;
  }
  
  const query = searchQuery.value.toLowerCase().trim();
  filteredLabs.value = labs.value.filter(lab => 
    lab.name.toLowerCase().includes(query) || 
    lab.id.toLowerCase().includes(query)
  );
};

// 生成随机的工程研究中心图片占位符
function generateLabImagePlaceholder() {
  // 这里生成不同类型的工程研究中心图片占位符
  const imageTypes = [
    // 建筑类型图片
    `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 300 200'%3E%3Crect width='300' height='200' fill='%234986ff' opacity='0.2'/%3E%3Cpath d='M50,180 L50,80 L150,30 L250,80 L250,180 Z' fill='%234986ff' opacity='0.4'/%3E%3Crect x='90' y='120' width='40' height='60' fill='%234986ff' opacity='0.6'/%3E%3Crect x='170' y='120' width='40' height='60' fill='%234986ff' opacity='0.6'/%3E%3C/svg%3E`,
    // 工程研究中心内部类型图片
    `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 300 200'%3E%3Crect width='300' height='200' fill='%234986ff' opacity='0.2'/%3E%3Crect x='20' y='40' width='260' height='120' fill='%234986ff' opacity='0.3'/%3E%3Ccircle cx='70' cy='70' r='20' fill='%234986ff' opacity='0.5'/%3E%3Crect x='120' y='50' width='140' height='40' fill='%234986ff' opacity='0.4'/%3E%3Crect x='120' y='110' width='140' height='30' fill='%234986ff' opacity='0.4'/%3E%3C/svg%3E`,
    // 商业建筑类型图片
    `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 300 200'%3E%3Crect width='300' height='200' fill='%234986ff' opacity='0.2'/%3E%3Cpath d='M50,30 L250,30 L250,170 L50,170 Z' fill='%234986ff' opacity='0.3'/%3E%3Cpath d='M80,50 L220,50 L220,150 L80,150 Z' fill='%23fff' opacity='0.2'/%3E%3Cpath d='M90,60 L110,60 L110,80 L90,80 Z' fill='%234986ff' opacity='0.5'/%3E%3Cpath d='M130,60 L150,60 L150,80 L130,80 Z' fill='%234986ff' opacity='0.5'/%3E%3Cpath d='M170,60 L190,60 L190,80 L170,80 Z' fill='%234986ff' opacity='0.5'/%3E%3Cpath d='M90,100 L110,100 L110,120 L90,120 Z' fill='%234986ff' opacity='0.5'/%3E%3Cpath d='M130,100 L150,100 L150,120 L130,120 Z' fill='%234986ff' opacity='0.5'/%3E%3Cpath d='M170,100 L190,100 L190,120 L170,120 Z' fill='%234986ff' opacity='0.5'/%3E%3C/svg%3E`,
    // 高科技玻璃建筑风格
    `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 300 200'%3E%3Crect width='300' height='200' fill='%234986ff' opacity='0.1'/%3E%3Cpath d='M60,20 L240,20 L240,180 L60,180 Z' fill='%234986ff' opacity='0.2'/%3E%3Cpath d='M80,40 L140,40 L140,160 L80,160 Z' fill='%234986ff' opacity='0.3'/%3E%3Cpath d='M160,40 L220,40 L220,160 L160,160 Z' fill='%234986ff' opacity='0.3'/%3E%3Cline x1='80' y1='60' x2='140' y2='60' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='80' y1='80' x2='140' y2='80' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='80' y1='100' x2='140' y2='100' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='80' y1='120' x2='140' y2='120' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='80' y1='140' x2='140' y2='140' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='160' y1='60' x2='220' y2='60' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='160' y1='80' x2='220' y2='80' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='160' y1='100' x2='220' y2='100' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='160' y1='120' x2='220' y2='120' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3Cline x1='160' y1='140' x2='220' y2='140' stroke='%23fff' stroke-width='1' opacity='0.5' /%3E%3C/svg%3E`
  ];

  // 随机选择一种图片类型
  return imageTypes[Math.floor(Math.random() * imageTypes.length)];
}

// 初始化雷达图
const initRadarCharts = () => {
  filteredLabs.value.forEach((lab, index) => {
    const chartDom = document.getElementById(`lab-chart-${index}`);
    if (!chartDom) return;

    // 先清空已有的图表实例
    echarts.dispose(chartDom);
    const chart = echarts.init(chartDom);

    // 生成雷达图所需的指标
    const indicators = [
      { name: '创新水平', max: 100 },
      { name: '研究能力', max: 100 },
      { name: '成果转化', max: 100 },
      { name: '学科建设', max: 100 },
      { name: '行业贡献', max: 100 },
      { name: '发展潜力', max: 100 }
    ];

    chart.setOption({
      radar: {
        indicator: indicators,
        splitArea: { show: false },
        axisLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.2)' } },
        splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.2)' } },
        name: { textStyle: { color: '#fff', fontSize: 10 } },
        radius: '70%'
      },
      series: [
        {
          type: 'radar',
          data: [
            {
              value: lab.evaluationData,
              name: '评估结果',
              areaStyle: { opacity: 0 },
              lineStyle: { color: 'rgb(238, 23, 143)', width: 2 }, // 玫红色线段
              itemStyle: { color: 'rgb(238, 23, 143)' } // 玫红色数据点
            }
          ]
        }
      ]
    });

    // 添加窗口大小变化时的调整
    window.addEventListener('resize', () => {
      chart.resize();
    });
  });
};

// 监听过滤后的工程研究中心数据变化，重新初始化图表
watch(filteredLabs, () => {
  // 使用 setTimeout 确保 DOM 已更新
  setTimeout(() => {
    initRadarCharts();
  }, 100);
}, { deep: true });

onMounted(() => {
  // 初始化时显示所有工程研究中心
  filteredLabs.value = labs.value;
  // 需要延迟一下，确保 DOM 已经渲染
  setTimeout(() => {
    initRadarCharts();
  }, 100);
});
</script>

<style>
@import './common.css';
</style>

<style scoped>
.evaluation-page {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  /* background-color: #0c1633; */
  color: white;
  overflow: hidden;
}

.dashboard-header {
  height: 60px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
  position: relative;
  width: 100%;
}

.logo img {
  height: 40px;
  margin-right: 10px;
}

.main-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 28px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.title-line {
  border: 2px solid rgba(73,134,255,1);
  width: 150px;
}

.title-text {
  margin: 0 30px;
}

.content-container {
  display: flex;
  flex: 1;
  padding: 20px;
  overflow: hidden;
  gap: 20px;
}

.dimension-image, .lab-list-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 特定于LabDetail的样式 */
.sidebar-header {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: left;
  background-color: transparent;
}

.sidebar-title {
  font-size: 22px;
  font-weight: bold;
  color: white;
  margin: 0;
  text-align: left;
}

.home-link {
  text-decoration: underline;
  cursor: pointer;
  color: #4986ff;
}

.dimension-sidebar {
  width: 280px;
  display: flex;
  flex-direction: column;
}

.dimension-content {
  flex: 1;
  /* background-color: #262F50; */
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 右侧内容区 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0 10px;
  overflow: hidden;
}

/* 搜索和操作栏 */
.action-bar {
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  display: flex;
  align-items: center;
  width: 300px;
  background-color: rgba(255,255,255,0.1);
  border-radius: 20px;
  overflow: hidden;
}

.search-box input {
  flex: 1;
  background: transparent;
  border: none;
  padding: 10px 15px;
  color: white;
  outline: none;
}

.search-box input::placeholder {
  color: rgba(255,255,255,0.5);
}

.search-button {
  background: transparent;
  border: none;
  color: white;
  padding: 0 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.search-icon {
  fill: white;
}

.add-evaluation-btn {
  /* background-color: rgba(14,62,167,1); */
  color: rgba(255,255,255,1);
  border: 1px solid rgba(73,134,255,1);
  border-radius: 10px;
  padding: 8px 15px;
  font-size: 14px;
  text-align: center;
  font-family: PingFangSC-regular;
  cursor: pointer;
}

/* 工程研究中心卡片网格 */
.lab-card-grid {
  display: flex;
  flex: 1;
  overflow: hidden;
  /* background-color: #262F50; */
  border-radius: 10px;
}

@media (max-width: 1200px) {
  .dimension-sidebar {
    width: 100%;
    height: auto;
    max-height: 300px;
    margin-bottom: 10px;
  }

  .sidebar-header {
    height: auto;
    padding: 10px 0;
  }
}
</style>