import { ref, computed } from 'vue'
import type { Ref, ComputedRef } from 'vue'  // 正确导入类型
import { ElMessage } from 'element-plus'
import type { ColumnConfig } from '@/components/DynamicColumnSelector/DynamicColumnDialog.vue'

export interface UseDynamicColumnsOptions {
  storageKey?: string
  defaultVisibleKeys?: string[]
  columns: ColumnConfig[]
}

export interface UseDynamicColumnsReturn {
  selectedKeys: Ref<string[]>
  visibleColumns: ComputedRef<ColumnConfig[]>
  selectedCount: ComputedRef<number>
  updateSelectedKeys: (keys: string[]) => void
  resetToDefault: () => void
  getTableColumnProps: (column: ColumnConfig) => Record<string, any>
  getExportColumns: () => string[]
}

export function useDynamicColumns(options: UseDynamicColumnsOptions): UseDynamicColumnsReturn {
  const {
    storageKey,
    defaultVisibleKeys = [],
    columns
  } = options

  // 选中的列键值
  const selectedKeys = ref<string[]>([])

  // 计算属性：可见列
  const visibleColumns = computed<ColumnConfig[]>(() => {
    return columns.filter(column => selectedKeys.value.includes(column.key))
  })

  // 计算属性：选中的列数量
  const selectedCount = computed(() => selectedKeys.value.length)

  // 初始化选中的列
  const initSelectedKeys = () => {
    let keys: string[]

    // 尝试从本地存储加载
    if (storageKey) {
      const savedKeys = localStorage.getItem(storageKey)
      if (savedKeys) {
        try {
          keys = JSON.parse(savedKeys)
        } catch (error) {
          console.error('Failed to parse saved columns:', error)
          keys = defaultVisibleKeys
        }
      } else {
        keys = defaultVisibleKeys
      }
    } else {
      keys = defaultVisibleKeys
    }

    // 过滤掉不存在的列
    const validKeys = keys.filter(key =>
      columns.some(col => col.key === key)
    )

    selectedKeys.value = validKeys.length > 0 ? validKeys : defaultVisibleKeys
  }

  // 保存到本地存储
  const saveToStorage = () => {
    if (storageKey) {
      localStorage.setItem(storageKey, JSON.stringify(selectedKeys.value))
    }
  }

  // 更新选中的列
  const updateSelectedKeys = (keys: string[]) => {
    selectedKeys.value = keys
    saveToStorage()
    ElMessage.success('列设置已保存')
  }

  // 重置为默认
  const resetToDefault = () => {
    selectedKeys.value = [...defaultVisibleKeys]
    saveToStorage()
    ElMessage.success('已恢复默认列设置')
  }

  // 获取表格列属性（用于el-table-column）
  const getTableColumnProps = (column: ColumnConfig): Record<string, any> => {
    const props: Record<string, any> = {
      property: column.property || column.key,
      label: column.label
    }

    if (column.width) props.width = column.width
    // if (column.minWidth) props.minWidth = column.minWidth
    if (column.sortable) props.sortable = column.sortable
    if (column.showOverflowTooltip) props['show-overflow-tooltip'] = column.showOverflowTooltip

    return props
  }

  // 导出时获取选中的列信息
  const getExportColumns = (): string[] => {
    return selectedKeys.value.map(key => {
      const column = columns.find(col => col.key === key)
      return column?.property || key
    })
  }

  // 初始化
  initSelectedKeys()

  return {
    selectedKeys,
    visibleColumns,
    selectedCount,
    updateSelectedKeys,
    resetToDefault,
    getTableColumnProps,
    getExportColumns
  }
}
