<template>
  <div class="shell-analysis-result-page">
    <div class="page-header">
      <h2>
        <i class="fas fa-magic"></i>
        智能薄壳化分析结果
      </h2>
      <p>Creo智能薄壳化分析结果展示</p>
    </div>

    <div class="page-content">
      <!-- 分析统计摘要 -->
      <div class="shell-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>
            完成时间: {{ analysisTime }}
          </div>
        </div>

        <div class="summary-stats">
          <div class="stat-card">
            <div class="stat-value">{{ allParts.length }}</div>
            <div class="stat-label">总零件数</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ analysisResults.estimatedReduction.volumeReduction }}</div>
            <div class="stat-label">体积减少</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ analysisResults.estimatedReduction.fileSizeReduction }}</div>
            <div class="stat-label">文件大小减少</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ analysisResults.estimatedReduction.performanceImprovement }}</div>
            <div class="stat-label">性能提升</div>
          </div>
        </div>
      </div>

      <!-- 零件列表区域 -->
      <div class="shell-parts-list">
        <div class="shell-parts-header">
          <h4>
            <i class="fas fa-list"></i>
            薄壳化分析结果 ({{ filteredParts.length }} 个零件)
          </h4>
          <div class="shell-controls">
            <!-- 筛选器 -->
            <div class="filter-controls">
              <button
                class="filter-btn"
                :class="{ active: currentFilter === 'all' }"
                @click="setFilter('all')"
              >
                全部
              </button>
              <button
                class="filter-btn"
                :class="{ active: currentFilter === 'safe_delete' }"
                @click="setFilter('safe_delete')"
              >
                安全删除
              </button>
              <button
                class="filter-btn"
                :class="{ active: currentFilter === 'recommended_delete' }"
                @click="setFilter('recommended_delete')"
              >
                建议删除
              </button>
              <button
                class="filter-btn"
                :class="{ active: currentFilter === 'must_keep' }"
                @click="setFilter('must_keep')"
              >
                必须保留
              </button>
            </div>

            <div class="action-controls">
              <button class="shell-select-all" @click="selectAll">
                <i class="fas fa-check-square"></i>
                全选当前类别
              </button>
              <button class="shell-clear-all" @click="clearAll">
                <i class="far fa-square"></i>
                清空
              </button>
            </div>
          </div>
        </div>

        <div class="table-container">
          <table class="shell-parts-table">
            <thead>
              <tr>
                <th width="50">选择</th>
                <th width="60">ID</th>
                <th width="120">零件名称</th>
                <th width="300">零件路径</th>
                <th width="100">体积减少</th>
                <th width="80">置信度</th>
                <th width="200">原因</th>
                <th width="100">删除建议</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="part in paginatedParts"
                :key="part.id"
                class="shell-part-row"
                :class="{ 'selected': selectedParts.has(part.id) }"
                :data-part-id="part.id"
              >
                <td>
                  <input
                    type="checkbox"
                    class="shell-checkbox"
                    :data-part-id="part.id"
                    @change="updateSelection"
                    :checked="selectedParts.has(part.id)"
                  >
                </td>
                <td>{{ part.id }}</td>
                <td class="part-name">{{ part.name }}</td>
                <td class="part-path">{{ part.partPath }}</td>
                <td class="volume-reduction">{{ (part.volumeReduction || 0).toFixed(6) }}%</td>
                <td class="confidence-value">{{ formatPercent(part.confidence * 100) }}%</td>
                <td class="reason-text">{{ part.reason }}</td>
                <td>
                  <span class="deletion-recommendation-badge" :class="getDeletionRecommendationClass(part.deletion_recommendation)">
                    {{ getDeletionRecommendationText(part.deletion_recommendation) }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页器 -->
        <div class="pagination-container" v-if="totalPages > 1">
          <div class="pagination">
            <button
              class="page-btn"
              :disabled="currentPage === 1"
              @click="previousPage"
            >
              <i class="fas fa-chevron-left"></i>
              上一页
            </button>

            <div class="page-numbers">
              <template v-for="(page, index) in visiblePageNumbers" :key="`page-${page}-${index}`">
                <button
                  v-if="typeof page === 'number'"
                  class="page-number"
                  :class="{ active: currentPage === page }"
                  @click="goToPage(page)"
                >
                  {{ page }}
                </button>
                <span
                  v-else
                  class="page-ellipsis"
                >
                  {{ page }}
                </span>
              </template>
            </div>

            <button
              class="page-btn"
              :disabled="currentPage === totalPages"
              @click="nextPage"
            >
              下一页
              <i class="fas fa-chevron-right"></i>
            </button>
          </div>

          <div class="pagination-info">
            第 {{ currentPage }} 页 / 共 {{ totalPages }} 页，展示 {{ filteredParts.length }} 个结果
          </div>
        </div>

        <!-- 操作区域 -->
        <div class="shell-operations">
          <div class="selection-status">
            <span id="shell-selected-count">已选择: {{ selectedParts.size }} 个零件</span>
          </div>
          <button
            class="shell-apply-btn shell-delete-btn"
            :disabled="selectedParts.size === 0"
            @click="deleteSelectedComponents"
          >
            <i class="fas fa-trash"></i>
            删除选中
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

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

// 常量配置
const PAGE_SIZE = 10

// Props接收API数据
const props = defineProps({
  analysisData: {
    type: Object,
    default: null
  }
})

// 当前时间格式化
const analysisTime = computed(() => {
  return props.analysisData?.analysis_time || new Date().toLocaleString('zh-CN')
})

// 选中的零件集合
const selectedParts = ref(new Set())

// 已删除的零件集合
const deletedParts = ref(new Set())

// 筛选状态
const currentFilter = ref('all') // all, safe_delete, recommended_delete, must_keep

// 分页状态
const currentPage = ref(1)
const pageSize = ref(PAGE_SIZE)

// 直接使用API数据，遵循"核心需求第一原则"，暴露问题快速失败
const analysisResults = computed(() => {
  if (!props.analysisData) {
    throw new Error('分析数据不能为空')
  }
  return props.analysisData.data
})

// 为零件添加唯一ID和类别标记
const addUniqueIdAndCategory = (parts, category, startId) => {
  return parts.map((part, index) => ({
    ...part,
    id: startId + index,
    originalId: part.id,
    deletion_recommendation: category
  }))
}

// 合并所有零件列表
const allParts = computed(() => {
  if (!analysisResults.value) return []

  let currentId = 1
  const safeDeletions = addUniqueIdAndCategory(analysisResults.value.safeDeletions, 'safe_delete', currentId)
  currentId += safeDeletions.length

  const suggestedDeletions = addUniqueIdAndCategory(analysisResults.value.suggestedDeletions, 'recommended_delete', currentId)
  currentId += suggestedDeletions.length

  const preserveList = addUniqueIdAndCategory(analysisResults.value.preserveList, 'must_keep', currentId)

  return [...safeDeletions, ...suggestedDeletions, ...preserveList]
})

// 筛选后的零件列表
const filteredParts = computed(() => {
  let parts = allParts.value

  // 排除已删除的零件
  parts = parts.filter(part => !deletedParts.value.has(part.id))

  if (currentFilter.value !== 'all') {
    parts = parts.filter(part => part.deletion_recommendation === currentFilter.value)
  }

  return parts
})

// 分页后的零件列表
const paginatedParts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredParts.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredParts.value.length / pageSize.value)
})

