<template>
  <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="900px"
      :before-close="handleClose"
      custom-class="talent-drawer"
  >
    <div class="drawer-content">
      <!-- 标签导航 -->
      <div class="tab-navigation">
        <div
            v-for="(tab, index) in tabs"
            :key="index"
            :class="['tab-item', { active: activeTab === tab.value }]"
            @click="activeTab = tab.value"
        >
          {{ tab.label }}
        </div>
      </div>

      <!-- URL输入标签页 -->
      <div v-if="activeTab === 'url'" class="tab-content">
        <div class="url-input-container">
          <el-input
              v-model="urlInput"
              placeholder="请输入URL"
              class="url-input"
          />
          <el-button
              type="primary"
              @click="fetchDataFromUrl"
              class="send-button"
          >
            发送
          </el-button>
        </div>
        
        <div class="detail-content-image">
          <img src="../assets/人才详情贴图.png" alt="人才详情" class="talent-detail-image" />
        </div>
      </div>

      <!-- 上传文档标签页 -->
      <div v-else-if="activeTab === 'upload'" class="tab-content">
        <el-upload
            class="upload-container"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
        >
          <el-button type="primary">选择文件</el-button>
          <div class="el-upload__tip">请上传文档，支持PDF、DOC、DOCX格式</div>
        </el-upload>
        
        <div class="detail-content-image">
          <img src="../assets/人才详情贴图.png" alt="人才详情" class="talent-detail-image" />
        </div>
      </div>

      <!-- 手动输入标签页 -->
      <div v-else class="tab-content">
        <div class="manual-input-tip">请手动填写以下信息</div>
        
        <div class="detail-content-image">
          <img src="../assets/人才详情贴图.png" alt="人才详情" class="talent-detail-image" />
        </div>
      </div>

      <!-- 个人信息表单 - 仅在数据加载后显示 -->
      <div v-if="dataLoaded" class="personal-info-form">
        <div class="form-header">
          <div class="photo-section">
            <div class="teacher-photo">
              <img :src="formData.photo || defaultPhoto" alt="教师照片" />
            </div>
            <div class="teacher-id">ID: {{ formData.id || 'BLG00000' }}</div>
          </div>

          <div class="basic-info">
            <div class="form-row">
              <div class="form-item">
                <span class="label">姓名:</span>
                <el-input v-model="formData.name" placeholder="请输入姓名" />
              </div>
              <div class="form-item">
                <span class="label">性别:</span>
                <el-input v-model="formData.gender" placeholder="请输入性别" />
              </div>
              <div class="form-item">
                <span class="label">出生年月:</span>
                <el-date-picker
                    v-model="formData.birthDate"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY.MM.DD"
                    value-format="YYYY.MM.DD"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item">
                <span class="label">职称:</span>
                <el-input v-model="formData.title" placeholder="请输入职称" />
              </div>
              <div class="form-item">
                <span class="label">职务:</span>
                <el-input v-model="formData.position" placeholder="请输入职务" />
              </div>
              <div class="form-item">
                <span class="label">最高学历:</span>
                <el-input v-model="formData.education" placeholder="请输入最高学历" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item full-width">
                <span class="label">通讯地址:</span>
                <el-input v-model="formData.address" placeholder="请输入通讯地址" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item">
                <span class="label">学科方向:</span>
                <el-input v-model="formData.academicDirection" placeholder="请输入学科方向" />
              </div>
              <div class="form-item">
                <span class="label">人才计划:</span>
                <el-input v-model="formData.talentPlan" placeholder="请输入人才计划" />
              </div>
              <div class="form-item">
                <span class="label">办公地点:</span>
                <el-input v-model="formData.officeLocation" placeholder="请输入办公地点" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item">
                <span class="label">电子邮箱:</span>
                <el-input v-model="formData.email" placeholder="请输入电子邮箱" />
              </div>
              <div class="form-item">
                <span class="label">联系方式:</span>
                <el-input v-model="formData.phone" placeholder="请输入联系方式" />
              </div>
              <div class="form-item">
                <span class="label">导师类型:</span>
                <el-input v-model="formData.tutorType" placeholder="请输入导师类型" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item">
                <span class="label">论文:</span>
                <el-input v-model="formData.papers" placeholder="请输入论文数量" />
              </div>
              <div class="form-item">
                <span class="label">项目:</span>
                <el-input v-model="formData.projects" placeholder="请输入项目数量" />
              </div>
            </div>
          </div>
        </div>

        <!-- 详细信息部分 -->
        <div class="detail-sections">
          <h3 class="section-title">教育与工作经历</h3>
          <div class="section-content">
            <el-input
                type="textarea"
                v-model="formData.eduWorkHistory"
                :rows="4"
                placeholder="请输入教育与工作经历"
            />
          </div>

          <h3 class="section-title">研究方向</h3>
          <div class="section-content">
            <el-input
                type="textarea"
                v-model="formData.researchDirection"
                :rows="4"
                placeholder="请输入研究方向"
            />
          </div>

          <h3 class="section-title">近五年承担的科研项目</h3>
          <div class="section-content">
            <el-input
                type="textarea"
                v-model="formData.recentProjects"
                :rows="4"
                placeholder="请输入近五年承担的科研项目"
            />
          </div>

          <h3 class="section-title">代表性学术论文</h3>
          <div class="section-content">
            <el-input
                type="textarea"
                v-model="formData.representativePapers"
                :rows="4"
                placeholder="请输入代表性学术论文"
            />
          </div>

          <h3 class="section-title">授权国家发明专利及出版专著</h3>
          <div class="section-content">
            <el-input
                type="textarea"
                v-model="formData.patents"
                :rows="4"
                placeholder="请输入授权国家发明专利及出版专著"
            />
          </div>
        </div>

        <!-- 雷达图 -->
        <div class="evaluation-chart-section">
          <div id="evaluation-radar-chart" class="radar-chart"></div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <!-- <button class="drawer-btn cancel-btn" @click="handleClose">取消</button>
        <button class="drawer-btn confirm-btn" @click="handleSave">确定</button> -->
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { RadarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage } from 'element-plus';

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

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  dimensions: {
    type: Array,
    default: () => []
  },
  teacherData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'save']);

