<template>
  <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="900px"
      :before-close="handleClose"
      custom-class="lab-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="lab-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="lab-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="lab-detail-image" />
        </div>
      </div>

      <!-- 工程研究中心信息表单 - 仅在数据加载后显示 -->
      <div v-if="dataLoaded" class="lab-info-form">
        <div class="form-header">
          <div class="image-section">
            <div class="lab-image">
              <img :src="formData.image || defaultImage" alt="工程研究中心照片" />
            </div>
            <div class="lab-id">ID: {{ formData.id || 'BLG00000' }}</div>
          </div>

          <div class="basic-info">
            <div class="form-row">
              <div class="form-item full-width">
                <span class="label">工程研究中心名称:</span>
                <el-input v-model="formData.name" placeholder="请输入工程研究中心名称" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item">
                <span class="label">人员数量:</span>
                <el-input v-model="formData.personnel" placeholder="请输入人员数量" />
              </div>
              <div class="form-item">
                <span class="label">国家级项目:</span>
                <el-input v-model="formData.nationalProjects" placeholder="请输入国家级项目数" />
              </div>
              <div class="form-item">
                <span class="label">其它项目:</span>
                <el-input v-model="formData.otherProjects" placeholder="请输入其它项目数" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-item">
                <span class="label">成果:</span>
                <el-input v-model="formData.achievements" 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.labAchievements"
                :rows="8"
                placeholder="请输入工程研究中心其他成就信息"
            />
          </div>
        </div>

        <!-- 雷达图 -->
        <div class="evaluation-chart-section">
          <div id="lab-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: () => []
  },
  labData: {
    type: Object,
    default: () => ({})
  }
});

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

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

// 默认工程研究中心图片占位符
const defaultImage = `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`;

// 抽屉标题的计算属性
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: '',
  personnel: '',
  nationalProjects: '',
  otherProjects: '',
  achievements: '',
  image: '',
  labAchievements: '',
  evaluationData: [60, 60, 60, 60, 60, 60]  // 默认评估数据
});

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

// 从props初始化表单数据
watch(() => props.labData, (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('lab-evaluation-radar-chart');
  if (!chartDom) return;

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

  chart = echarts.init(chartDom);

  // 从dimensions生成指标
  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: formData.evaluationData,
            name: '评估结果',
            areaStyle: { opacity: 0 },
            lineStyle: { color: 'rgb(238, 23, 143)', width: 2 }, // 玫红色线段
            itemStyle: { color: 'rgb(238, 23, 143)' } // 玫红色数据点
          }
        ]
      }
    ]
  });

  // 添加窗口大小变化事件监听器
  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: '基础力学教学实验中心',
    personnel: '30人',
    nationalProjects: '45项',
    otherProjects: '11项',
    achievements: '28项',
    image: defaultImage,
    labAchievements: `基础力学教学实验中心成立于2018年，是北京理工大学重点建设的工程研究中心之一。致力于力学基础理论与应用研究，为工业和国防科技提供科研支持。

工程研究中心拥有先进的力学测试设备和模拟系统，在材料力学、流体力学等领域具有领先优势。近年来承担多项国家重点研发计划项目。

工程研究中心现有研究人员26人，其中教授5人，副教授8人，讲师和工程技术人员13人。拥有博士生导师6人，硕士生导师10人。

近五年承担国家重点研发计划项目3项，国家自然科学基金项目12项，省部级科研项目25项，企业合作项目30余项。

近五年发表SCI论文120余篇，获得国家发明专利35项，省部级科技奖励5项。多项成果已在航空航天、高端装备制造等领域实现转化应用。`,
    evaluationData: [85, 78, 92, 76, 88, 80]
  };

  // 使用响应更新表单数据
  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 labData = { ...formData.value };
    
    // 发送POST请求到后端API
    const response = await fetch('http://localhost:8000/labs', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getToken()}`
      },
      body: JSON.stringify(labData)
    });
    
    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>
.lab-drawer :deep(.el-drawer__header) {
  margin-bottom: 0;
  color: white;
  background-color: #0c1633;
  border-bottom: 1px solid rgba(73,134,255,0.3);
}

.lab-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);
}

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

.lab-image {
  width: 150px;
  height: 100px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 10px;
}

.lab-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.lab-id {
  font-size: 14px;
  color: rgba(255,255,255,0.7);
}

.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; /* 确保最小高度 */
}

/* 抽屉页脚 */
.lab-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;
}

/* 按钮样式 */
.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;
}

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