import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { TableStructure, ImageSize, SelectedLine } from '@/types'
import { useHistoryStore } from './historyStore'

/**
 * 创建默认结构
 */
function createDefaultStructure(): TableStructure {
  return {
    horizontal_lines: [],
    vertical_lines: [],
    modified_h_lines: [],
    modified_v_lines: []
  }
}

export const useEditorStore = defineStore('editor', () => {
  // 状态
  const imageSrc = ref<string | null>(null)
  const imageSize = ref<ImageSize>({ width: 0, height: 0 })
  const scaleFactor = ref(1.0)
  const structure = ref<TableStructure>(createDefaultStructure())
  const ocrData = ref<Record<string, unknown> | null>(null)
  const selectedLine = ref<SelectedLine | null>(null)
  const zoom = ref(1.0)
  const stagePos = ref({ x: 0, y: 0 })
  const isLoading = ref(false)
  const suggestedFilename = ref<string | null>(null)
  
  // 表格边界框状态 [x1, y1, x2, y2]
  const tableBbox = ref<number[] | null>(null)
  const isDefiningBbox = ref(false)  // 是否正在定义边界框
  const skewAngle = ref(0)  // 倾斜角度（度）

  // 计算属性
  const hasData = computed(() => imageSrc.value !== null)
  
  const horizontalLineCount = computed(() => structure.value.horizontal_lines.length)
  const verticalLineCount = computed(() => structure.value.vertical_lines.length)
  
  const rowCount = computed(() => Math.max(0, horizontalLineCount.value - 1))
  const colCount = computed(() => Math.max(0, verticalLineCount.value - 1))
  
  // 有效的表格边界（优先使用用户定义的，否则使用结构中的，最后回退到图片边界）
  const effectiveTableBbox = computed(() => {
    if (tableBbox.value && tableBbox.value.length === 4) {
      return tableBbox.value
    }
    if (structure.value.table_bbox && structure.value.table_bbox.length === 4) {
      return structure.value.table_bbox
    }
    // 回退到图片边界
    return [0, 0, imageSize.value.width, imageSize.value.height]
  })
  
  // 是否有明确定义的表格边界
  const hasDefinedBbox = computed(() => {
    return (tableBbox.value && tableBbox.value.length === 4) ||
           (structure.value.table_bbox && structure.value.table_bbox.length === 4)
  })

  // 获取历史存储
  const historyStore = useHistoryStore()

  // 方法
  function loadData(
    base64Image: string,
    size: ImageSize,
    tableStructure: TableStructure,
    scale: number,
    ocr: Record<string, unknown> | null,
    filename?: string | null
  ) {
    imageSrc.value = base64Image
    imageSize.value = size
    structure.value = tableStructure
    scaleFactor.value = scale
    ocrData.value = ocr
    suggestedFilename.value = filename || null
    selectedLine.value = null
    zoom.value = 1.0
    stagePos.value = { x: 0, y: 0 }
    
    // 初始化表格边界框（从结构中获取）
    tableBbox.value = tableStructure.table_bbox || null
    
    // 初始化倾斜角度
    skewAngle.value = tableStructure.skew_angle || 0
    isDefiningBbox.value = false
    
    // 清空历史
    historyStore.clear()
  }

  function selectLine(line: SelectedLine | null) {
    selectedLine.value = line
  }

  function clearSelection() {
    selectedLine.value = null
  }

  /**
   * 更新线条位置
   */
  function updateLinePosition(type: 'h' | 'v', index: number, newValue: number) {
    // 保存历史
    historyStore.pushState(JSON.parse(JSON.stringify(structure.value)))
    
    if (type === 'h') {
      structure.value.horizontal_lines[index] = Math.round(newValue)
      // 标记为已修改
      if (!structure.value.modified_h_lines.includes(index)) {
        structure.value.modified_h_lines.push(index)
      }
    } else {
      structure.value.vertical_lines[index] = Math.round(newValue)
      if (!structure.value.modified_v_lines.includes(index)) {
        structure.value.modified_v_lines.push(index)
      }
    }
    
    // 保持排序
    structure.value.horizontal_lines.sort((a, b) => a - b)
    structure.value.vertical_lines.sort((a, b) => a - b)
  }

  /**
   * 添加线条
   */
  function addLine(type: 'h' | 'v', value: number) {
    // 保存历史
    historyStore.pushState(JSON.parse(JSON.stringify(structure.value)))
    
    const roundedValue = Math.round(value)
    
    if (type === 'h') {
      if (!structure.value.horizontal_lines.includes(roundedValue)) {
        structure.value.horizontal_lines.push(roundedValue)
        structure.value.horizontal_lines.sort((a, b) => a - b)
        // 标记新添加的线为已修改
        const newIndex = structure.value.horizontal_lines.indexOf(roundedValue)
        if (!structure.value.modified_h_lines.includes(newIndex)) {
          structure.value.modified_h_lines.push(newIndex)
        }
      }
    } else {
      if (!structure.value.vertical_lines.includes(roundedValue)) {
        structure.value.vertical_lines.push(roundedValue)
        structure.value.vertical_lines.sort((a, b) => a - b)
        const newIndex = structure.value.vertical_lines.indexOf(roundedValue)
        if (!structure.value.modified_v_lines.includes(newIndex)) {
          structure.value.modified_v_lines.push(newIndex)
        }
      }
    }
  }

  /**
   * 删除选中的线条
   */
  function deleteSelectedLine() {
    if (!selectedLine.value) return
    
    // 保存历史
    historyStore.pushState(JSON.parse(JSON.stringify(structure.value)))
    
    const { type, index } = selectedLine.value
    
    if (type === 'h') {
      structure.value.horizontal_lines.splice(index, 1)
      // 更新修改记录中的索引
      structure.value.modified_h_lines = structure.value.modified_h_lines
        .filter(i => i !== index)
        .map(i => i > index ? i - 1 : i)
    } else {
      structure.value.vertical_lines.splice(index, 1)
      structure.value.modified_v_lines = structure.value.modified_v_lines
        .filter(i => i !== index)
        .map(i => i > index ? i - 1 : i)
    }
    
    selectedLine.value = null
  }

  /**
   * 微调选中线条
   */
  function nudgeSelectedLine(delta: number) {
    if (!selectedLine.value) return
    
    const { type, index } = selectedLine.value
    
    if (type === 'h') {
      const currentValue = structure.value.horizontal_lines[index]
      updateLinePosition('h', index, currentValue + delta)
    } else {
      const currentValue = structure.value.vertical_lines[index]
      updateLinePosition('v', index, currentValue + delta)
    }
  }

  /**
   * 设置缩放
   */
  function setZoom(newZoom: number) {
    zoom.value = Math.max(0.25, Math.min(2.0, newZoom))
  }

  /**
   * 设置画布位置
   */
  function setStagePos(x: number, y: number) {
    stagePos.value = { x, y }
  }

  /**
   * 设置加载状态
   */
  function setLoading(loading: boolean) {
    isLoading.value = loading
  }

  /**
   * 应用历史状态
   */
  function applyStructure(newStructure: TableStructure) {
    structure.value = newStructure
    selectedLine.value = null
  }

  /**
   * 更新表格边界框
   */
  function updateTableBbox(bbox: number[]) {
    tableBbox.value = bbox
    // 同时更新structure中的table_bbox
    structure.value.table_bbox = bbox
  }
  
  /**
   * 开始/结束定义边界框模式
   */
  function setDefiningBbox(defining: boolean) {
    isDefiningBbox.value = defining
  }
  
  /**
   * 更新倾斜角度
   */
  function updateSkewAngle(angle: number) {
    skewAngle.value = angle
    // 同时更新structure
    structure.value.skew_angle = angle
  }

  /**
   * 恢复结构（用于撤销/重做）
   */
  function restoreStructure(newStructure: TableStructure) {
    structure.value = JSON.parse(JSON.stringify(newStructure))
    selectedLine.value = null
  }

  /**
   * 更新结构（用于重新分析）
   */
  function updateStructure(newStructure: TableStructure) {
    structure.value = {
      ...newStructure,
      modified_h_lines: [],
      modified_v_lines: []
    }
    selectedLine.value = null
  }

  /**
   * 重置编辑器
   */
  function reset() {
    imageSrc.value = null
    imageSize.value = { width: 0, height: 0 }
    scaleFactor.value = 1.0
    structure.value = createDefaultStructure()
    ocrData.value = null
    suggestedFilename.value = null
    selectedLine.value = null
    zoom.value = 1.0
    stagePos.value = { x: 0, y: 0 }
    isLoading.value = false
    tableBbox.value = null
    isDefiningBbox.value = false
    skewAngle.value = 0
    historyStore.clear()
  }

  return {
    // 状态
    imageSrc,
    imageSize,
    scaleFactor,
    structure,
    ocrData,
    suggestedFilename,
    selectedLine,
    zoom,
    stagePos,
    isLoading,
    tableBbox,
    isDefiningBbox,
    skewAngle,
    
    // 计算属性
    hasData,
    horizontalLineCount,
    verticalLineCount,
    rowCount,
    colCount,
    effectiveTableBbox,
    hasDefinedBbox,
    
    // 方法
    loadData,
    selectLine,
    clearSelection,
    updateLinePosition,
    addLine,
    deleteSelectedLine,
    nudgeSelectedLine,
    setZoom,
    setStagePos,
    setLoading,
    updateTableBbox,
    setDefiningBbox,
    updateSkewAngle,
    applyStructure,
    restoreStructure,
    updateStructure,
    reset
  }
})