// 智能分页显示页码（解决页码过多溢出问题）
const visiblePageNumbers = computed(() => {
  const total = totalPages.value
  const current = currentPage.value
  const maxVisible = 7 // 最多显示7个页码

  if (total <= maxVisible) {
    // 总页数不多，显示所有页码
    return Array.from({ length: total }, (_, i) => i + 1)
  }

  const pages = []

  // 始终显示第1页
  pages.push(1)

  let startPage, endPage

  if (current <= 4) {
    // 当前页在前面
    startPage = 2
    endPage = 5
  } else if (current >= total - 3) {
    // 当前页在后面
    startPage = total - 4
    endPage = total - 1
  } else {
    // 当前页在中间
    startPage = current - 1
    endPage = current + 1
  }

  // 添加省略号
  if (startPage > 2) {
    pages.push('...')
  }

  // 添加中间页码
  for (let i = startPage; i <= endPage; i++) {
    if (i > 1 && i < total) {
      pages.push(i)
    }
  }

  // 添加省略号
  if (endPage < total - 1) {
    pages.push('...')
  }

  // 始终显示最后一页
  if (total > 1) {
    pages.push(total)
  }

  return pages
})


// 格式化百分比
const formatPercent = (value) => {
  return value.toFixed(1)
}

// 获取删除建议样式类
const getDeletionRecommendationClass = (recommendation) => {
  switch (recommendation) {
    case 'safe_delete':
      return 'safe'
    case 'recommended_delete':
      return 'recommended'
    case 'must_keep':
      return 'must-keep'
    default:
      return 'unknown'
  }
}

