<template>
  <div class="side-panel">
    <!-- CAD软件选择器 -->
    <div class="software-selector">
      <h3 class="selector-title">
        <i class="fas fa-desktop"></i>
        选择CAD软件
      </h3>
      <CadSoftwareGrid
        :current-software="currentSoftware"
        :connection-status="connectionStatus"
        @software-selected="selectSoftware"
        @test-connection="testConnection"
      />
      <div class="selected-software">
        <span class="selected-label">当前选择:</span>
        <span class="selected-name">{{ currentSoftware || '请先选择软件' }}</span>
      </div>
    </div>

    <!-- 模型管理面板 -->
    <div class="panel-section">
      <h3 class="section-title">
        <i class="fas fa-folder-open"></i>
        模型管理
      </h3>
      <div class="section-content">
        <!-- 模型选择选项 -->
        <div class="project-selection">
          <div class="selection-title">
            <i class="fas fa-project-diagram"></i>
            <span>选择模型来源</span>
          </div>
          <div class="selection-options">
            <label class="option-item">
              <input type="radio" name="project-source" value="open-file" checked>
              <div class="option-content">
                <i class="fas fa-file-upload"></i>
                <span>打开模型文件</span>
                <small>从本地文件系统选择模型文件</small>
              </div>
            </label>
            <label class="option-item">
              <input type="radio" name="project-source" value="current-project">
              <div class="option-content">
                <i class="fas fa-eye"></i>
                <span>查看当前模型</span>
                <small>获取已打开的模型</small>
              </div>
            </label>
          </div>
          <div class="project-actions">
            <button class="confirm-btn" @click="handleOpenModel">
              <i class="fas fa-folder-open"></i>
              打开模型
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useCADStore } from '@/stores/cad'
import CadSoftwareGrid from '@/components/ui/CadSoftwareGrid.vue'
import creoApi from '@/services/creoApi'
import revitApi from '@/services/revitApi'
import pdmsApi from '@/services/pdmsApi'
import { ElNotification, ElMessageBox } from 'element-plus'
import { getNotificationConfig } from '@/config/cad'

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

// 定义事件
const emit = defineEmits(['show-model-viewer'])

const cadStore = useCADStore()

// 当前选择的软件
const currentSoftware = ref('')

// 获取连接状态从CAD store
const connectionStatus = computed(() => {
  const statusMap = {}
  cadStore.cadConnections.forEach(cad => {
    const key = cad.name.toLowerCase().replace(/\s+/g, '')
    statusMap[key] = cad.connected ? 'connected' : 'disconnected'
  })
  return statusMap
})

// 选择软件
const selectSoftware = (software) => {
  currentSoftware.value = software
}

// 预留的获取连接状态方法
// const getConnectionStatus = (software) => {
//   return connectionStatus.value[software] || 'disconnected'
// }

// 测试连接
const testConnection = async (software) => {
  // 设置连接中状态
  cadStore.setCADConnecting(software, true)

  // 目前只支持Creo
  if (software === 'creo' || software === 'Creo') {
    const result = await creoApi.testConnection()
    cadStore.setCADConnection(software, result.success)
  } else if (software === 'revit') {
    const result = await revitApi.testConnection()
    cadStore.setCADConnection(software, result.success)
  } else if (software === 'pdms') {
    const result = await pdmsApi.testConnection()
    cadStore.setCADConnection(software, result.success)
  } else {
    // 其他软件暂不支持
    cadStore.setCADConnection(software, false)
  }

  cadStore.setCADConnecting(software, false)
}

