import { ComponentConfig } from './globalConfig'
import { createPathObject } from './utils'

export const OptionsMap = createPathObject({})

export function getOptionsByBaseCode(baseCode) {
  if (Array.isArray(OptionsMap[baseCode])) {
    return OptionsMap[baseCode]
  }
  if (!OptionsMap[baseCode]) {
    if (typeof ComponentConfig.BaseOptionsLoader === 'function') {
      OptionsMap[baseCode] = ComponentConfig.BaseOptionsLoader(baseCode)
      if (Array.isArray(OptionsMap[baseCode])) {
        return OptionsMap[baseCode]
      }
      if (OptionsMap[baseCode] instanceof Promise) {
        OptionsMap[baseCode].then((data) => {
          if (Array.isArray(data)) {
            OptionsMap[baseCode] = data
          } else {
            throw new Error('BaseOptionsLoader必须返回Array或Promise<Array>')
          }
        }).catch((e) => {
          console.error(e)
          delete OptionsMap[baseCode]
        })
        return []
      }
      throw new Error('BaseOptionsLoader必须返回Array或Promise<Array>')
    } else {
      throw new Error('BaseOptionsLoader必须是一个方法')
    }
  }
  return []
}

export async function asyncGetOptionsByBaseCode(baseCode) {
  getOptionsByBaseCode(baseCode)
  return OptionsMap[baseCode]
}

export async function asyncGetOptionsLabelByBaseCode(baseCode, value) {
  return asyncGetOptionsByBaseCode(baseCode).then((arr) => {
    return (arr.find((item) => {
      return item.value === value
    }) || {}).label
  })
}