// 用于visible属性的双向绑定
const drawerVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 默认照片占位符
const defaultPhoto = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='120' viewBox='0 0 100 120'%3E%3Crect width='100' height='120' fill='%234986ff' opacity='0.3'/%3E%3Ccircle cx='50' cy='45' r='25' fill='%234986ff' opacity='0.6'/%3E%3Ccircle cx='50' cy='95' r='35' fill='%234986ff' opacity='0.6'/%3E%3C/svg%3E`;

// 抽屉标题的计算属性
const drawerTitle = computed(() => props.isEdit ? '详情' : '新增评估');

// 标签页配置
const tabs = [
  { label: 'URL输入', value: 'url' },
  { label: '上传文档', value: 'upload' },
  { label: '手动录入', value: 'manual' }
];

// 激活的标签页
const activeTab = ref('url');

// URL输入
const urlInput = ref('');

// 数据是否已加载标志
const dataLoaded = ref(false);

// 选择的上传文件
const selectedFile = ref(null);

// 表单数据
const formData = reactive({
  id: 'BLG45187',
  name: '',
  gender: '',
  birthDate: '',
  title: '',
  position: '',
  education: '',
  address: '',
  academicDirection: '',
  talentPlan: '',
  officeLocation: '',
  email: '',
  phone: '',
  tutorType: '',
  papers: '',
  projects: '',
  photo: '',
  eduWorkHistory: '',
  researchDirection: '',
  recentProjects: '',
  representativePapers: '',
  patents: '',
  evaluationData: [60, 60, 60, 60, 60, 60]  // 默认评估数据
});

// 雷达图实例
let chart = null;

// 从props初始化表单数据
watch(() => props.teacherData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    Object.assign(formData, newValue);
    if (props.isEdit) {
      dataLoaded.value = true;
    }
  }
}, { immediate: true, deep: true });

// 监听抽屉可见性变化
watch(() => props.visible, (isVisible) => {
  if (isVisible && dataLoaded.value) {
    // 当抽屉变为可见时，初始化或更新图表
    nextTick(() => {
      initRadarChart();
    });
  }
});

// 组件挂载时初始化
onMounted(() => {
  if (props.visible && dataLoaded.value) {
    initRadarChart();
  }
});

// 初始化雷达图
const initRadarChart = () => {
  const chartDom = document.getElementById('evaluation-radar-chart');
  if (!chartDom) return;

  // 清除任何现有图表
  if (chart) {
    chart.dispose();
  }

  chart = echarts.init(chartDom);

  // 从dimensions生成指标
  const indicators = props.dimensions.map(dim => ({
    name: dim.name,
    max: 100
  })) || [
    { 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: formData.evaluationData,
            name: '评估结果',
            areaStyle: { opacity: 0 },
            lineStyle: { color: 'rgb(63, 196, 15)', width: 2 },
            itemStyle: { color: 'rgb(63, 196, 15)' }
          }
        ]
      }
    ]
  });

  // 添加窗口大小变化事件监听器
  window.addEventListener('resize', () => {
    chart && chart.resize();
  });
};

// 处理文件变更
const handleFileChange = (file) => {
  selectedFile.value = file;

  // 文件上传后的模拟数据加载
  setTimeout(() => {
    fetchMockData();
  }, 500);
};

// 从URL获取数据
const fetchDataFromUrl = async () => {
  if (!urlInput.value) {
    return;
  }

  // 演示使用模拟数据
  fetchMockData();
};

// 用于演示的模拟数据
const fetchMockData = () => {
  // 模拟与图片中匹配的响应数据
  const response = {
    id: 'BLG45187',
    name: '张三',
    gender: '男',
    birthDate: '1991.11.12',
    title: '预聘助理教授',
    position: '教授',
    education: '博士研究生',
    address: '北京市海淀区北京理工大学自动化学院',
    academicDirection: '控制理论与控制工程',
    talentPlan: '无',
    officeLocation: '6号楼509',
    email: 'zhangsan@bit.edu.cn',
    phone: '15487546574',
    tutorType: '硕士生导师',
    papers: '15篇',
    projects: '26项',
    photo: defaultPhoto,
    eduWorkHistory: '2023.12 至今北京理工大学, 自动化学院, 预聘助理教授\n2020.07-2023.12 北京理工大学 自动化学院 博士后(合作导师:张国良 教授)\n2016.09-2021.09 北京航空航天大学 自动化科学与电气工程学院 控制科学与工程 博士 联培\n2011.09-2015.06 中国石油大学(华东)机械设计制造及其自动化 本科',
    researchDirection: '伺服控制\n高天空地机器人协同',
    recentProjects: '项目1\n项目2\n项目3',
    representativePapers: '论文1\n论文2\n论文3',
    patents: '专利1\n专利2',
    evaluationData: [85, 90, 78, 82, 76, 88]
  };

  // 使用响应更新表单数据
  Object.assign(formData, response);

  // 设置数据已加载标志
  dataLoaded.value = true;

  // 更新图表
  nextTick(() => {
    initRadarChart();
  });
};

// 处理关闭
const handleClose = () => {
  drawerVisible.value = false;
  // 重置数据加载状态
  if (!props.isEdit) {
    dataLoaded.value = false;
  }
};

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

// 处理保存
const handleSave = async () => {
  try {
    // 准备请求体数据
    const talentData = { ...formData.value };
    
    // 发送POST请求到后端API
    const response = await fetch('http://localhost:8000/talents', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getToken()}`
      },
      body: JSON.stringify(talentData)
    });
    
    if (response.ok) {
      const savedData = await response.json();
      emit('save', savedData);
      ElMessage.success('保存成功');
      handleClose();
    } else {
      const error = await response.json();
      ElMessage.error(`保存失败: ${error.detail || '未知错误'}`);
    }
  } catch (error) {
    console.error('保存请求出错:', error);
    ElMessage.error('保存失败，请稍后再试');
  }
};
</script>

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

