import { get } from './request'

export interface DictData {
  dictCode?: number
  dictSort?: number
  dictLabel: string
  dictValue: string
  dictType: string
  cssClass?: string
  listClass?: string
  isDefault?: string
  status?: string
  parentId?: number
  ancestors?: string
  remark?: string
  children?: DictData[]
}

export interface DictOptions {
  options: { value: string; label: string }[]
  labelMap: Record<string, string>
  colorMap: Record<string, string>
  data: DictData[]
}

/**
 * 获取指定字典类型的树形数据
 * @param dictType 字典类型，如 cooperation_type / facility_type / project_status
 */
export function getDictTree(dictType: string): Promise<DictData[]> {
  return get<DictData[]>(`/dict/data/tree/${dictType}`)
}

/**
 * 将字典数据转换为选项/映射结构
 */
export function buildDictOptions(data: DictData[]): DictOptions {
  const flatten = (items: DictData[]): DictData[] => {
    return items.reduce<DictData[]>((acc, item) => {
      acc.push(item)
      if (item.children && item.children.length > 0) {
        acc.push(...flatten(item.children))
      }
      return acc
    }, [])
  }

  const flat = flatten(data || [])
  const options = flat.map((item) => ({ value: item.dictValue, label: item.dictLabel }))
  const labelMap = flat.reduce<Record<string, string>>((acc, item) => {
    acc[item.dictValue] = item.dictLabel
    return acc
  }, {})
  const colorMap = flat.reduce<Record<string, string>>((acc, item) => {
    acc[item.dictValue] = item.listClass || ''
    return acc
  }, {})

  return { options, labelMap, colorMap, data }
}
