<template>
  <div class="editor-view">
    <!-- 未加载数据时显示上传界面 -->
    <template v-if="!editorStore.hasData">
      <div class="upload-container">
        <div class="upload-section">
          <FileUploader />
        </div>
        <div class="template-section">
          <h3>模板管理</h3>
          <TemplatePanel @load-file="handleLoadFile" />
        </div>
      </div>
    </template>
    
    <!-- 已加载数据时显示编辑界面 -->
    <template v-else>
      <!-- 主内容区 -->
      <div class="main-content">
        <!-- 左侧画布 -->
        <div class="canvas-area">
          <TableCanvas />
        </div>
        
        <!-- 右侧面板 -->
        <div class="side-panel">
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane label="工具" name="tools">
              <ToolPanel />
              <StructurePanel />
              <SavePanel />
            </el-tab-pane>
            <el-tab-pane label="模板" name="templates">
              <TemplatePanel @load-file="handleLoadFile" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      
      <!-- 顶部工具栏 -->
      <div class="top-bar">
        <el-button @click="handleReset" type="info" plain>
          <el-icon><Refresh /></el-icon>
          重新选择文件
        </el-button>
        <el-button @click="handleReanalyze" type="warning" plain :loading="isReanalyzing">
          <el-icon><Aim /></el-icon>
          重新分析
        </el-button>
      </div>
      
      <!-- 底部批量导航栏 -->
      <div v-if="templateStore.hasFilePairs" class="batch-nav-bar">
        <div class="nav-info">
          <el-tag type="info" size="small">
            {{ templateStore.currentPairIndex + 1 }} / {{ templateStore.filePairs.length }}
          </el-tag>
          <span class="file-name">{{ templateStore.currentFilePair?.image_name }}</span>
          <el-tag 
            :type="templateStore.currentFilePair?.has_structure ? 'success' : 'warning'" 
            size="small"
          >
            {{ templateStore.currentFilePair?.has_structure ? '已标注' : '待处理' }}
          </el-tag>
        </div>
        
        <div class="nav-actions">
          <!-- 模板选择 -->
          <el-select 
            v-model="templateStore.selectedTemplateName" 
            placeholder="选择模板"
            size="small"
            clearable
            style="width: 150px"
          >
            <el-option 
              v-for="tpl in templateStore.templates" 
              :key="tpl.name" 
              :label="tpl.name" 
              :value="tpl.name"
            />
          </el-select>
          
          <el-button-group>
            <el-button 
              size="small" 
              @click="goToPrevFile" 
              :disabled="!templateStore.hasPrevPair"
              title="上一个 (Ctrl+←)"
            >
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <el-button 
              size="small" 
              @click="goToNextFile" 
              :disabled="!templateStore.hasNextPair"
              title="下一个 (Ctrl+→)"
            >
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </el-button-group>
          
          <el-button 
            type="primary" 
            size="small"
            @click="applySelectedTemplate"
            :disabled="!templateStore.selectedTemplateName"
            title="应用模板 (Ctrl+T)"
          >
            <el-icon><Check /></el-icon>
            应用模板
          </el-button>
          
          <el-button 
            type="success" 
            size="small"
            @click="saveAndNext"
            :disabled="!templateStore.hasNextPair"
            title="保存并继续下一个"
          >
            <el-icon><Right /></el-icon>
            保存并继续
          </el-button>
        </div>
        
        <div class="nav-shortcuts">
          <span class="shortcut-hint">快捷键: Ctrl+← 上一个 | Ctrl+→ 下一个 | Ctrl+T 应用模板</span>
        </div>
      </div>
    </template>
    
    <!-- 全局 loading -->
    <el-loading 
      v-model:full-screen="isLoading"
      text="加载中..."
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Aim, ArrowLeft, ArrowRight, Check, Right } from '@element-plus/icons-vue'
import { useEditorStore, useHistoryStore, useTemplateStore } from '@/stores'
import { useKeyboardShortcuts } from '@/composables'
import { TableCanvas, FileUploader, ToolPanel, StructurePanel, SavePanel, TemplatePanel } from '@/components'
import { reanalyzeStructure, loadByPath, saveResult } from '@/api'
import * as templateApi from '@/api/template'

const editorStore = useEditorStore()
const historyStore = useHistoryStore()
const templateStore = useTemplateStore()
const { setup: setupKeyboardShortcuts, cleanup: cleanupKeyboardShortcuts, registerCallbacks } = useKeyboardShortcuts()

const isLoading = computed(() => editorStore.isLoading)
const isReanalyzing = ref(false)
const activeTab = ref('tools')

onMounted(() => {
  setupKeyboardShortcuts()
  // 注册键盘快捷键回调
  registerCallbacks({
    onLoadFile: handleLoadFile,
    onApplyTemplate: applySelectedTemplate
  })
})

onUnmounted(() => {
  cleanupKeyboardShortcuts()
})

