<template>
  <div class="deletion-params-container">
    <div class="deletion-params-header">
      <h3>
        <i class="fas fa-trash-alt"></i>
        设置删除参数
      </h3>
      <button class="deletion-params-close" @click="$emit('close')">
        <i class="fas fa-times"></i>
      </button>
    </div>

    <div class="deletion-params-form">
      <!-- 层级选择区域 -->
      <div class="level-selection-section">
        <h4>
          <i class="fas fa-layer-group"></i>
          选择删除层级
        </h4>
        <div class="level-selection-description">
          选择从哪个层级开始删除模型组件。选择层级后，该层级及以下的所有组件都将被删除。
        </div>

        <div class="level-input-group">
          <div class="level-input-row">
            <label class="level-input-label">删除层级:</label>
            <div class="level-input-control">
              <input type="number"
                     class="level-number-input"
                     id="deletion-level-input"
                     min="1"
                     :max="maxLevel + 1"
                     v-model="displayLevel"
                     :disabled="loading">
              <span>或选择:</span>
              <select class="level-select"
                      id="deletion-level-select"
                      v-model="displayLevel"
                      :disabled="loading">
                <option value="">-- 选择层级 --</option>
                <option v-for="level in availableLevels" :key="level" :value="level + 1">
                  层级 {{ level + 1 }} ({{ getLevelComponentCount(level) }} 个组件)
                </option>
              </select>
            </div>
          </div>

          <div class="level-range-indicator">
            <span class="range-label">删除范围:</span>
            <span class="range-value" id="deletion-range-display">{{ rangeDisplayText }}</span>
          </div>
        </div>
      </div>


      <!-- 操作按钮 -->
      <div class="deletion-params-actions">
        <button class="params-action-btn secondary" @click="$emit('close')">
          <i class="fas fa-times"></i>
          取消
        </button>
        <button class="params-action-btn danger"
                id="execute-deletion-btn"
                @click="handleExecuteDeletion"
                :disabled="loading || selectedLevel === null">
          <i class="fas fa-trash"></i>
          执行删除
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { creoApi } from '@/services/creoApi'
import { ElNotification } from 'element-plus'
import { useCADStore } from '@/stores/cad'
import { getNotificationConfig } from '@/config/cad'

// 获取通知配置
const notificationConfig = getNotificationConfig()

// Props - 暂时保留供将来使用
defineProps({
  hierarchyData: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['close'])

// Store
const cadStore = useCADStore()

// 响应式数据
const selectedLevel = ref(null)
const hierarchyStatistics = ref({})
const totalLevels = ref(0)
const loading = ref(false)

// 计算属性 - 可用层级列表
const availableLevels = computed(() => {
  if (!hierarchyStatistics.value || Object.keys(hierarchyStatistics.value).length === 0) {
    return []
  }
  // 从statistics对象中提取所有层级并转换为数字数组
  return Object.keys(hierarchyStatistics.value)
    .map(level => parseInt(level))
    .sort((a, b) => a - b)
})

// 计算属性 - 最大层级
const maxLevel = computed(() => {
  return totalLevels.value > 0 ? totalLevels.value - 1 : 0
})

// 计算属性 - 显示层级（用户看到的层级，从1开始）
const displayLevel = computed({
  get: () => selectedLevel.value !== null ? selectedLevel.value + 1 : null,
  set: (value) => selectedLevel.value = value !== null ? value - 1 : null
})

// 计算属性 - 范围显示文本
const rangeDisplayText = computed(() => {
  if (selectedLevel.value === null) return '请选择层级'
  return `层级 ${selectedLevel.value + 1} 及以下`
})

// 获取层级组件数量
const getLevelComponentCount = (level) => {
  if (!hierarchyStatistics.value || !hierarchyStatistics.value[level]) {
    return 0
  }
  return hierarchyStatistics.value[level]
}

// 初始化默认层级
const initializeDefaultLevel = () => {
  if (availableLevels.value.length > 0) {
    let defaultLevel = availableLevels.value[0]

    if (availableLevels.value.includes(0) && availableLevels.value.includes(1)) {
      defaultLevel = 1
    } else if (availableLevels.value.includes(0) && availableLevels.value.length > 1) {
      defaultLevel = availableLevels.value[1]
    }

    selectedLevel.value = defaultLevel
  }
}

// 获取层级统计信息
const fetchHierarchyStatistics = async () => {
  loading.value = true
  const result = await creoApi.getHierarchyStatistics()
  if (result.success && result.data && result.data.data) {
    hierarchyStatistics.value = result.data.data.statistics
    totalLevels.value = result.data.data.total_levels
    initializeDefaultLevel()
  }
  loading.value = false
}

// 执行层级删除
const handleExecuteDeletion = async () => {
  if (selectedLevel.value === null) return

  if (!cadStore.currentProjectName) {
    throw new Error('当前没有项目名称')
  }

  const result = await creoApi.deleteHierarchy(selectedLevel.value, cadStore.currentProjectName)
  if (result.success) {
    // 显示删除成功的详细信息
    showDeletionSuccessMessage(result.data.data)
    emit('close')
  }
}

// 显示删除成功消息
const showDeletionSuccessMessage = (data) => {
  const totalDeleted = data.deletion_summary?.total_deleted || 0

  // 收集所有删除的组件名称
  const allDeletedComponents = []
  if (data.deleted_components) {
    Object.values(data.deleted_components).forEach(levelComponents => {
      allDeletedComponents.push(...levelComponents)
    })
  }

  // 生成组件名称列表，限制长度
  let componentsList = allDeletedComponents.join(', ')
  const maxLength = 200 // 限制显示长度
  if (componentsList.length > maxLength) {
    componentsList = componentsList.substring(0, maxLength) + '...'
  }

  // 显示成功通知
  const message = `删除成功！共删除 ${totalDeleted} 个组件：${componentsList}`

  ElNotification({
    title: '层级删除完成',
    message: message,
    type: 'success',
    duration: notificationConfig.SUCCESS_LONG_DURATION
  })
}

// 组件挂载时初始化
onMounted(() => {
  fetchHierarchyStatistics()
})
</script>

<style scoped>
/* 删除参数设置容器 */
.deletion-params-container {
  background: var(--color-bg-secondary);
  border-radius: var(--size-border-radius);
  padding: var(--spacing-xl);
  box-shadow: var(--color-shadow-card);
  border: 1px solid var(--color-border-primary);
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
}

/* 删除参数头部 */
.deletion-params-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 2px solid var(--color-border-primary);
}

