<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 primary-dimension">
            <div class="dimension-name">
              <el-input 
                v-model="dim.name" 
                placeholder="请输入一级维度名称" 
              />
            </div>
            <div class="dimension-actions">
              <el-button 
                type="primary" 
                icon="Plus" 
                circle 
                @click="addSubDimension(index)"
                class="add-sub-btn"
              />
              <el-button 
                type="danger" 
                icon="Delete" 
                circle 
                @click="removeDimension(index)"
                class="delete-btn"
              />
            </div>
            
            <!-- 二级维度列表 -->
            <div class="sub-dimensions-list">
              <div v-for="(subDim, subIndex) in dim.subDimensions" :key="`${index}-${subIndex}`" class="dimension-item sub-dimension">
                <div class="dimension-name">
                  <el-input 
                    v-model="subDim.name" 
                    placeholder="请输入二级维度名称" 
                  />
                </div>
                <div class="dimension-weight">
                  <div class="weight-input-group">
                    <el-input-number 
                      v-model="subDim.weight" 
                      :min="1" 
                      :max="100" 
                      :step="1"
                    />
                    <span class="weight-unit">%</span>
                  </div>
                  <el-button 
                    type="danger" 
                    icon="Delete" 
                    circle 
                    @click="removeSubDimension(index, subIndex)"
                    class="delete-btn"
                  />
                </div>
              </div>
            </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 action-item">
              <span class="label">&nbsp;</span>
              <div class="action-container">
                <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"
          :disabled="totalWeight !== 100"
        >确认</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: () => []
  }
});

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
    const dimensionsCopy = JSON.parse(JSON.stringify(newDimensions));
    
    // 确保每个维度都有subDimensions数组
    dimensionsCopy.forEach(dim => {
      if (!dim.subDimensions) {
        dim.subDimensions = [];
      }
    });
    
    dimensions.value = dimensionsCopy;
  } else {
    dimensions.value = [];
  }
}, { immediate: true, deep: true });

// 新维度数据
const newDimension = reactive({
  name: '',
  subDimensions: []
});

// 计算所有二级维度的总权重
const totalWeight = computed(() => {
  let total = 0;
  dimensions.value.forEach(dim => {
    dim.subDimensions.forEach(subDim => {
      total += (subDim.weight || 0);
    });
  });
  return total;
});

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

// 添加二级维度
const addSubDimension = (parentIndex) => {
  // 确保维度对象存在且有subDimensions属性
  if (!dimensions.value[parentIndex]) {
    console.error('维度不存在:', parentIndex);
    return;
  }
  
  // 如果subDimensions不存在，先初始化为空数组
  if (!dimensions.value[parentIndex].subDimensions) {
    dimensions.value[parentIndex].subDimensions = [];
  }
  
  // 添加新的二级维度
  dimensions.value[parentIndex].subDimensions.push({
    name: '',
    weight: 5
  });
};

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

// 删除二级维度
const removeSubDimension = (parentIndex, subIndex) => {
  dimensions.value[parentIndex].subDimensions.splice(subIndex, 1);
};

// 处理关闭
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;
  }
  
  // 检查每个二级维度是否都有名称
  let hasEmptyName = false;
  dimensions.value.forEach(dim => {
    if (!dim.name) {
      hasEmptyName = true;
    }
    dim.subDimensions.forEach(subDim => {
      if (!subDim.name) {
        hasEmptyName = true;
      }
    });
  });
  
  if (hasEmptyName) {
    ElMessage.error('请为所有维度填写名称');
    return;
  }
  
  try {
    // 从localStorage获取JWT令牌
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('未登录或登录已过期，请重新登录');
      return;
    }

    // 将二级维度结构保存到后端
    const response = await axios.post(`${getApiBaseUrl()}/dimensions/save`, {
      dimensions: dimensions.value,
      category: 'lab'
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.data && response.data.success) {
      // 发送保存事件
      emit('save', dimensions.value);
      
      // 关闭抽屉
      handleClose();
      
      ElMessage.success('维度设置保存成功');
    } else {
      throw new Error(response.data?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存维度数据失败:', error);
    ElMessage.error(`保存维度数据失败: ${error.message}`);
  }
};
</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;
  overflow-y: auto;
}

.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 {
  padding: 10px;
  transition: all 0.3s ease;
}

.primary-dimension {
  background-color: rgba(73,134,255,0.1);
  border-radius: 8px;
  margin-bottom: 15px;
  border-left: 3px solid #4986ff;
}

.dimension-name {
  flex: 1;
  margin-bottom: 10px;
}

.dimension-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 10px;
}

.sub-dimensions-list {
  margin-left: 20px;
}

.sub-dimension {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(255,255,255,0.05);
  border-radius: 4px;
  margin-bottom: 8px;
  padding: 8px;
}

.sub-dimension .dimension-name {
  flex: 1;
  margin-bottom: 0;
  margin-right: 10px;
}

.dimension-weight {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 120px;
  justify-content: flex-end;
}

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

.delete-btn, .add-sub-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;
  align-items: flex-end;
}

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

.action-item {
  flex: 0.3;
}

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

.action-container {
  display: flex;
  justify-content: flex-end;
}

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

.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> 