<template>
  <div class="geometry-complexity-result-page">
    <div class="page-header">
      <h2>
        <i class="fas fa-chart-line"></i>
        几何复杂度分析结果
      </h2>
      <p>Creo几何复杂度分析结果展示</p>
    </div>

    <div class="page-content">
      <!-- 分析统计摘要 -->
      <div class="complexity-analysis-summary">
        <div class="summary-header">
          <h4><i class="fas fa-chart-pie"></i> 分析摘要</h4>
          <div class="analysis-time">
            <i class="fas fa-clock"></i>
            完成时间: {{ analysisTimeFormatted }}
          </div>
        </div>

        <div class="summary-stats">
          <div class="stat-card">
            <div class="stat-value">{{ totalPartsAnalyzed }}</div>
            <div class="stat-label">总零件数</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ averageComplexity }}</div>
            <div class="stat-label">平均复杂度</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ selectedParts.size }}</div>
            <div class="stat-label">已选择零件</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ highComplexityCount }}</div>
            <div class="stat-label">高复杂度零件</div>
          </div>
        </div>
      </div>

      <!-- 零件列表区域 -->
      <div class="complexity-parts-list">
        <div class="complexity-parts-header">
          <h4>
            <i class="fas fa-list"></i>
            几何复杂度分析结果 ({{ partsData.length }} 个零件)
          </h4>
          <div class="complexity-controls">
            <button class="complexity-select-all" @click="selectAll">
              <i class="fas fa-check-square"></i>
              全选
            </button>
            <button class="complexity-clear-all" @click="clearAll">
              <i class="far fa-square"></i>
              清空
            </button>
          </div>
        </div>

        <div class="table-container">
          <table class="complexity-parts-table">
            <thead>
              <tr>
                <th width="50">选择</th>
                <th width="60">ID</th>
                <th width="200">零件名称</th>
                <th width="80">表面数</th>
                <th width="80">特征数</th>
                <th width="80">曲面数</th>
                <th width="60">孔数</th>
                <th width="80">圆角数</th>
                <th width="100">复杂度得分</th>
                <th width="100">体积 (mm³)</th>
              </tr>
            </thead>
            <tbody id="complexity-parts-tbody">
              <tr
                v-for="part in partsData"
                :key="part.uniqueId"
                class="complexity-part-row"
                :class="{ selected: selectedParts.has(part.uniqueId) }"
                :data-part-id="part.uniqueId"
              >
                <td>
                  <input
                    type="checkbox"
                    class="complexity-checkbox"
                    :data-part-id="part.uniqueId"
                    :checked="selectedParts.has(part.uniqueId)"
                    @change="updateSelection"
                  />
                </td>
                <td>{{ part.uniqueId }}</td>
                <td>
                  <div class="part-info">
                    <span class="complexity-part-name">{{ part.part_name }}</span>
                    <div class="complexity-part-path">{{ part.part_path }}</div>
                    <div class="complexity-file-size">{{ part.file_size }}</div>
                  </div>
                </td>
                <td>{{ part.surface_count }}</td>
                <td>{{ part.feature_count }}</td>
                <td>{{ part.curved_surface_count }}</td>
                <td>{{ part.hole_count }}</td>
                <td>{{ part.fillet_count }}</td>
                <td>
                  <span
                    class="complexity-score"
                    :class="getComplexityClass(part.complexity_score)"
                  >
                    {{ part.complexity_score.toFixed(2) }}
                  </span>
                </td>
                <td>{{ formatVolume(part.volume) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 删除操作区域 -->
      <div class="complexity-delete-section">
        <div class="complexity-delete-header">
          <h4>
            <i class="fas fa-trash"></i>
            删除操作
          </h4>
          <div class="complexity-selected-count" id="complexity-selected-count">
            已选择: {{ selectedParts.size }} 个零件
          </div>
        </div>

        <div class="complexity-delete-summary">
          <p>选中的零件将从模型中删除。请仔细检查选择的零件，删除操作无法撤销。</p>
        </div>

        <button
          id="complexity-delete-btn"
          class="complexity-delete-btn"
          :disabled="selectedParts.size === 0"
          @click="deleteSelected"
        >
          <i class="fas fa-trash"></i>
          删除选中零件
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { creoApi } from '@/services/creoApi'

// 定义props
const props = defineProps({
  analysisData: {
    type: Object,
    default: null
  }
})

// 响应式数据
const selectedParts = ref(new Set())
const deletedParts = ref(new Set())
const analysisTime = ref('')

// 为零件添加稳定ID并过滤已删除的零件
const partsData = computed(() => {
  const rawParts = props.analysisData?.parts || []
  return rawParts
    .map((part, index) => ({
      ...part,
      uniqueId: index + 1, // 稳定的唯一ID
    }))
    .filter(part => !deletedParts.value.has(part.uniqueId))
})

// 计算属性 - 优先使用API返回的统计数据
const averageComplexity = computed(() => {
  return props.analysisData?.average_complexity?.toFixed(2) || '0.00'
})

const totalPartsAnalyzed = computed(() => {
  return props.analysisData?.total_parts_analyzed || partsData.value.length
})

const analysisTimeFormatted = computed(() => {
  if (props.analysisData?.analysis_time) {
    return new Date(props.analysisData.analysis_time).toLocaleString('zh-CN')
  }
  return analysisTime.value
})

const highComplexityCount = computed(() => {
  return partsData.value.filter(part => part.complexity_score >= 7.0).length
})

// 方法
const getComplexityClass = (score) => {
  if (score >= 8.5) return 'very-high'
  if (score >= 7.0) return 'high'
  if (score >= 5.0) return 'medium'
  if (score >= 3.0) return 'low'
  return 'very-low'
}

const formatVolume = (volume) => {
  if (volume === 0 || volume === null || volume === undefined) {
    return 'N/A'
  }
  return volume.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const selectAll = () => {
  selectedParts.value.clear()
  partsData.value.forEach(part => {
    selectedParts.value.add(part.uniqueId)
  })
}

const clearAll = () => {
  selectedParts.value.clear()
}

const updateSelection = (event) => {
  const partId = parseInt(event.target.getAttribute('data-part-id'))
  if (event.target.checked) {
    selectedParts.value.add(partId)
  } else {
    selectedParts.value.delete(partId)
  }
}

const deleteSelected = async () => {
  if (selectedParts.value.size === 0) {
    return
  }

  await ElMessageBox.confirm(
    `确定要删除选中的 ${selectedParts.value.size} 个零件吗？此操作不可撤销！`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )

  // 获取选中零件的路径
  const selectedPartIds = Array.from(selectedParts.value)
  const componentPaths = []

  selectedPartIds.forEach(partId => {
    const part = partsData.value.find(p => p.uniqueId === partId)
    if (part && part.part_path) {
      componentPaths.push(part.part_path)
    }
  })

  if (componentPaths.length === 0) {
    return
  }

  const result = await creoApi.deleteComponentsByPath(componentPaths, false)
  if (result.success) {
    // 将已删除的零件ID添加到删除集合中
    selectedPartIds.forEach(partId => {
      deletedParts.value.add(partId)
    })
    // 清空选择
    selectedParts.value.clear()
  }
}

// 生命周期
onMounted(() => {
  analysisTime.value = new Date().toLocaleString('zh-CN')
})
</script>

<style scoped>
/* 页面基础样式 */
.geometry-complexity-result-page {
  padding: var(--spacing-2xl);
  height: 100%;
}

.page-header {
  margin-bottom: var(--spacing-2xl);
}

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

.page-header h2 i {
  color: var(--color-complexity);
}

.page-header p {
  color: var(--color-text-secondary);
  margin: 0;
}

.page-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

/* 分析统计摘要样式 */
.complexity-analysis-summary {
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-complexity-border-1);
  border-radius: var(--size-border-radius-card);
  padding: var(--spacing-xl);
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 1px solid var(--color-complexity-border-2);
}

.summary-header h4 {
  margin: 0;
  color: var(--color-complexity);
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.analysis-time {
  color: var(--color-text-muted);
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.summary-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: var(--spacing-md);
}

.stat-card {
  background: var(--color-white-rgb-05);
  border: 1px solid var(--color-complexity-border-15);
  border-radius: var(--size-border-radius);
  padding: var(--spacing-md);
  text-align: center;
  transition: all 0.2s ease;
}

.stat-card:hover {
  background: var(--color-complexity-bg-2);
  transform: translateY(-2px);
}

.stat-value {
  font-size: var(--font-size-2xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-complexity);
  line-height: 1.2;
  margin-bottom: var(--spacing-xs);
}

.stat-label {
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
  font-weight: var(--font-weight-medium);
}

/* 零件列表样式 */
.complexity-parts-list {
  background: var(--color-bg-secondary);
  border-radius: var(--size-border-radius-card);
  overflow: hidden;
}

.complexity-parts-header {
  background: var(--color-complexity-border-15);
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--color-complexity-border-2);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.complexity-parts-header h4 {
  margin: 0;
  color: var(--color-complexity);
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.complexity-controls {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
}

.complexity-select-all,
.complexity-clear-all {
  background: var(--color-complexity-border-15);
  border: 1px solid var(--color-complexity-border-3);
  color: var(--color-complexity);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-sm);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.complexity-select-all:hover,
.complexity-clear-all:hover {
  background: var(--color-complexity-border-2);
}

.table-container {
  max-height: 400px;
  overflow-y: auto;
}

.complexity-parts-table {
  width: 100%;
  border-collapse: collapse;
}

.complexity-parts-table th {
  background: var(--color-bg-secondary);
  color: var(--color-complexity);
  padding: var(--spacing-sm) var(--spacing-md);
  text-align: left;
  font-weight: var(--font-weight-semibold);
  border-bottom: 1px solid var(--color-complexity-border-2);
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: var(--color-shadow-btn);
}

.complexity-parts-table td {
  padding: var(--spacing-sm) var(--spacing-md);
  border-bottom: 1px solid var(--color-complexity-border-15);
  color: var(--color-text-secondary);
}

.complexity-parts-table tr:hover {
  background: var(--color-complexity-bg-1);
}

.complexity-parts-table tr.selected {
  background: var(--color-complexity-bg-2);
  border-left: 3px solid var(--color-complexity);
}

.complexity-checkbox {
  width: 18px;
  height: 18px;
  accent-color: var(--color-complexity);
  cursor: pointer;
}

.part-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.complexity-part-name {
  color: var(--color-primary);
  font-weight: var(--font-weight-medium);
  font-size: var(--font-size-sm);
}

.complexity-part-path {
  color: var(--color-complexity-low);
  font-size: var(--font-size-xs);
  font-family: 'Courier New', monospace;
  opacity: 0.8;
}

.complexity-file-size {
  color: var(--color-text-muted);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-medium);
}

.complexity-score {
  display: inline-block;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-sm);
  font-weight: var(--font-weight-semibold);
  font-size: var(--font-size-sm);
}

.complexity-score.very-high {
  background: var(--color-complexity-critical-bg);
  color: var(--color-complexity-critical);
  font-weight: var(--font-weight-bold);
}

.complexity-score.high {
  background: var(--color-complexity-high-bg);
  color: var(--color-complexity-high);
  font-weight: var(--font-weight-semibold);
}

.complexity-score.medium {
  background: var(--color-complexity-medium-bg);
  color: var(--color-complexity-medium);
}

.complexity-score.low {
  background: var(--color-complexity-low-bg);
  color: var(--color-complexity-low);
}

.complexity-score.very-low {
  background: var(--color-complexity-excellent-bg);
  color: var(--color-complexity-excellent);
}

/* 删除操作区域 */
.complexity-delete-section {
  background: var(--color-complexity-bg-1);
  border: 1px solid var(--color-complexity-border-2);
  border-radius: var(--size-border-radius-card);
  padding: var(--spacing-xl);
}

.complexity-delete-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
}

.complexity-delete-header h4 {
  margin: 0;
  color: var(--color-complexity);
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.complexity-selected-count {
  background: var(--color-complexity-border-15);
  color: var(--color-complexity);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-full);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
}

.complexity-delete-summary {
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--color-complexity-bg-2);
  border-radius: var(--size-border-radius);
  border-left: 4px solid var(--color-complexity);
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
}

.complexity-delete-btn {
  background: var(--color-complexity-high-gradient);
  border: none;
  color: white;
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--size-border-radius);
  cursor: pointer;
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px var(--color-primary-rgb-3);
}

.complexity-delete-btn:hover:not(:disabled) {
  background: var(--color-complexity-high-gradient-hover);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px var(--color-primary-rgb-4);
}

.complexity-delete-btn:disabled {
  background: var(--color-white-rgb-3);
  cursor: not-allowed;
  box-shadow: none;
  transform: none;
}
</style>