// 处理打开模型
const handleOpenModel = async () => {
  const connectedCAD = cadStore.currentCAD
  if (!connectedCAD) {
    ElNotification({
      title: '操作提示',
      message: '请先连接CAD软件',
      type: 'warning',
      position: 'top-right',
      duration: notificationConfig.ERROR_DURATION
    })
    return
  }

  // 获取选中的模型来源选项
  const selectedOption = document.querySelector('input[name="project-source"]:checked')?.value

  if (selectedOption === 'current-project') {
    // 查看当前模型
    if (connectedCAD.id === 'creo') {
      const result = await creoApi.getCurrentModel()
      if (result.success) {
        cadStore.setCurrentProjectName(result.data.data.fileName)
        emit('show-model-viewer', result.data)
      }
    } else if (connectedCAD.id === 'revit') {
      const result = await revitApi.getCurrentModel()
      if (result.success) {
        cadStore.setCurrentProjectName(result.data.data.project.name)
        emit('show-model-viewer', result.data.data)
      }
    } else if (connectedCAD.id === 'pdms') {
      const result = await pdmsApi.getCurrentModel()
      if (result.success) {
        cadStore.setCurrentProjectName(result.data.data.ProjectInfo.ProjectName)
        emit('show-model-viewer', result.data.data)
      }
    }
  } else {
    // 打开文件 - 使用ElementPlus输入框
    try {
      const { value: filePath } = await ElMessageBox.prompt('请输入模型文件路径', '打开模型文件', {
        confirmButtonText: '打开',
        cancelButtonText: '取消',
        inputPlaceholder: '例如: Z:\\工具\\Revit2017(64bit)\\model.asm'
      })

      if (filePath && connectedCAD.id === 'creo') {
        // 处理文件路径格式，支持中文字符和特殊字符
        const processedFilePath = filePath.trim()

        // 第一步：打开模型文件
        const openResult = await creoApi.openModelFile(processedFilePath)
        if (openResult.success) {
          // 第二步：获取当前模型详细信息
          const modelResult = await creoApi.getCurrentModel()
          if (modelResult.success) {
            cadStore.setCurrentProjectName(modelResult.data.data.fileName)
            emit('show-model-viewer', modelResult.data)
          }
        }
      }
    } catch (error) {
      if (error === 'cancel') {
        // 用户取消操作，正常流程
        return
      }
      throw new Error(`打开文件失败: ${error.message}`)
    }
  }
}
</script>

<style scoped>
.side-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--color-bg-primary);
  color: var(--color-text-primary);
  overflow-y: auto;
  padding: var(--spacing-xl);
  gap: var(--spacing-2xl);
}

/* CAD软件选择器 */
.software-selector {
  background: var(--color-bg-card);
  border-radius: var(--size-border-radius);
  padding: var(--spacing-xl);
  border: var(--border-width-thin) solid var(--color-border-primary);
}

.selector-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin: 0 0 var(--spacing-lg) 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--color-text-primary);
}

.selector-title i {
  color: var(--color-primary);
}


.selected-software {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background: var(--color-white-rgb-05);
  border-radius: var(--size-border-radius-button);
  font-size: var(--font-size-base);
}

.selected-label {
  color: var(--color-text-secondary);
  font-weight: 500;
}

.selected-name {
  color: var(--color-text-primary);
  font-weight: 600;
}

/* 模型管理面板 */
.panel-section {
  background: var(--color-bg-card);
  border-radius: var(--size-border-radius);
  padding: var(--spacing-xl);
  border: var(--border-width-thin) solid var(--color-border-primary);
}

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

.section-title i {
  color: var(--color-primary);
}

.selection-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-base);
  font-weight: 500;
  color: var(--color-text-primary);
}

.selection-title i {
  color: var(--color-primary);
}

.selection-options {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-lg);
}

.option-item {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  background: var(--color-white-rgb-05);
  border-radius: var(--size-border-radius-button);
  cursor: pointer;
  transition: var(--transition-all);
}

.option-item:hover {
  background: var(--color-white-rgb-05);
}

.option-item input[type="radio"] {
  margin-top: var(--size-2);
}

.option-content {
  flex: 1;
}

.option-content i {
  color: var(--color-primary);
  margin-right: var(--spacing-sm);
}

.option-content span {
  display: block;
  color: var(--color-text-primary);
  font-weight: 500;
  margin-bottom: var(--spacing-xs);
}

.option-content small {
  color: var(--color-text-secondary);
  font-size: var(--font-size-xs);
}

.project-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.confirm-btn {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-grid-gap) var(--spacing-lg);
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: var(--size-border-radius-button);
  font-size: var(--font-size-base);
  font-weight: 500;
  cursor: pointer;
  transition: var(--transition-all);
}

.confirm-btn:hover {
  background: var(--color-primary-dark);
  transform: translateY(-1px);
}

.confirm-btn i {
  font-size: var(--font-size-base);
}

/* 滚动条样式 */
.side-panel::-webkit-scrollbar {
  width: var(--size-6);
}

.side-panel::-webkit-scrollbar-track {
  background: transparent;
}

.side-panel::-webkit-scrollbar-thumb {
  background: var(--color-white-rgb-2);
  border-radius: var(--size-3);
}

.side-panel::-webkit-scrollbar-thumb:hover {
  background: var(--color-white-rgb-3);
}
</style>