itemCategory.js 2.24 KB
import { getItemCategoryMapping } from '@/api/extend/itemCategory'

// 品项分类「内部编码 → 显示名/颜色」映射缓存
// 设计要点:内部编码(生美/医美/科美/合作/其他/产品)保持不变,仅显示名可配置;
// 任何取不到映射的情况一律兜底返回原编码,保证永不空白、零风险。
let categoryMap = {}
let categoryList = []
let loaded = false
let loadingPromise = null

/**
 * 编码 → 显示名(兜底返回原编码)
 * @param {string} code 内部编码
 */
export function catName(code) {
  if (code === undefined || code === null || code === '') return code
  const item = categoryMap[code]
  return item && item.displayName ? item.displayName : code
}

/**
 * 编码 → 颜色(取不到返回空串)
 * @param {string} code 内部编码
 */
export function catColor(code) {
  const item = categoryMap[code]
  return item && item.color ? item.color : ''
}

/** 获取启用中的分类列表(副本) */
export function getCategoryList() {
  return categoryList.slice()
}

/**
 * 获取启用中的分类下拉选项(value=内部编码,label=显示名)
 * 供品项资料 qt2 等下拉使用;未加载时返回空数组
 */
export function getCategoryOptions() {
  return categoryList.map(it => ({
    label: (it && it.displayName) ? it.displayName : it.code,
    value: it.code
  }))
}

/** 是否已加载完成 */
export function isCategoryLoaded() {
  return loaded
}

/**
 * 加载并缓存分类映射;自动去重并发请求,失败不阻断业务
 * @param {boolean} force 强制刷新
 */
export function loadItemCategoryMap(force = false) {
  if (loaded && !force) return Promise.resolve(categoryList)
  if (loadingPromise && !force) return loadingPromise
  loadingPromise = getItemCategoryMapping()
    .then(res => {
      const list = res && res.data ? res.data : []
      const map = {}
      list.forEach(it => {
        if (it && it.code != null) map[it.code] = it
      })
      categoryMap = map
      categoryList = list
      loaded = true
      loadingPromise = null
      return categoryList
    })
    .catch(() => {
      // 失败保持兜底(返回原编码),不阻断业务
      loadingPromise = null
      return categoryList
    })
  return loadingPromise
}