<template>
  <div class="opened-models">
    <div class="section-header">
      <div class="header-content">
        <div class="title-section">
          <h3 class="section-title">已打开模型信息</h3>
          <div class="section-stats">
            <span class="stat-item">
              <i class="fas fa-cube"></i>
              {{ models.length }} 个模型
            </span>
            <span class="stat-item" v-if="connectedCADs > 0">
              <i class="fas fa-link"></i>
              {{ connectedCADs }} 个连接
            </span>
          </div>
        </div>
        <div class="section-actions">
          <BaseButton 
            type="text" 
            icon="fas fa-sync-alt"
            @click="refreshModels"
            :loading="isRefreshing"
          >
            刷新
          </BaseButton>
          <BaseButton 
            type="primary" 
            icon="fas fa-plus"
            size="small"
            @click="$emit('add')"
          >
            添加
          </BaseButton>
        </div>
      </div>
    </div>
    
    <div class="models-table-container" :class="{ 'empty': models.length === 0 }">
      <div class="table-wrapper">
        <table class="models-table">
          <thead>
            <tr>
              <th class="col-title">
                <div class="col-header">
                  <i class="fas fa-cube"></i>
                  <span>标题</span>
                </div>
              </th>
              <th class="col-name">
                <div class="col-header">
                  <i class="fas fa-file"></i>
                  <span>模型名称</span>
                </div>
              </th>
              <th class="col-source">
                <div class="col-header">
                  <i class="fas fa-desktop"></i>
                  <span>来源</span>
                </div>
              </th>
              <th class="col-time">
                <div class="col-header">
                  <i class="fas fa-clock"></i>
                  <span>打开时间</span>
                </div>
              </th>
              <th class="col-actions">
                <div class="col-header">
                  <i class="fas fa-cog"></i>
                  <span>操作</span>
                </div>
              </th>
            </tr>
          </thead>
          <tbody>
            <transition-group name="model-list" tag="tbody">
              <tr 
                v-for="model in models" 
                :key="model.id"
                class="model-row"
                :class="{ 
                  'active': currentModel === model.id,
                  'recent': isRecentModel(model)
                }"
                @click="selectModel(model.id)"
              >
                <td class="col-title">
                  <div class="title-cell">
                    <div class="model-icon" :class="getModelIconClass(model)">
                      <i class="fas fa-cube"></i>
                    </div>
                    <div class="model-info">
                      <div class="model-title">{{ model.title }}</div>
                      <div class="model-path">{{ getModelPath(model) }}</div>
                    </div>
                  </div>
                </td>
                <td class="col-name">
                  <div class="name-cell">
                    <div class="model-filename">{{ model.name }}</div>
                    <div class="model-meta">
                      <span class="model-version">{{ model.version }}</span>
                      <span class="model-size">{{ model.size }}</span>
                    </div>
                  </div>
                </td>
                <td class="col-source">
                  <div class="source-cell">
                    <div class="source-icon" :class="getSourceClass(model.source)">
                      <i :class="getSourceIcon(model.source)"></i>
                    </div>
                    <div class="source-info">
                      <div class="source-name">{{ model.source }}</div>
                      <div class="source-status" :class="getSourceStatusClass(model.source)">
                        <div class="status-dot"></div>
                        <span>已连接</span>
                      </div>
                    </div>
                  </div>
                </td>
                <td class="col-time">
                  <div class="time-cell">
                    <div class="time-relative">{{ formatTime(model.openTime) }}</div>
                    <div class="time-absolute">{{ formatTimeDetail(model.openTime) }}</div>
                  </div>
                </td>
                <td class="col-actions">
                  <div class="actions-cell">
                    <BaseButton 
                      type="text" 
                      icon="fas fa-eye"
                      size="small"
                      @click.stop="viewModel(model)"
                      title="查看模型"
                      class="action-btn view-btn"
                    />
                    <BaseButton 
                      type="text" 
                      icon="fas fa-download"
                      size="small"
                      @click.stop="exportModel(model)"
                      title="导出模型"
                      class="action-btn export-btn"
                    />
                    <BaseButton 
                      type="text" 
                      icon="fas fa-times"
                      size="small"
                      @click.stop="closeModel(model)"
                      title="关闭模型"
                      class="action-btn close-btn"
                    />
                  </div>
                </td>
              </tr>
            </transition-group>
          </tbody>
        </table>
      </div>
      
      <!-- 空状态 -->
      <transition name="fade">
        <div v-if="models.length === 0" class="empty-state">
          <div class="empty-icon">
            <i class="fas fa-inbox"></i>
          </div>
          <h4 class="empty-title">暂无打开的模型</h4>
          <p class="empty-desc">请先连接CAD软件或打开模型文件</p>
          <BaseButton 
            type="primary" 
            icon="fas fa-plus"
            @click="$emit('add')"
            class="empty-action"
          >
            打开模型
          </BaseButton>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import BaseButton from '@/components/ui/BaseButton.vue'