// 获取删除建议文本
const getDeletionRecommendationText = (recommendation) => {
  switch (recommendation) {
    case 'safe_delete':
      return '安全删除'
    case 'recommended_delete':
      return '建议删除'
    case 'must_keep':
      return '必须保留'
    default:
      return '未知'
  }
}

// 筛选功能
const setFilter = (filter) => {
  currentFilter.value = filter
  currentPage.value = 1
}

// 分页功能
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 全选功能 - 选择当前筛选类别的所有零件
const selectAll = () => {
  selectedParts.value.clear()
  filteredParts.value.forEach(part => {
    selectedParts.value.add(part.id)
  })
}

// 清空选择
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 deleteSelectedComponents = async () => {
  if (selectedParts.value.size === 0) {
    ElNotification.warning({
      title: '选择提示',
      message: '请先选择要删除的组件'
    })
    return
  }

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

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

  selectedPartIds.forEach(partId => {
    const part = allParts.value.find(p => p.id === partId)
    if (part && part.partPath) {
      componentPaths.push(part.partPath)
    }
  })

  if (componentPaths.length === 0) {
    throw new Error('未找到有效的组件路径')
  }

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

<style scoped>
.shell-analysis-result-page {
  padding: var(--spacing-2xl);
  height: 100%;
  overflow-y: auto;
}

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

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

.page-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 分析统计摘要样式 */
.shell-analysis-summary {
  background: var(--color-white-rgb-05);
  border: 1px solid var(--color-white-rgb-1);
  border-radius: 12px;
  padding: 0;
  overflow: hidden;
  box-shadow: var(--color-shadow-btn);
}

.summary-header {
  background: var(--color-gradient-brand-bg);
  padding: 25px 30px;
  border-bottom: 2px solid var(--color-primary-rgb-3);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-header h4 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0;
  color: var(--color-primary);
  font-size: 1.2rem;
  font-weight: 600;
}

.summary-header h4 i {
  color: var(--color-primary);
}

.analysis-time {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--color-text-secondary);
  font-size: 0.95rem;
}

.analysis-time i {
  color: var(--color-primary);
}

.summary-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 30px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: var(--color-primary-rgb);
  border: 1px solid var(--color-border-primary);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  background: var(--color-primary-rgb-3);
  border-color: var(--color-border-active);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px var(--color-primary-rgb);
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  color: var(--color-primary);
  margin-bottom: 8px;
}

.stat-label {
  color: var(--color-text-secondary);
  font-size: 0.9rem;
  font-weight: 500;
}

/* 零件列表样式 */
.shell-parts-list {
  background: var(--color-white-rgb-05);
  border: 1px solid var(--color-white-rgb-1);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: var(--color-shadow-btn);
}

.shell-parts-header {
  background: var(--color-gradient-brand-bg);
  padding: 25px 30px;
  border-bottom: 2px solid var(--color-primary-rgb-3);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.shell-parts-header h4 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0;
  color: var(--color-primary);
  font-size: 1.2rem;
  font-weight: 600;
}

.shell-parts-header h4 i {
  color: var(--color-primary);
}

.shell-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.shell-select-all,
.shell-clear-all {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.shell-select-all {
  background: var(--color-primary-gradient);
  color: white;
  box-shadow: 0 2px 8px var(--color-primary-rgb-3);
}

.shell-select-all:hover {
  background: var(--color-primary-gradient-hover);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px var(--color-primary-rgb-4);
}

.shell-clear-all {
  background: var(--color-primary-rgb);
  color: var(--color-primary);
  border: 1px solid var(--color-primary-rgb-3);
}

.shell-clear-all:hover {
  background: var(--color-primary-rgb-3);
}

/* 表格样式 */
.table-container {
  overflow-x: auto;
}

.shell-parts-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;
}

.shell-parts-table th {
  background: var(--color-complexity-bg-1);
  color: var(--color-text-primary);
  padding: 12px 15px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid var(--color-complexity-border-2);
}

.shell-parts-table td {
  padding: 12px 15px;
  border-bottom: 1px solid var(--color-white-rgb-1);
  vertical-align: middle;
}

.shell-part-row {
  transition: all 0.2s ease;
}

.shell-part-row:hover {
  background: var(--color-complexity-bg-1);
}

.shell-part-row.selected {
  background: var(--color-complexity-bg-1);
  border-left: 3px solid var(--color-complexity);
}