.deletion-params-header h3 {
  margin: 0;
  color: var(--color-text-primary);
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.deletion-params-header h3 i {
  color: var(--color-error);
}

.deletion-params-close {
  background: none;
  border: none;
  color: var(--color-text-secondary);
  font-size: var(--font-size-xl);
  cursor: pointer;
  padding: var(--spacing-xs);
  border-radius: var(--size-border-radius-button);
  transition: all var(--transition-duration) var(--transition-timing);
}

.deletion-params-close:hover {
  background: var(--color-bg-tertiary);
  color: var(--color-text-primary);
}

/* 参数设置表单 */
.deletion-params-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

/* 层级选择区域 */
.level-selection-section {
  background: var(--color-white-rgb-05);
  border-radius: var(--size-border-radius-button);
  padding: var(--spacing-xl);
  border: 1px solid var(--color-border-primary);
}

.level-selection-section h4 {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--color-text-primary);
  font-size: var(--font-size-lg);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.level-selection-section h4 i {
  color: var(--color-primary);
}

.level-selection-description {
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
  margin-bottom: var(--spacing-xl);
  line-height: 1.5;
}

/* 层级输入控件 */
.level-input-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.level-input-row {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.level-input-label {
  min-width: 120px;
  color: var(--color-text-secondary);
  font-weight: var(--font-weight-medium);
}

.level-input-control {
  flex: 1;
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.level-number-input {
  width: 100px;
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--size-border-radius-button);
  background: var(--color-bg-primary);
  color: var(--color-text-primary);
  font-size: var(--font-size-base);
  text-align: center;
}

.level-number-input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-rgb);
}

.level-select {
  flex: 1;
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--size-border-radius-button);
  background: var(--color-bg-primary);
  color: var(--color-text-primary);
}

.level-select:focus {
  outline: none;
  border-color: var(--color-primary);
}

/* 层级范围指示器 */
.level-range-indicator {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-top: var(--spacing-md);
  padding: var(--spacing-md);
  background: var(--color-bg-tertiary);
  border-radius: var(--size-border-radius-button);
  border: 1px solid var(--color-border-primary);
}

.level-range-indicator .range-label {
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
}

.level-range-indicator .range-value {
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}



/* 操作按钮区域 */
.deletion-params-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: var(--spacing-lg);
  padding-top: var(--spacing-xl);
  border-top: 1px solid var(--color-border-primary);
}

.params-action-btn {
  padding: var(--spacing-md) var(--spacing-xl);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--size-border-radius-button);
  cursor: pointer;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  transition: all var(--transition-duration) var(--transition-timing);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  min-width: 120px;
  justify-content: center;
}

.params-action-btn.secondary {
  background: var(--color-white-rgb-05);
  color: var(--color-text-secondary);
  border-color: var(--color-border-primary);
}

.params-action-btn.secondary:hover {
  background: var(--color-bg-tertiary);
  border-color: var(--color-border-secondary);
  color: var(--color-text-primary);
}

.params-action-btn.danger {
  background: var(--color-error);
  color: white;
  border-color: var(--color-error);
}

.params-action-btn.danger:hover:not(:disabled) {
  background: var(--color-error);
  opacity: 0.9;
  transform: translateY(-1px);
}

.params-action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .deletion-params-container {
    padding: var(--spacing-xl);
    margin-top: var(--spacing-lg);
  }

  .deletion-params-header {
    flex-direction: column;
    gap: var(--spacing-md);
    text-align: center;
  }

  .level-input-row {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }

  .level-input-label {
    min-width: auto;
  }

  .deletion-params-actions {
    flex-direction: column;
    gap: var(--spacing-md);
  }

  .params-action-btn {
    width: 100%;
  }

}

/* 动画效果 */
@keyframes slideInFromTop {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>