<template>
  <div class="save-panel">
    <!-- 面板头部 - 始终可见 -->
    <div class="panel-header" @click="expandSettings = !expandSettings">
      <div class="header-left">
        <div class="panel-title">保存设置</div>
        <div class="path-summary">
          <span class="path-label">输出路径：</span>
          <span class="path-value">{{ outputDir }}</span>
          <el-icon 
            class="expand-icon" 
            :class="{ expanded: expandSettings }"
          >
            <ArrowDown />
          </el-icon>
        </div>
      </div>
      <div class="header-right">
        <el-tag type="info" size="small">{{ baseFilename }}</el-tag>
      </div>
    </div>

    <!-- 可配置的选项（可折叠） -->
    <el-collapse-transition>
      <div v-show="expandSettings" class="settings-panel">
        <!-- 路径详情卡片 -->
        <div class="path-detail-card">
          <div class="card-title">输出配置</div>
          <div class="detail-grid">
            <div class="detail-item">
              <div class="detail-label">📁 输出目录</div>
              <div class="detail-value path-copy">
                {{ outputDir }}
              </div>
            </div>
            <div class="detail-item">
              <div class="detail-label">📄 基础文件名</div>
              <div class="detail-value">
                {{ baseFilename }}
              </div>
            </div>
          </div>
          <div class="config-hint">
            ℹ️ 这些设置由数据源配置指定，无法修改。修改请返回数据源设置。
          </div>
        </div>

        <!-- 保存选项卡片 -->
        <div class="options-card">
          <div class="card-title">文件处理</div>
          <el-form label-position="top" size="small" class="options-form">
            <!-- 结构文件后缀 -->
            <el-form-item label="结构文件名">
              <div class="filename-preview">
                <span class="filename">{{ baseFilename }}<span class="suffix">{{ structureSuffix }}</span>.json</span>
              </div>
              <div class="config-hint" style="margin-top: 8px;">
                ℹ️ 后缀由数据源配置指定：{{ structureSuffix }}.json
              </div>
            </el-form-item>

            <!-- 覆盖策略 -->
            <el-form-item label="文件存在时">
              <el-radio-group v-model="overwriteMode" size="small">
                <el-radio-button label="overwrite">
                  <el-icon><DocumentCopy /></el-icon>
                  <span style="margin-left: 4px;">覆盖</span>
                </el-radio-button>
                <el-radio-button label="skip">
                  <el-icon><CircleCloseFilled /></el-icon>
                  <span style="margin-left: 4px;">跳过</span>
                </el-radio-button>
                <el-radio-button label="new">
                  <el-icon><Plus /></el-icon>
                  <span style="margin-left: 4px;">新文件</span>
                </el-radio-button>
              </el-radio-group>
              <div class="strategy-hint">
                <span v-if="overwriteMode === 'overwrite'">覆盖现有文件</span>
                <span v-else-if="overwriteMode === 'skip'">跳过保存，保留现有文件</span>
                <span v-else>创建新文件（添加时间戳）</span>
              </div>
            </el-form-item>

            <!-- 图片保存 -->
            <el-form-item label="图片处理">
              <div class="image-option">
                <el-switch v-model="saveImage" size="large" />
                <span class="option-text">
                  <span v-if="saveImage">保存图片 ({{ baseFilename }}<span class="suffix">{{ imageSuffix }}</span>.png)</span>
                  <span v-else>不保存图片</span>
                </span>
              </div>
            </el-form-item>

            <!-- 图片后缀（仅当保存图片时显示） -->
            <el-form-item v-if="saveImage" label="图片文件名">
              <div class="filename-preview">
                <span class="filename">{{ baseFilename }}<span class="suffix">{{ imageSuffix }}</span>.png</span>
              </div>
              <div class="config-hint" style="margin-top: 8px;">
                ℹ️ 后缀由数据源配置指定：{{ imageSuffix || '(空)' }}.png
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 保存按钮 -->
        <el-button 
          type="primary" 
          @click="handleSave"
          :loading="isSaving"
          :disabled="!canSave"
          size="default"
          class="save-button"
        >
          <el-icon><Download /></el-icon>
          保存结果
        </el-button>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, ArrowDown, DocumentCopy, CircleCloseFilled, Plus } from '@element-plus/icons-vue'
import { saveResult } from '@/api'
import { useEditorStore, useTemplateStore } from '@/stores'

const editorStore = useEditorStore()
const templateStore = useTemplateStore()

// UI 状态
const expandSettings = ref(false)
const isSaving = ref(false)

// 只读：来自模板的输出目录
const outputDir = computed(() => {
  return templateStore.scanConfig.outputDir || './output'
})

// 只读：来自当前文件的基础文件名（去掉扩展名）
const baseFilename = computed(() => {
  const pair = templateStore.currentFilePair
  if (pair && pair.image_name) {
    return pair.image_name.split('.')[0]
  }
  return editorStore.suggestedFilename || 'table'
})

// 从数据源配置读取结构文件后缀
const structureSuffix = computed(() => {
  const activeSource = templateStore.activeDataSource
  if (activeSource && activeSource.output && activeSource.output.structure_suffix) {
    // 移除 .json 后缀（后端会自动添加）
    return activeSource.output.structure_suffix.replace('.json', '')
  }
  return '_structure'
})

