import { manageApi } from '@vue2-client/services/api'
import { handleTree } from '@vue2-client/utils/util'
import { indexedDB } from '@vue2-client/utils/indexedDB'
import { getConfigByName } from '@vue2-client/services/api/common'

// 字典缓存
const dictCache = new Map()

const GetAppDataService = {
  install (Vue) {
    Vue.$appdata = Vue.prototype.$appdata = GetAppDataService
  },

  async load () {
    localStorage.setItem(
      process.env.VUE_APP_DICTIONARY_KEY,
      JSON.stringify({})
    )
    localStorage.setItem(
      process.env.VUE_APP_BADGE_KEY,
      JSON.stringify({})
    )
  },

  // 返回树形省市区
  async getDivisionsOhChinaForTree () {
    return new Promise((resolve, reject) => {
      try {
        indexedDB.getByWeb(
          'divisionsOhChina',
          manageApi.getDivisionsOhChina,
          {},
          res => resolve(res),
          processRes => handleTree(processRes, 'code', 'parentcode')
        )
      } catch (e) {
        reject(e)
      }
    })
  },
  // 用于徽标解析字典值
  parseDictValue (dictList, value) {
    if (!Array.isArray(dictList)) {
      return {
        status: 'none',
        text: value
      }
    }

    const item = dictList.find(i => i.value == value)
    if (item) {
      return {
        status: item.status || 'none',
        text: item.label
      }
    }

    return {
      status: 'none',
      text: value
    }
  },

  // 获取徽标字典值
  async getDictValue (
    dictKey,
    value,
    callback,
    isDev = false,
    serviceName = process.env.VUE_APP_SYSTEM_NAME
  ) {
    const dictList = await this.getDictByKeyAsync(
      dictKey,
      serviceName,
      isDev
    )
    const result = this.parseDictValue(dictList, value)

    if (typeof callback === 'function') {
      callback(result)
    } else {
      return result
    }
  },

  // 获取琉璃字典（Callback 版本）
  getDictByKey (dictKey, serviceName, callback, isDev) {
    this.getDictByKeyAsync(dictKey, serviceName, isDev)
      .then(res => {
        if (typeof callback === 'function') {
          callback(res)
        }
      })
  },

  // 获取琉璃字典（Promise 版本，核心实现）
  async getDictByKeyAsync (
    dictKey,
    serviceName = process.env.VUE_APP_SYSTEM_NAME,
    isDev = false
  ) {
    const cacheKey = `${serviceName}:${dictKey}`

    if (dictCache.has(cacheKey)) {
      return dictCache.get(cacheKey)
    }
    const dictList = await new Promise(resolve => {
      getConfigByName(
        dictKey,
        serviceName,
        res => resolve(res?.value || []),
        isDev
      )
    })

    dictCache.set(cacheKey, dictList)
    return dictList
  },

  getParams () {
    const str = localStorage.getItem(process.env.VUE_APP_DICTIONARY_KEY)
    return str ? JSON.parse(str) : {}
  },

  getSingleValues () {
    const str = localStorage.getItem(process.env.VUE_APP_BADGE_KEY)
    return str ? JSON.parse(str) : {}
  },

  getWebConfigByKey (key) {
    const str = localStorage.getItem(process.env.VUE_APP_WEB_CONFIG_KEY)
    if (!str) return undefined
    const object = JSON.parse(str)
    return object?.[key]
  },

  getStylesByKey (key) {
    const str = localStorage.getItem(process.env.VUE_APP_WEB_STYLES_KEY)
    if (!str) return undefined
    const object = JSON.parse(str)
    return object?.[key]
  }
}

export default GetAppDataService
