import { getStore } from './storage'

export interface DictItem {
  value: string
  label: string
}

export type DictMap = Record<string, DictItem[]>

export const formatDict = (dict: DictItem[] | undefined, dictValue: any): string => {
  try {
    if (!dict) return String(dictValue)
    for (const item of dict) {
      if (item.value === String(dictValue)) return item.label
    }
    return String(dictValue)
  } catch {
    return String(dictValue)
  }
}

export const selectDict = (dict: DictMap, dictName: string, filter: string[] = []): DictItem[] => {
  const filterSet = new Set(filter)
  return (dict[dictName] || []).filter((o) => !filterSet.has(o.value))
}

export const dateFormater = (fmt: string, time: any): string => {
  if (time === '' || time === null || time === undefined) return ''
  let date = new Date(time)
  const opt: Record<string, string> = {
    'Y+': date.getFullYear().toString(),
    'M+': (date.getMonth() + 1).toString(),
    'd+': date.getDate().toString(),
    'H+': date.getHours().toString(),
    'm+': date.getMinutes().toString(),
    's+': date.getSeconds().toString()
  }
  for (const k in opt) {
    const ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
    }
  }
  return fmt
}

export interface TreeNode {
  children?: TreeNode[]
  [key: string]: any
}

export const treeToArray = (tree: TreeNode[]): TreeNode[] => {
  return tree.reduce((res: TreeNode[], item) => {
    const { children, ...rest } = item
    return res.concat(rest, children && children.length ? treeToArray(children) : [])
  }, [])
}

export const hasAuthCode = (code: string): boolean => {
  const permissions: string[] = getStore('permissions') || []
  return permissions.some((item: string) => item === code)
}
