import { getListByCodeApi } from '@/api/system/dictData'

const statusMap: Map<string, 'inProcess' | 'completed' | 'fail'> = new Map()
const dataMap: Map<string, DictType[]> = new Map()

export async function getDictByCode(code: string): Promise<DictType[]> {
  const dictStatus = statusMap.get(code)

  if (dictStatus === 'fail') {
    statusMap.delete(code)
    return new Promise((resolve) => {
      resolve([])
    })
  }

  if (dictStatus === 'completed') {
    return new Promise((resolve) => {
      resolve(dataMap.get(code) ?? [])
    })
  }

  if (dictStatus === 'inProcess') {
    return new Promise((resolve) => {
      setTimeout(() => {
        getDictByCode(code).then((response) => {
          resolve(response)
        })
      }, 10)
    })
  }

  statusMap.set(code, 'inProcess')
  getListByCodeApi({ code })
    .then((resp) => {
      dataMap.set(code, resp)
      statusMap.set(code, 'completed')
    })
    .catch(() => {
      statusMap.set(code, 'fail')
    })

  return new Promise((resolve) => {
    setTimeout(() => {
      getDictByCode(code).then((response) => {
        resolve(response)
      })
    }, 50)
  })
}

export interface DictType {
  label: string
  value: number
  cssStyle: 'success' | 'warning' | 'info' | 'primary' | 'danger' | 'default'
}