import { useCADStore } from '@/stores/cad'

// 时间常量配置
const TIME_CONSTANTS = {
  // 基础时间单位
  MILLISECONDS_PER_SECOND: 1000,
  SECONDS_PER_MINUTE: 60,
  MINUTES_PER_HOUR: 60,
  HOURS_PER_DAY: 24
}

// 计算常量 - 使用基础常量计算避免魔术数字
const DERIVED_TIME_CONSTANTS = {
  MILLISECONDS_PER_MINUTE: TIME_CONSTANTS.MILLISECONDS_PER_SECOND * TIME_CONSTANTS.SECONDS_PER_MINUTE,
  MILLISECONDS_PER_HOUR: TIME_CONSTANTS.MILLISECONDS_PER_SECOND * TIME_CONSTANTS.SECONDS_PER_MINUTE * TIME_CONSTANTS.MINUTES_PER_HOUR,
  MILLISECONDS_PER_DAY: TIME_CONSTANTS.MILLISECONDS_PER_SECOND * TIME_CONSTANTS.SECONDS_PER_MINUTE * TIME_CONSTANTS.MINUTES_PER_HOUR * TIME_CONSTANTS.HOURS_PER_DAY,
  // 业务常量
  RECENT_MODEL_THRESHOLD: TIME_CONSTANTS.MILLISECONDS_PER_SECOND * TIME_CONSTANTS.SECONDS_PER_MINUTE * TIME_CONSTANTS.MINUTES_PER_HOUR // 1小时内算最近
}

const emit = defineEmits(['select', 'view', 'export', 'close', 'refresh', 'add'])

const cadStore = useCADStore()
const currentModel = ref('')
const isRefreshing = ref(false)

// 计算属性
const models = computed(() => cadStore.openedModels)
const connectedCADs = computed(() => {
  return cadStore.cadConnections.filter(cad => cad.connected).length
})

const selectModel = (modelId) => {
  currentModel.value = modelId
  cadStore.selectModel(modelId)
  emit('select', modelId)
}

const viewModel = (model) => {
  emit('view', model)
}

const exportModel = async (model) => {
  const result = await cadStore.exportModel(model.id)
  if (result.success) {
    emit('export', model)
  } else {
    // 处理导出失败
  }
}

const closeModel = (model) => {
  const result = cadStore.closeModel(model.id)
  if (result.success) {
    emit('close', model)
    
    // 如果关闭的是当前选中的模型，清除选择
    if (currentModel.value === model.id) {
      currentModel.value = ''
    }
  }
}

const refreshModels = async () => {
  isRefreshing.value = true
  const result = await cadStore.refreshModels()
  if (result.success) {
    emit('refresh')
  }
  isRefreshing.value = false
}

const isRecentModel = (model) => {
  const now = new Date()
  const diff = now - model.openTime
  return diff < DERIVED_TIME_CONSTANTS.RECENT_MODEL_THRESHOLD
}

const getModelIconClass = (model) => {
  return {
    'assembly': model.name.includes('.asm'),
    'part': model.name.includes('.prt'),
    'drawing': model.name.includes('.drw')
  }
}

const getModelPath = (model) => {
  return model.path ? model.path.split('/').pop() : '本地文件'
}

const getSourceClass = (source) => {
  return source.toLowerCase().replace(/\s+/g, '-')
}

const getSourceStatusClass = (source) => {
  const cad = cadStore.getCADConnection(source)
  return cad && cad.connected ? 'connected' : 'disconnected'
}

const getSourceIcon = (source) => {
  const iconMap = {
    'SolidWorks': 'fas fa-cube',
    'AutoCAD': 'fas fa-drafting-compass',
    'Creo': 'fas fa-cogs',
    'CATIA': 'fas fa-industry',
    'NX': 'fas fa-gears',
    'Inventor': 'fas fa-tools'
  }
  return iconMap[source] || 'fas fa-file'
}