.el-drawer__body{
  padding: 0px !important;
}
.el-drawer__header{
  background-color: #0c1633 !important;
  margin-bottom:0px !important;
}
.el-drawer__footer{
  background-color: #0c1633 !important;
}
</style>

<style scoped>
.talent-drawer :deep(.el-drawer__header) {
  margin-bottom: 0;
  color: white;
  background-color: #0c1633;
  border-bottom: 1px solid rgba(73,134,255,0.3);
}

.talent-drawer :deep(.el-drawer__body) {
  padding: 0;
  overflow: hidden;
  background-color: #0c1633;
}

.drawer-content {
  padding: 20px;
  color: white;
  height: 100%;
  overflow-y: auto;
  background-color: #0c1633;
}

/* 标签导航 */
.tab-navigation {
  display: flex;
  border-bottom: 1px solid rgba(73,134,255,0.3);
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 16px;
  color: rgba(255,255,255,0.7);
  position: relative;
}

.tab-item.active {
  color: #4986ff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #4986ff;
}

/* URL输入部分 */
.url-input-container {
  display: flex;
  margin-bottom: 20px;
}

.url-input {
  flex: 1;
  margin-right: 10px;
}

/* 上传部分 */
.upload-container {
  margin-bottom: 20px;
}

.el-upload__tip {
  color: rgba(255,255,255,0.7);
  margin-top: 5px;
}

