import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  TableStructure, 
  TemplateInfo, 
  FilePair, 
  DirectoryItem, 
  DataSourceConfig 
} from '@/types'

/**
 * 模板管理 Store
 */
export const useTemplateStore = defineStore('template', () => {
  // 模板列表
  const templates = ref<TemplateInfo[]>([])
  const isLoadingTemplates = ref(false)
  
  // 当前预览
  const previewStructure = ref<TableStructure | null>(null)
  const previewTemplateName = ref<string | null>(null)
  const isPreviewMode = ref(false)
  
  // 批量模式
  const batchMode = ref(false)
  const selectedTemplateName = ref<string | null>(null)  // 选中的模板，用于批量应用
  const autoApplyTemplate = ref(false)  // 是否自动应用模板
  
  // 目录浏览
  const currentPath = ref<string>('')
  const directoryItems = ref<DirectoryItem[]>([])  
  const parentPath = ref<string | null>(null)  
  
  // 文件扫描
  const filePairs = ref<FilePair[]>([])
  const currentPairIndex = ref(0)
  const scanConfig = ref({
    imageDir: '',
    jsonDir: '',
    outputDir: ''
  })
  
  // 数据源配置
  const dataSources = ref<DataSourceConfig[]>([])
  const activeDataSourceFilename = ref<string | null>(null)  // 使用 filename 作为唯一标识符
  const isLoadingDataSources = ref(false)
  
  // 计算属性
  const hasTemplates = computed(() => templates.value.length > 0)
  const hasFilePairs = computed(() => filePairs.value.length > 0)
  const currentFilePair = computed(() => 
    filePairs.value[currentPairIndex.value] || null
  )
  const labeledCount = computed(() => 
    filePairs.value.filter(p => p.has_structure).length
  )
  const unlabeledCount = computed(() => 
    filePairs.value.filter(p => !p.has_structure).length
  )
  const selectedTemplate = computed(() =>
    templates.value.find(t => t.name === selectedTemplateName.value) || null
  )
  const hasPrevPair = computed(() => currentPairIndex.value > 0)
  const hasNextPair = computed(() => currentPairIndex.value < filePairs.value.length - 1)
  
  // 数据源相关计算属性
  const hasDataSources = computed(() => dataSources.value.length > 0)
  const activeDataSource = computed(() => 
    dataSources.value.find(ds => ds.filename === activeDataSourceFilename.value) || null
  )
  // 为了向后兼容，保留 activeDataSourceName（使用 name 字段）
  const activeDataSourceName = computed(() => activeDataSource.value?.name || null)
  
  // 方法
  function setTemplates(list: TemplateInfo[]) {
    templates.value = list
  }
  
  function addTemplate(template: TemplateInfo) {
    templates.value.unshift(template)
  }
  
  function removeTemplate(name: string) {
    const index = templates.value.findIndex(t => t.name === name)
    if (index !== -1) {
      templates.value.splice(index, 1)
    }
  }
  
  function setPreview(structure: TableStructure, templateName: string) {
    previewStructure.value = structure
    previewTemplateName.value = templateName
    isPreviewMode.value = true
  }
  
  function clearPreview() {
    previewStructure.value = null
    previewTemplateName.value = null
    isPreviewMode.value = false
  }
  
  function setDirectory(path: string, items: DirectoryItem[], parent: string | null) {
    currentPath.value = path
    directoryItems.value = items
    parentPath.value = parent
  }
  
  function setFilePairs(pairs: FilePair[]) {
    filePairs.value = pairs
    currentPairIndex.value = 0
  }
  
  function setCurrentPairIndex(index: number) {
    if (index >= 0 && index < filePairs.value.length) {
      currentPairIndex.value = index
    }
  }
  
  function nextPair() {
    if (currentPairIndex.value < filePairs.value.length - 1) {
      currentPairIndex.value++
    }
  }
  
  function prevPair() {
    if (currentPairIndex.value > 0) {
      currentPairIndex.value--
    }
  }
  
  function updatePairStatus(index: number, hasStructure: boolean, structurePath: string | null) {
    if (index >= 0 && index < filePairs.value.length) {
      filePairs.value[index].has_structure = hasStructure
      filePairs.value[index].structure_path = structurePath
    }
  }
  
  function setScanConfig(config: { imageDir: string; jsonDir: string; outputDir: string }) {
    scanConfig.value = config
  }
  
  function selectTemplate(name: string | null) {
    selectedTemplateName.value = name
  }
  
  function toggleBatchMode(enabled?: boolean) {
    batchMode.value = enabled ?? !batchMode.value
  }
  
  function setAutoApplyTemplate(enabled: boolean) {
    autoApplyTemplate.value = enabled
  }
  
  // 数据源管理方法
  function setDataSources(sources: DataSourceConfig[]) {
    dataSources.value = sources
  }
  
  function selectDataSource(sourceFilename: string | null) {
    activeDataSourceFilename.value = sourceFilename
    
    // 如果选择了数据源，自动应用其配置到 scanConfig
    if (sourceFilename) {
      const source = dataSources.value.find(ds => ds.filename === sourceFilename)
      if (source) {
        applyDataSourceConfig(source)
      } else {
        console.warn('selectDataSource: 未找到匹配的数据源', {
          sourceFilename,
          availableFilenames: dataSources.value.map(ds => ds.filename),
          dataSourcesCount: dataSources.value.length
        })
      }
    }
  }
  
  function applyDataSourceConfig(source: DataSourceConfig) {
    // 后端已经解析了模板变量，这里只需处理相对路径转绝对路径
    let resolvedImageDir = source.image_dir
    let resolvedJsonDir = source.json_dir
    let resolvedOutputDir = source.output.directory
    
    // 如果是相对路径，与 base_dir 组合成绝对路径
    if (!resolvedImageDir.startsWith('/')) {
      resolvedImageDir = `${source.base_dir}/${resolvedImageDir}`.replace(/\/+/g, '/')
    }
    if (!resolvedJsonDir.startsWith('/')) {
      resolvedJsonDir = `${source.base_dir}/${resolvedJsonDir}`.replace(/\/+/g, '/')
    }
    if (!resolvedOutputDir.startsWith('/')) {
      resolvedOutputDir = `${source.base_dir}/${resolvedOutputDir}`.replace(/\/+/g, '/')
    }
    
    scanConfig.value = {
      imageDir: resolvedImageDir,
      jsonDir: resolvedJsonDir,
      outputDir: resolvedOutputDir
    }
    
    // 如果数据源指定了默认模板，自动选择
    if (source.batch?.template_name) {
      selectedTemplateName.value = source.batch.template_name
    }
    
    // 如果数据源指定了自动应用，设置标志
    if (source.batch?.auto_apply !== undefined) {
      autoApplyTemplate.value = source.batch.auto_apply
    }
  }
  
  function reset() {
    templates.value = []
    previewStructure.value = null
    previewTemplateName.value = null
    isPreviewMode.value = false
    filePairs.value = []
    currentPairIndex.value = 0
    batchMode.value = false
    selectedTemplateName.value = null
    autoApplyTemplate.value = false
    activeDataSourceFilename.value = null
  }

  return {
    // 状态
    templates,
    isLoadingTemplates,
    previewStructure,
    previewTemplateName,
    isPreviewMode,
    batchMode,
    selectedTemplateName,
    autoApplyTemplate,
    currentPath,
    directoryItems,
    parentPath,
    filePairs,
    currentPairIndex,
    scanConfig,
    dataSources,
    activeDataSourceFilename,
    activeDataSourceName,  // 计算属性，向后兼容
    isLoadingDataSources,
    
    // 计算属性
    hasTemplates,
    hasFilePairs,
    currentFilePair,
    labeledCount,
    unlabeledCount,
    selectedTemplate,
    hasPrevPair,
    hasNextPair,
    hasDataSources,
    activeDataSource,
    
    // 方法
    setTemplates,
    addTemplate,
    removeTemplate,
    setPreview,
    clearPreview,
    setDirectory,
    setFilePairs,
    setCurrentPairIndex,
    nextPair,
    prevPair,
    updatePairStatus,
    setScanConfig,
    selectTemplate,
    toggleBatchMode,
    setAutoApplyTemplate,
    setDataSources,
    selectDataSource,
    applyDataSourceConfig,
    reset
  }
})