const formatTime = (time) => {
  const now = new Date()
  const diff = now - time
  const minutes = Math.floor(diff / DERIVED_TIME_CONSTANTS.MILLISECONDS_PER_MINUTE)
  const hours = Math.floor(diff / DERIVED_TIME_CONSTANTS.MILLISECONDS_PER_HOUR)
  const days = Math.floor(diff / DERIVED_TIME_CONSTANTS.MILLISECONDS_PER_DAY)
  
  if (minutes < TIME_CONSTANTS.MINUTES_PER_HOUR) {
    return `${minutes}分钟前`
  } else if (hours < TIME_CONSTANTS.HOURS_PER_DAY) {
    return `${hours}小时前`
  } else {
    return `${days}天前`
  }
}

const formatTimeDetail = (time) => {
  return time.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.opened-models {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

.section-header {
  margin-bottom: var(--spacing-md);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-lg);
  background: var(--color-white-rgb-05);
  border: 1px solid var(--color-white-rgb-1);
  border-radius: var(--size-border-radius-card);
  backdrop-filter: blur(10px);
}

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

.section-title {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  margin: 0;
  letter-spacing: 0.5px;
}

.section-stats {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  font-weight: var(--font-weight-medium);
}

.stat-item i {
  color: var(--color-primary);
  font-size: var(--font-size-sm);
}

.section-actions {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.models-table-container {
  background: var(--color-bg-card);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--size-border-radius-card);
  overflow: hidden;
  box-shadow: var(--color-shadow-card);
  transition: all var(--transition-duration) var(--transition-timing);
}

.models-table-container:hover {
  box-shadow: 0 25px 50px var(--color-black-rgb-35);
}

.table-wrapper {
  overflow-x: auto;
}

.models-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 16px;
  background: var(--color-white-rgb-05);
}

.models-table th {
  background: var(--color-white-rgb-05);
  border-bottom: 2px solid var(--color-border-primary);
  padding: var(--spacing-xl) var(--spacing-lg);
  text-align: left;
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-secondary);
  white-space: nowrap;
  position: relative;
}

.models-table th:first-child {
  padding-left: var(--spacing-xl);
}

.models-table th:last-child {
  padding-right: var(--spacing-xl);
}

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

.col-header i {
  font-size: var(--font-size-sm);
  color: var(--color-text-tertiary);
}

.models-table td {
  padding: var(--spacing-xl) var(--spacing-lg);
  border-bottom: 1px solid var(--color-border-primary);
  vertical-align: middle;
  transition: all var(--transition-duration) var(--transition-timing);
}

.models-table td:first-child {
  padding-left: var(--spacing-xl);
}

.models-table td:last-child {
  padding-right: var(--spacing-xl);
}

.model-row {
  cursor: pointer;
  transition: all var(--transition-duration) var(--transition-timing);
  position: relative;
}

.model-row::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 0;
  background: var(--color-primary-gradient);
  transition: width var(--transition-duration) var(--transition-timing);
  opacity: 0.1;
}

.model-row:hover {
  background: var(--color-white-rgb-05);
  transform: translateX(4px);
}

.model-row:hover::before {
  width: 4px;
}

.model-row.active {
  background: var(--color-primary-rgb);
}

.model-row.active::before {
  width: 4px;
  opacity: 0.3;
}

.model-row.recent {
  background: var(--color-warning-rgb-05);
}

.model-row:last-child td {
  border-bottom: none;
}

/* 列样式 */
.col-title {
  width: 35%;
}

.col-name {
  width: 30%;
}

.col-source {
  width: 20%;
}

.col-time {
  width: 12%;
}

.col-actions {
  width: 3%;
}

/* 单元格内容样式 */
.title-cell {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.model-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, var(--color-primary-rgb) 0%, var(--color-primary-light-rgb-05) 100%);
  border-radius: var(--size-border-radius);
  color: var(--color-primary);
  font-size: 20px;
  transition: all var(--transition-duration) var(--transition-timing);
}

.model-icon.assembly {
  background: var(--color-gradient-success);
  color: var(--color-success);
}

.model-icon.part {
  background: var(--color-gradient-info);
  color: var(--color-info);
}

.model-icon.drawing {
  background: linear-gradient(135deg, var(--color-warning-rgb-1) 0%, var(--color-warning-rgb-05) 100%);
  color: var(--color-warning);
}

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

.model-title {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  line-height: 1.3;
}