/* 手动输入提示 */
.manual-input-tip {
  margin-bottom: 20px;
  color: rgba(255,255,255,0.7);
}

/* 个人信息表单 */
.form-header {
  display: flex;
  margin-bottom: 30px;
  background-color: #1f3266;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid rgba(73,134,255,0.3);
}

.photo-section {
  margin-right: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.basic-info {
  flex: 1;
}

.form-row {
  display: flex;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  margin-right: 15px;
  display: flex;
  flex-direction: column;
}

.form-item:last-child {
  margin-right: 0;
}

.form-item.full-width {
  flex: 3;
}

.label {
  display: block;
  margin-bottom: 8px;
  color: rgba(255,255,255,0.7);
}

/* 详细信息部分 */
.detail-sections {
  margin-bottom: 30px;
  background-color: #1f3266;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid rgba(73,134,255,0.3);
}

.section-title {
  margin: 15px 0 10px;
  font-size: 16px;
  color: rgba(255,255,255,0.9);
}

.section-content {
  margin-bottom: 20px;
}

/* 雷达图部分 */
.evaluation-chart-section {
  background-color: #1f3266;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid rgba(73,134,255,0.3);
}

.radar-chart {
  width: 100%;
  height: 300px; /* 明确指定雷达图高度 */
  min-height: 300px; /* 确保最小高度 */
}

/* 抽屉页脚 */
.talent-drawer :deep(.el-drawer__footer) {
  border-top: 1px solid rgba(73,134,255,0.3);
  padding: 10px 20px;
  background-color: #0c1633;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
}

/* 按钮样式 - 现在与TalentDetail中的按钮一致 */
.drawer-btn {
  padding: 8px 15px;
  border-radius: 10px;
  font-size: 14px;
  font-family: PingFangSC-regular;
  cursor: pointer;
  margin-left: 10px;
}

.cancel-btn {
  background-color: transparent;
  color: rgba(255,255,255,0.8);
  border: 1px solid rgba(73,134,255,0.5);
}

.confirm-btn {
  background-color: rgba(14,62,167,1);
  color: rgba(255,255,255,1);
  border: 1px solid rgba(73,134,255,1);
}

/* Element Plus组件的深色主题覆盖样式 */
:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper) {
  background-color: rgba(255,255,255,0.1);
  box-shadow: 0 0 0 1px rgba(73,134,255,0.3) inset;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  background-color: transparent;
  color: white;
}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: rgba(255,255,255,0.5);
}

:deep(.el-select .el-input__wrapper) {
  background-color: rgba(255,255,255,0.1);
  box-shadow: 0 0 0 1px rgba(73,134,255,0.3) inset;
}

:deep(.el-select-dropdown__item) {
  color: #606266;
}

:deep(.el-date-editor) {
  background-color: rgba(255,255,255,0.1);
  border-color: rgba(73,134,255,0.3);
  color: white;
}

:deep(.el-upload),
:deep(.el-upload-dragger) {
  background-color: rgba(255,255,255,0.1);
  border-color: rgba(73,134,255,0.3);
}

/* 滚动条样式 */
.drawer-content::-webkit-scrollbar {
  width: 6px;
}

.drawer-content::-webkit-scrollbar-track {
  background: transparent;
}

.drawer-content::-webkit-scrollbar-thumb {
  background-color: #4986ff;
  border-radius: 10px;
  border: none;
}

.detail-content-image {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
}

.talent-detail-image {
  width: 100%;
  max-width: 800px;
  object-fit: contain;
}
</style>