.part-name {
  font-weight: 600;
  color: var(--color-text-primary);
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.part-path {
  color: var(--color-text-secondary);
  font-size: 0.85rem;
  font-family: monospace;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
}

.thickness-value {
  font-weight: 600;
  color: var(--color-primary);
}

.volume-reduction {
  font-weight: 600;
  color: var(--color-success);
}

.confidence-value {
  font-weight: 600;
  color: var(--color-info);
}

.reason-text {
  font-size: 0.85rem;
  color: var(--color-text-secondary);
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.feasibility-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 600;
  text-align: center;
}

.feasibility-badge.high {
  background: var(--color-complexity-low-bg);
  color: var(--color-complexity-low);
  border: 1px solid var(--color-complexity-low);
}

.feasibility-badge.medium {
  background: var(--color-complexity-medium-bg);
  color: var(--color-complexity-medium);
  border: 1px solid var(--color-complexity-medium);
}

.feasibility-badge.low {
  background: var(--color-complexity-high-bg);
  color: var(--color-complexity-high);
  border: 1px solid var(--color-complexity-high);
}

/* 操作区域样式 */
/* 筛选器样式 */
.filter-controls {
  display: flex;
  gap: 8px;
}

.filter-btn {
  padding: 6px 12px;
  border: 1px solid var(--color-border-secondary);
  background: var(--color-bg-secondary);
  color: var(--color-text-secondary);
  border-radius: 4px;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn.active {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.filter-btn:hover:not(.active) {
  background: var(--color-bg-hover);
  border-color: var(--color-border-active);
}

.action-controls {
  display: flex;
  gap: 12px;
}

/* 删除建议徽章样式 */
.deletion-recommendation-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 600;
  text-align: center;
}

.deletion-recommendation-badge.safe {
  background: var(--color-bg-success);
  color: var(--color-success);
  border: 1px solid var(--color-success);
}

.deletion-recommendation-badge.recommended {
  background: var(--color-bg-warning);
  color: var(--color-warning);
  border: 1px solid var(--color-warning);
}

.deletion-recommendation-badge.must-keep {
  background: var(--color-bg-error);
  color: var(--color-error);
  border: 1px solid var(--color-error);
}

.deletion-recommendation-badge.unknown {
  background: var(--color-white-rgb-1);
  color: var(--color-text-tertiary);
  border: 1px solid var(--color-border-primary);
}

/* 分页器样式 */
.pagination-container {
  padding: 20px 30px;
  background: var(--color-bg-secondary);
  border-top: 1px solid var(--color-border-primary);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-btn {
  padding: 8px 16px;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border-primary);
  color: var(--color-text-primary);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.page-btn:hover:not(:disabled) {
  background: var(--color-bg-hover);
  border-color: var(--color-border-active);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.page-number {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border-primary);
  color: var(--color-text-primary);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.page-number.active {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.page-number:hover:not(.active) {
  background: var(--color-bg-hover);
  border-color: var(--color-border-active);
}

.page-ellipsis {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text-secondary);
  font-size: 0.9rem;
  user-select: none;
}

.pagination-info {
  color: var(--color-text-secondary);
  font-size: 0.9rem;
}

.shell-operations {
  padding: 20px 30px;
  background: var(--color-primary-rgb);
  border-top: 1px solid var(--color-primary-rgb-3);
  display: flex;
  justify-content: space-between;
  align-items: center;
}


.selection-status {
  color: var(--color-text-secondary);
  font-weight: 600;
}

.shell-apply-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  background: var(--color-primary-gradient);
  color: white;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 2px 8px var(--color-primary-rgb-3);
}

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

.shell-apply-btn:disabled {
  background: var(--color-white-rgb-1);
  color: var(--color-text-tertiary);
  cursor: not-allowed;
  box-shadow: none;
}

.shell-delete-btn {
  background: var(--color-error);
}

.shell-delete-btn:hover:not(:disabled) {
  background: var(--color-error);
  filter: brightness(0.9);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shell-analysis-result-page {
    padding: 15px;
  }

  .summary-stats {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    padding: 20px;
  }

  .summary-header,
  .shell-parts-header,
  .shell-operations {
    padding: 20px;
  }

  .table-container {
    overflow-x: scroll;
  }

  .shell-parts-table {
    min-width: 800px;
  }

  .shell-controls {
    flex-direction: column;
    gap: 8px;
  }

  .shell-operations {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>