<template>
  <el-drawer
    v-model="props.visible"
    title=""
    direction="rtl"
    size="600px"
    :before-close="handleClose"
    custom-class="dimension-drawer"
  >
    <div class="drawer-content">
      <div class="dimension-section">
        <h2 class="section-title">评估维度设置</h2>
        
        <!-- 维度列表 -->
        <div class="dimensions-list">
          <div v-for="(dim, index) in dimensions" :key="index" class="dimension-item">
            <div class="dimension-name">
              <el-input 
                v-model="dim.name" 
                placeholder="请输入维度名称" 
              />
            </div>
            <div class="dimension-weight">
              <div class="weight-input-group">
                <el-input-number 
                  v-model="dim.weight" 
                  :min="1" 
                  :max="100" 
                  :step="1"
                />
                <span class="weight-unit">%</span>
              </div>
              <el-button 
                type="danger" 
                icon="Delete" 
                circle 
                @click="removeDimension(index)"
                class="delete-btn"
              />
            </div>
          </div>
        </div>
        
        <!-- 新增维度表单 -->
        <div class="new-dimension-form">
          <div class="form-row">
            <div class="form-item">
              <span class="label">新增维度名称</span>
              <el-input 
                v-model="newDimension.name" 
                placeholder="请输入维度名称"
                class="dimension-input"
              />
            </div>
            <div class="form-item weight-item">
              <span class="label">维度权重</span>
              <div class="weight-input-container">
                <el-input-number 
                  v-model="newDimension.weight" 
                  :min="1" 
                  :max="100" 
                  :step="1"
                  class="weight-input"
                />
                <span class="weight-unit">%</span>
                <el-button 
                  type="primary"
                  icon="Plus"
                  circle
                  class="add-btn"
                  @click="addDimension"
                  :disabled="!newDimension.name"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 权重总计信息 -->
        <div class="weight-summary">
          <div class="weight-total">
            <span>权重维度要求:</span>
            <span class="weight-value">100%</span>
          </div>
          <div class="weight-current" :class="{ 'weight-error': totalWeight !== 100 }">
            <span>当前权重维度总计:</span>
            <span class="weight-value">{{ totalWeight }}%</span>
          </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, computed, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { getApiBaseUrl } from '../config'; // 导入API基础URL函数

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  dimensions: {
    type: Array,
    default: () => []
  },
  category: {
    type: String,
    default: 'talent' // 'talent'或'lab'
  }
});

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

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

// 所有维度数据
const dimensions = ref([]);

// 初始化维度数据
watch(() => props.dimensions, (newDimensions) => {
  if (newDimensions && newDimensions.length > 0) {
    // 深拷贝维度数据，避免直接修改props
    dimensions.value = JSON.parse(JSON.stringify(newDimensions));
  } else {
    dimensions.value = [];
  }
}, { immediate: true, deep: true });

// 新维度数据
const newDimension = reactive({
  name: '',
  weight: 5
});

// 计算总权重
const totalWeight = computed(() => {
  return dimensions.value.reduce((sum, dim) => sum + (dim.weight || 0), 0);
});

// 添加新维度
const addDimension = () => {
  if (!newDimension.name) {
    ElMessage.warning('请输入维度名称');
    return;
  }
  
  // 添加到维度列表
  dimensions.value.push({
    name: newDimension.name,
    weight: newDimension.weight
  });
  
  // 重置表单
  newDimension.name = '';
  newDimension.weight = 5;
};

// 删除维度
const removeDimension = (index) => {
  dimensions.value.splice(index, 1);
};

// 验证总权重 - 不再每次变更时显示提示
const validateTotalWeight = () => {
  // 移除提示消息，只在保存时验证
};

// 处理关闭 - 修复后的函数
const handleClose = (done) => {
  // 如果有 done 回调(来自 before-close)，则调用它
  if (typeof done === 'function') {
    done();
  }
  // 无论如何都要更新状态
  drawerVisible.value = false;
};

// 处理保存
const handleSave = async () => {


  if (totalWeight.value !== 100) {
    ElMessage.error('权重总计必须为100%，请调整后再保存');
    return;
  }
  
  try {
    // 构建要保存的维度数据
    const dimensionsData = dimensions.value.map(dim => ({
      name: dim.name,
      weight: dim.weight,
      category: props.category,
      id: dim.id
    }));

    // 从localStorage获取JWT令牌
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('未登录或登录已过期，请重新登录');
      return;
    }

    // 根据类别(教师科研人才评估或工程研究中心评估)选择对应的API接口
    const response = await axios.post(`${getApiBaseUrl()}/api/save-dimensions`, {
      dimensions: dimensionsData,
      category: props.category
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.data.success) {
      ElMessage.success('维度设置保存成功');
      // 发送保存事件，通知父组件刷新数据
      emit('save', dimensions.value);
      // 关闭抽屉
      handleClose();
    } else {
      throw new Error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存维度失败:', error);
    ElMessage.error('保存维度失败，请重试');
  }
};
</script>

<style>
/* 确保引入common.css */
@import './common.css';
</style>

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

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

.drawer-content {
  padding: 20px;
  color: white;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #0c1633;
}

.dimension-section {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.section-title {
  margin: 15px 0;
  font-size: 18px;
  color: rgba(255,255,255,0.9);
  text-align: center;
  border-bottom: 1px solid rgba(73,134,255,0.3);
  padding-bottom: 10px;
}

.dimensions-list {
  background-color: #1f3266;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid rgba(73,134,255,0.3);
  margin-bottom: 20px;
  overflow-y: auto;
  flex: 1; /* 让这个元素占满可用空间 */
}

.dimension-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid rgba(73,134,255,0.1);
}

.dimension-name {
  flex: 1;
  margin-right: 15px;
}

.dimension-weight {
  display: flex;
  align-items: center;
  gap: 10px;
}

.weight-input-group {
  display: flex;
  align-items: center;
}

.delete-btn {
  font-size: 12px;
  padding: 6px;
}

.new-dimension-form {
  background-color: #1f3266;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid rgba(73,134,255,0.3);
  margin-bottom: 20px;
}

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

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.weight-item {
  flex: 0.7;
}

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

.weight-input-container {
  display: flex;
  align-items: center;
}

.weight-input {
  width: 80px;
}

.weight-unit {
  margin: 0 5px;
  color: #4986ff;
}

.add-btn {
  margin-left: 10px;
}

.weight-summary {
  background-color: #1f3266;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid rgba(73,134,255,0.3);
  margin-top: 20px;
}

.weight-total, .weight-current {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.weight-value {
  font-weight: bold;
  color: #4986ff;
}

.weight-error .weight-value {
  color: #f56c6c;
}

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

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

/* 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-input-number) {
  width: 100px;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  background-color: rgba(73,134,255,0.2);
  color: white;
}

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

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

.drawer-content::-webkit-scrollbar-thumb,
.dimensions-list::-webkit-scrollbar-thumb {
  background-color: #4986ff;
  border-radius: 10px;
  border: none;
}
</style>