import { api } from './common'
import type { AppMenuItem } from '../stores/menu'

// 后端 Workspace 页面数据结构
export interface WorkspacePage {
  name: string
  title: string
  for_user: string
  parent_page: string | null
  content: string
  public: number
  module: string
  icon: string
  indicator_color: string
  is_hidden: number
  label: string
}

// 后端 API 响应结构
export interface WorkspaceSidebarResponse {
  pages: WorkspacePage[]
  has_access: boolean
  has_create_access: boolean
}

/**
 * 调用后端 get_desktop_page 接口获取带权限过滤的 Workspace 页面数据
 * 该接口会根据用户权限过滤 cards、shortcuts、quick_lists 等内容
 */
export const getDesktopPage = async (workspaceData: any): Promise<any> => {
  const result = await api.call('jingrow.desk.desktop.get_desktop_page', {
    page: JSON.stringify(workspaceData)
  })
  
  return result.message || result
}

/**
 * 调用后端 get_workspace_sidebar_items 接口获取菜单数据
 */
export const getWorkspaceSidebarItems = async (): Promise<WorkspaceSidebarResponse> => {
  try {
    const result = await api.call('jingrow.desk.desktop.get_workspace_sidebar_items')
    
    // Jingrow API 返回格式: { message: {...} }
    const data = result.message || result
    
    return {
      pages: data.pages || [],
      has_access: data.has_access || false,
      has_create_access: data.has_create_access || false
    }
  } catch (error: any) {
    console.error('Failed to fetch workspace sidebar items:', error)
    throw new Error(error.message || 'Failed to fetch workspace sidebar items')
  }
}

/**
 * 将后端 Workspace 数据转换为前端 AppMenuItem 格式
 */
export const transformWorkspaceToMenuItem = (page: WorkspacePage): AppMenuItem => {
  const isPrivate = page.public === 0
  const menuItem: AppMenuItem = {
    id: page.name,
    key: page.name,
    label: page.title || page.name,
    type: 'workspace',
    workspaceName: page.name,
    icon: page.icon || 'tabler:layout-dashboard',
    isPrivate: isPrivate,
    parentId: page.parent_page || undefined,
    hidden: page.is_hidden === 1,
    order: 0 // 将在后续处理中设置
  }

  return menuItem
}

/**
 * 批量转换 Workspace 页面为菜单项，并保持层级顺序
 */
export const transformWorkspacePages = (pages: WorkspacePage[]): AppMenuItem[] => {
  const menuItems: AppMenuItem[] = []
  
  const titleToName = new Map<string, string>()
  pages.forEach(p => {
    titleToName.set(p.title, p.name)
  })
  
  const publicPages = pages.filter(p => p.public === 1)
  const privatePages = pages.filter(p => p.public === 0)
  
  let order = 1
  
  privatePages.forEach(page => {
    const item = transformWorkspaceToMenuItem(page)
    if (page.parent_page) {
      item.parentId = titleToName.get(page.parent_page) || page.parent_page
    }
    item.order = order++
    menuItems.push(item)
  })
  
  publicPages.forEach(page => {
    const item = transformWorkspaceToMenuItem(page)
    if (page.parent_page) {
      item.parentId = titleToName.get(page.parent_page) || page.parent_page
    }
    item.order = order++
    menuItems.push(item)
  })
  
  return menuItems
}