// 从文件路径加载数据
async function handleLoadFile(payload: { imagePath: string; jsonPath: string }) {
  try {
    editorStore.setLoading(true)
    
    // 获取后缀配置
    const structureSuffix = templateStore.activeDataSource?.output?.structure_suffix?.replace('.json', '') || '_structure'
    const imageSuffix = templateStore.activeDataSource?.output?.image_suffix?.replace('.png', '') || ''
    
    const response = await loadByPath(
      payload.imagePath, 
      payload.jsonPath,
      templateStore.scanConfig.outputDir || './output',
      structureSuffix,
      imageSuffix
    )
    
    if (response.success) {
      editorStore.loadData(
        response.image_base64,
        response.image_size,
        response.structure,
        response.scale_factor,
        response.ocr_data || null,
        response.suggested_filename || undefined
      )
      historyStore.clear()
      ElMessage.success('加载成功')
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error: any) {
    console.error('加载文件失败:', error)
    ElMessage.error(`加载失败: ${error.message}`)
  } finally {
    editorStore.setLoading(false)
  }
}

async function handleReset() {
  try {
    await ElMessageBox.confirm(
      '确定要重新选择文件吗？当前编辑内容将丢失。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    editorStore.reset()
    historyStore.clear()
  } catch {
    // 用户取消
  }
}

async function handleReanalyze() {
  if (!editorStore.imageSrc || !editorStore.ocrData) {
    ElMessage.warning('OCR 数据不可用，无法重新分析')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '确定要重新分析吗？当前编辑内容将被覆盖。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    isReanalyzing.value = true
    
    const response = await reanalyzeStructure({
      ocr_data: editorStore.ocrData,
      image_size: editorStore.imageSize,
      options: {
        method: 'cell_index'  // 使用默认分析方法
      }
    })
    
    if (response.success && response.structure) {
      editorStore.updateStructure(response.structure)
      historyStore.clear()  // 清空历史
      ElMessage.success('重新分析完成')
    } else {
      ElMessage.error(response.message || '分析失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重新分析失败:', error)
      ElMessage.error('重新分析失败')
    }
  } finally {
    isReanalyzing.value = false
  }
}

// === 批量模式功能 ===

// 跳转到上一个文件
function goToPrevFile() {
  if (templateStore.hasPrevPair) {
    templateStore.prevPair()
    const pair = templateStore.currentFilePair
    if (pair) {
      handleLoadFile({ imagePath: pair.image_path, jsonPath: pair.json_path })
    }
  }
}

// 跳转到下一个文件
function goToNextFile() {
  if (templateStore.hasNextPair) {
    templateStore.nextPair()
    const pair = templateStore.currentFilePair
    if (pair) {
      handleLoadFile({ imagePath: pair.image_path, jsonPath: pair.json_path })
    }
  }
}

// 应用选中的模板
async function applySelectedTemplate() {
  const templateName = templateStore.selectedTemplateName
  if (!templateName || !editorStore.hasData) {
    return
  }
  
  try {
    const structure = await templateApi.previewApplyTemplate(
      templateName,
      editorStore.imageSize,
      editorStore.tableBbox,
      'relative'
    )
    editorStore.updateStructure(structure)
    ElMessage.success(`模板 "${templateName}" 已应用`)
  } catch (error: any) {
    ElMessage.error(`应用模板失败: ${error.message}`)
  }
}

// 保存当前文件并继续下一个
async function saveAndNext() {
  if (!editorStore.hasData || !editorStore.imageSrc) {
    ElMessage.warning('没有可保存的数据')
    return
  }
  
  try {
    // 保存当前文件
    const filename = editorStore.suggestedFilename || 'table'
    // 从 base64 图片中提取数据
    const imageBase64 = editorStore.imageSrc.includes(',') 
      ? editorStore.imageSrc.split(',')[1] 
      : editorStore.imageSrc
    
    const response = await saveResult({
      filename,
      structure: editorStore.structure,
      image_base64: imageBase64,
      output_dir: templateStore.scanConfig.outputDir || './output'
    })
    
    if (response.success) {
      ElMessage.success('保存成功')
      
      // 更新当前文件对的状态为已标注
      templateStore.updatePairStatus(
        templateStore.currentPairIndex,
        true,
        response.structure_path || null
      )
      
      // 跳转到下一个文件
      if (templateStore.hasNextPair) {
        goToNextFile()
        
        // 如果设置了自动应用模板
        if (templateStore.autoApplyTemplate && templateStore.selectedTemplateName) {
          // 等待文件加载完成后应用模板
          setTimeout(() => {
            applySelectedTemplate()
          }, 500)
        }
      } else {
        ElMessage.info('已完成所有文件的标注')
      }
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: any) {
    ElMessage.error(`保存失败: ${error.message}`)
  }
}
</script>

<style scoped>
.editor-view {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
}

.upload-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.upload-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e4e7ed;
}

.template-section {
  width: 400px;
  padding: 20px;
  overflow-y: auto;
  background: #fafafa;
}

.template-section h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.canvas-area {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.side-panel {
  width: 320px;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  background: #fff;
  overflow-y: auto;
}

.side-panel :deep(.el-tabs__content) {
  padding: 0;
}

.top-bar {
  position: absolute;
  top: 12px;
  right: 332px;
  display: flex;
  gap: 8px;
  z-index: 100;
}

.batch-nav-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 320px;
  background: #fff;
  border-top: 1px solid #e4e7ed;
  padding: 8px 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  z-index: 100;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

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

.nav-info .file-name {
  flex: 1;
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

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

.nav-shortcuts {
  border-top: 1px dashed #e4e7ed;
  padding-top: 6px;
}

.shortcut-hint {
  font-size: 11px;
  color: #909399;
}
</style>
