import { dictApi } from '@/api/menduner/common/useDictionaries'

const setDict = (type, val, cacheTime = 7200) => {
  localStorage.setItem(type, JSON.stringify({
    data: val,
    expire: Date.now() + cacheTime * 1000
  }))
}

export const getDict = (type, params, apiType = 'dict') => {
  if (!type) {
    // console.error('type不存在', type, params, apiType)
    return []
  }
  return new Promise((resolve) => {
    const item = localStorage.getItem(type)
    const catchData = item ? JSON.parse(item) : null
    if (catchData && catchData.expire && (Date.now() <= catchData.expire)) {
      return resolve({ data: catchData.data })
    }
    // 传参按照规范参数传
    const query = params ? params : { type }
    const apiFn = {
      // dict: getDictData,
      positionTreeData: dictApi.getPositionTreeData, // 职位tree
      areaTreeData: dictApi.getAreaTreeData, // 区域tree
      // industryTreeData: getIndustryTreeData, // 行业tree
      // industryList: getIndustryListData,
      // skillList: getSkillList,
      areaList: dictApi.getAreaListData,
      // areaMap: getAreaMapData,
      positionData: dictApi.getPositionData
    }
    if (!apiFn[apiType]) return
    
    apiFn[apiType](query).then(data => {
      setDict(type, data, Date.now())
      resolve({ data })
    })
  })
}