// 可配置：覆盖策略
const overwriteMode = ref<'overwrite' | 'skip' | 'new'>('overwrite')

// 可配置：是否保存图片
const saveImage = ref(true)

// 从数据源配置读取图片文件后缀
const imageSuffix = computed(() => {
  const activeSource = templateStore.activeDataSource
  if (activeSource && activeSource.output && activeSource.output.image_suffix) {
    // 移除 .png 后缀（后端会自动添加）
    return activeSource.output.image_suffix.replace('.png', '')
  }
  return ''
})

const canSave = computed(() => {
  return editorStore.hasData && outputDir.value && baseFilename.value
})

async function handleSave() {
  if (!canSave.value) {
    ElMessage.warning('请先上传文件')
    return
  }
  
  isSaving.value = true
  
  try {
    const filename = baseFilename.value
    const imageFilename = saveImage.value ? `${baseFilename.value}${imageSuffix.value}` : undefined
    
    const response = await saveResult({
      structure: editorStore.structure,
      image_base64: saveImage.value ? (editorStore.imageSrc || undefined) : undefined,
      output_dir: outputDir.value,
      filename: filename,
      image_filename: imageFilename,
      overwrite_mode: overwriteMode.value,
      structure_suffix: structureSuffix.value,
      image_suffix: imageSuffix.value,
      line_width: 2,
      line_color: [0, 0, 0]
    })
    
    if (response.success) {
      ElMessage.success(`保存成功!`)
      if (response.structure_path) {
        ElMessage.info(`✅ 结构: ${response.structure_path}`)
      }
      if (response.image_path) {
        ElMessage.info(`✅ 图片: ${response.image_path}`)
      }
      
      // 保存后更新文件对的标注状态
      if (templateStore.hasFilePairs) {
        const currentIndex = templateStore.currentPairIndex
        const structurePath = response.structure_path || null
        templateStore.updatePairStatus(currentIndex, true, structurePath)
        
        // 自动移到下一个文件
        if (templateStore.hasNextPair) {
          templateStore.nextPair()
          ElMessage.info('➡️  已移动到下一个文件')
        } else {
          ElMessage.success('🎉 所有文件处理完成！')
        }
      }
      
      // 保存后自动收起
      expandSettings.value = false
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: unknown) {
    console.error('保存失败:', error)
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    ElMessage.error(`保存失败: ${errorMessage}`)
  } finally {
    isSaving.value = false
  }
}
</script>

<style scoped>
.save-panel {
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
}

/* 面板头部 - 始终可见 */
.panel-header {
  padding: 12px 16px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.3s ease;
  user-select: none;
}

.panel-header:hover {
  background-color: #f5f5f5;
}

.header-left {
  flex: 1;
}

.panel-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
}

.path-summary {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.path-label {
  color: #909399;
  font-weight: 500;
}

.path-value {
  color: #409eff;
  font-family: 'Monaco', 'Menlo', monospace;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.expand-icon {
  color: #909399;
  transition: transform 0.3s ease;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.header-right {
  margin-left: 8px;
}

/* 设置面板 - 可折叠 */
.settings-panel {
  padding: 16px;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 路径详情卡片 */
.path-detail-card {
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 16px;
}

.card-title {
  font-size: 12px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 8px;
}

.detail-item {
  background: white;
  padding: 8px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.detail-label {
  font-size: 11px;
  color: #909399;
  margin-bottom: 4px;
  font-weight: 500;
}

.detail-value {
  font-size: 13px;
  color: #303133;
  font-family: 'Monaco', 'Menlo', monospace;
  word-break: break-all;
  line-height: 1.4;
}

.detail-value.path-copy {
  cursor: copy;
  padding: 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.detail-value.path-copy:hover {
  background-color: #ecf5ff;
}

.config-hint {
  font-size: 11px;
  color: #909399;
  line-height: 1.5;
  padding-top: 8px;
  border-top: 1px solid #d9ecff;
}

/* 选项卡片 */
.options-card {
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 12px;
}

.options-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.options-form :deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.options-form :deep(.el-form-item__label) {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
}

/* 文件名预览 */
.filename-preview {
  display: inline-block;
  background: #f5f7fa;
  padding: 6px 10px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  color: #303133;
  margin-bottom: 6px;
  border: 1px solid #dcdfe6;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.filename {
  display: block;
}

.suffix {
  color: #409eff;
  font-weight: 600;
}

/* 覆盖策略提示 */
.strategy-hint {
  font-size: 11px;
  color: #909399;
  margin-top: 4px;
  padding: 4px 8px;
  background: #f5f7fa;
  border-radius: 3px;
  border-left: 3px solid #e6a23c;
}

/* 图片选项 */
.image-option {
  display: flex;
  align-items: center;
  gap: 12px;
}

.option-text {
  font-size: 12px;
  color: #606266;
}

.option-text .suffix {
  color: #409eff;
  font-weight: 600;
}

/* 保存按钮 */
.save-button {
  width: 100%;
  height: 36px;
  font-size: 13px;
  font-weight: 600;
  border-radius: 4px;
}
</style>
