/**
 * TableColumnControl 集成辅助函数
 * 提供通用的列配置加载和保存逻辑
 */

import { ref, Ref, computed, ComputedRef } from 'vue'
import { useRoute } from 'vue-router'

export interface ColumnConfig {
  prop?: string
  label: string
  alwaysShow?: boolean
  fixed?: boolean | 'left' | 'right'
  minWidth?: number | string
  width?: number | string
  [key: string]: any
}

/**
 * 创建列显隐控制相关的响应式数据和方法
 * @param tableColumns 表格列配置数组
 * @returns 返回 visibleColumns、columnOrder、loadSavedConfig、handleColumnChange、handleColumnOrderChange 等
 */
export function useTableColumnControl(tableColumns: ColumnConfig[]) {
  const route = useRoute()
  
  // 当前显示的列
  const visibleColumns = ref<string[]>([])
  // 列排序顺序
  const columnOrder = ref<string[]>([])

  // 根据路由生成 storageKey
  const getStorageKey = (suffix: string = '') => {
    const routePath = route.path.replace(/^\//, '').replace(/\//g, '-')
    return `table-columns-${routePath}${suffix ? `-${suffix}` : ''}`
  }

  // 立即从 localStorage 加载配置
  const loadSavedConfig = () => {
    const storageKey = getStorageKey()
    const saved = localStorage.getItem(storageKey)
    if (saved) {
      try {
        const savedColumns = JSON.parse(saved)
        const validColumns = tableColumns
          .filter(col => !col.alwaysShow && !col.fixed)
          .map(col => col.prop || col.label)
        const filteredSaved = savedColumns.filter((col: string) => validColumns.includes(col))
        visibleColumns.value = filteredSaved.length > 0 ? filteredSaved : validColumns
      } catch (e) {
        console.error('解析列配置失败:', e)
        visibleColumns.value = tableColumns
          .filter(col => !col.alwaysShow && !col.fixed)
          .map(col => col.prop || col.label)
      }
    } else {
      visibleColumns.value = tableColumns
        .filter(col => !col.alwaysShow && !col.fixed)
        .map(col => col.prop || col.label)
    }
    
    // 加载列排序配置
    const orderKey = getStorageKey('order')
    const savedOrder = localStorage.getItem(orderKey)
    if (savedOrder) {
      try {
        const parsedOrder = JSON.parse(savedOrder)
        const validColumns = tableColumns
          .filter(col => !col.alwaysShow && !col.fixed)
          .map(col => col.prop || col.label)
        columnOrder.value = parsedOrder.filter((key: string) => validColumns.includes(key))
        validColumns.forEach(key => {
          if (!columnOrder.value.includes(key)) {
            columnOrder.value.push(key)
          }
        })
      } catch (e) {
        console.error('解析列排序失败:', e)
        columnOrder.value = tableColumns
          .filter(col => !col.alwaysShow && !col.fixed)
          .map(col => col.prop || col.label)
      }
    } else {
      columnOrder.value = tableColumns
        .filter(col => !col.alwaysShow && !col.fixed)
        .map(col => col.prop || col.label)
    }
  }

  // 排序后的表格列
  const sortedTableColumns = computed(() => {
    const columns = tableColumns.filter(col => {
      const key = col.prop || col.label
      return col.alwaysShow || col.fixed || visibleColumns.value.includes(key)
    })
    
    if (columnOrder.value.length > 0) {
      const orderedColumns: ColumnConfig[] = []
      const unorderedColumns: ColumnConfig[] = []
      
      columnOrder.value.forEach(key => {
        const col = columns.find(c => (c.prop || c.label) === key)
        if (col) {
          orderedColumns.push(col)
        }
      })
      
      columns.forEach(col => {
        const key = col.prop || col.label
        if (!columnOrder.value.includes(key)) {
          unorderedColumns.push(col)
        }
      })
      
      return [...orderedColumns, ...unorderedColumns]
    }
    
    return columns
  })

  // 列显示控制函数
  const checkColumnVisible = (prop: string): boolean => {
    if (visibleColumns.value.length === 0) {
      return true
    }
    return visibleColumns.value.includes(prop)
  }

  // 监听列变化
  const handleColumnChange = (columns: string[]) => {
    visibleColumns.value = columns
    const storageKey = getStorageKey()
    const selectableColumns = columns.filter(col => {
      const column = tableColumns.find(c => (c.prop || c.label) === col)
      return column && !column.alwaysShow && !column.fixed
    })
    localStorage.setItem(storageKey, JSON.stringify(selectableColumns))
  }

  // 监听列排序变化
  const handleColumnOrderChange = (order: string[]) => {
    columnOrder.value = order
    const storageKey = getStorageKey('order')
    localStorage.setItem(storageKey, JSON.stringify(order))
  }

  return {
    visibleColumns,
    columnOrder,
    sortedTableColumns,
    checkColumnVisible,
    loadSavedConfig,
    handleColumnChange,
    handleColumnOrderChange
  }
}