.model-path {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
  line-height: 1.2;
}

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

.model-filename {
  font-size: var(--font-size-sm);
  color: var(--color-text-primary);
  font-weight: var(--font-weight-medium);
  font-family: 'Courier New', monospace;
}

.model-meta {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
}

.model-version {
  background: var(--color-white-rgb-1);
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: var(--font-weight-medium);
}

.model-size {
  font-weight: var(--font-weight-medium);
}

.source-cell {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.source-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: var(--color-white-rgb-1);
  border-radius: var(--size-border-radius);
  color: var(--color-text-secondary);
  font-size: var(--font-size-base);
  transition: all var(--transition-duration) var(--transition-timing);
}

.source-icon.solidworks {
  background: var(--color-orange-rgb-1);
  color: var(--color-text-orange);
}

.source-icon.autocad {
  background: var(--color-red-rgb-1);
  color: var(--color-text-red);
}

.source-icon.creo {
  background: var(--color-blue-rgb-1);
  color: var(--color-text-blue);
}

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

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

.source-status {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-xs);
}

.source-status.connected {
  color: var(--color-success);
}

.source-status.disconnected {
  color: var(--color-error);
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
}

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

.time-relative {
  font-size: var(--font-size-sm);
  color: var(--color-text-primary);
  font-weight: var(--font-weight-medium);
}

.time-absolute {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
  font-family: monospace;
}

.actions-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}

.action-btn {
  transition: all var(--transition-duration) var(--transition-timing);
}

.action-btn.view-btn:hover {
  color: var(--color-info);
  background: var(--color-info-rgb-1);
}

.action-btn.export-btn:hover {
  color: var(--color-success);
  background: var(--color-success-rgb-1);
}

.action-btn.close-btn:hover {
  color: var(--color-error);
  background: var(--color-error-rgb-1);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-4xl);
  color: var(--color-text-tertiary);
  text-align: center;
  background: var(--color-white-rgb-05);
}

.empty-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, var(--color-white-rgb-05) 0%, var(--color-white-rgb-05) 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: var(--spacing-xl);
}

.empty-icon i {
  font-size: 32px;
  color: var(--color-text-tertiary);
  opacity: 0.6;
}

.empty-title {
  font-size: var(--font-size-xl);
  color: var(--color-text-secondary);
  margin: 0 0 var(--spacing-md) 0;
  font-weight: var(--font-weight-semibold);
}

.empty-desc {
  font-size: var(--font-size-base);
  color: var(--color-text-tertiary);
  margin: 0 0 var(--spacing-xl) 0;
  max-width: 300px;
  line-height: 1.5;
}

.empty-action {
  min-width: 120px;
}

/* 列表动画 */
.model-list-enter-active,
.model-list-leave-active {
  transition: all 0.3s ease;
}

.model-list-enter-from {
  opacity: 0;
  transform: translateY(-20px);
}

.model-list-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.model-list-move {
  transition: transform 0.3s ease;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity var(--transition-duration) var(--transition-timing);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .models-table {
    font-size: 14px;
  }
  
  .models-table th,
  .models-table td {
    padding: var(--spacing-lg) var(--spacing-md);
  }
  
  .model-icon {
    width: 44px;
    height: 44px;
    font-size: 18px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: var(--spacing-lg);
    text-align: center;
  }
  
  .section-stats {
    justify-content: center;
  }
  
  .models-table {
    font-size: 13px;
  }
  
  .models-table th,
  .models-table td {
    padding: var(--spacing-md) var(--spacing-sm);
  }
  
  .models-table th:first-child,
  .models-table td:first-child {
    padding-left: var(--spacing-md);
  }
  
  .models-table th:last-child,
  .models-table td:last-child {
    padding-right: var(--spacing-md);
  }
  
  .col-actions {
    width: auto;
  }
  
  .time-absolute {
    display: none;
  }
  
  .empty-state {
    padding: var(--spacing-3xl);
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: var(--spacing-lg);
  }
  
  .models-table {
    font-size: 12px;
  }
  
  .models-table th,
  .models-table td {
    padding: var(--spacing-md) var(--spacing-xs);
  }
  
  .model-icon {
    width: 40px;
    height: 40px;
    font-size: 16px;
  }
  
  .model-title {
    font-size: 13px;
  }
  
  .model-filename {
    font-size: 11px;
  }
  
  .empty-state {
    padding: var(--spacing-2xl);
  }
}
</style>
}