<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">
          <div class="search-box" style="margin-left: 170px;">
            
            <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="teacher-card-grid custom-scrollbar">
          <img src="../assets/人才贴图.png" alt="人才列表" class="talent-list-image" />
        </div>
      </div>
    </div>
  </div>

  <TalentDrawerDetail
      v-model:visible="drawerVisible"
      :is-edit="isEditMode"
      :dimensions="dimensions"
      :teacher-data="selectedTeacher"
      @save="handleSaveEvaluation"
  />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts/core';
import { RadarChart } from 'echarts/charts';
import TalentDrawerDetail from './TalentDrawerDetail.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 selectedTeacher = ref(null);

// Function to open the drawer for adding a new evaluation
const openAddEvaluationDrawer = () => {
  isEditMode.value = false;
  selectedTeacher.value = null;
  drawerVisible.value = true;
};

// Function to handle save from drawer
const handleSaveEvaluation = (data) => {
  if (isEditMode.value) {
    // Update existing teacher data
    const index = teachers.value.findIndex(t => t.id === data.id);
    if (index !== -1) {
      teachers.value[index] = { ...data };
    }
  } else {
    // Add new teacher
    teachers.value.push({ ...data });
  }

  // Update filtered teachers
  handleSearch();
};

// 向父组件发送页面切换事件
const emit = defineEmits(['navigate']);

// 跳转到仪表盘页面
const jumpToDashboard = () => {
  emit('navigate', 'dashboard');
  // 或者使用路由导航 (如果你使用的是 vue-router)
  // router.push('/dashboard');
};

// 跳转到外部科研成果评估链接
const redirectToResearchEvaluation = () => {
  window.open('http://82.156.236.221:10004/login', '_blank');
};

// 评估维度数据
const dimensions = ref([
  { name: '教育和工作经历', weight: 10, enabled: true },
  { name: '研究方向前沿性', weight: 8, enabled: true },
  { name: '主持科研项目情况', weight: 12, enabled: true },
  { name: '科研成果质量', weight: 16, enabled: true },
  { name: '教学能力与效果', weight: 14, enabled: true },
  { name: '学术服务与影响力', weight: 40, enabled: true }
]);

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

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

// 教师数据现在从API获取
const teachers = ref([]);
const filteredTeachers = ref([]);
const loading = ref(true);

// 从API获取人才数据
const fetchTalents = async () => {
  try {
    const response = await fetch(`${getApiBaseUrl()}/talents`, {
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      teachers.value = data;
      handleSearch(); // 初始化filteredTeachers
    } else {
      console.error('获取人才数据失败:', response.statusText);
    }
  } catch (error) {
    console.error('获取人才数据出错:', error);
  } finally {
    loading.value = false;
  }
};

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

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

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

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

    // 生成雷达图所需的指标
    const indicators = dimensions.value.map(dim => ({
      name: dim.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: teacher.evaluationData,
              name: '评估结果',
              areaStyle: { opacity: 0 }, // 移除半透明的底色
              lineStyle: { color: 'rgb(63, 196, 15)', width: 2 }, // 设置线段颜色为RGB(63, 196, 15)
              itemStyle: { color: 'rgb(63, 196, 15)' } // 设置点的颜色
            }
          ]
        }
      ]
    });

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

// 监听过滤后的教师数据变化，重新初始化图表
watch(filteredTeachers, () => {
  // 使用 nextTick 确保 DOM 已更新
  setTimeout(() => {
    initRadarCharts();
  }, 100);
}, { deep: true });

onMounted(() => {
  // 初始化时显示所有教师
  filteredTeachers.value = teachers.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, .talent-list-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 特定于TalentDetail的样式 */
.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;
}

/* 教师卡片网格 */
.teacher-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>