import useDictStore from '@/store/modules/dict'
import { _list } from '@/api/app'

/**
 * 获取字典数据
 */
export const useDict = (...args) => {
  const res = ref([])
  const hasCachedDict = useDictStore().getAllDict()

  if (!hasCachedDict) {
    _list({ pagevalue: 18 }).then((resp) => {
      const dictArr = rebuildDictArray(resp.Data.Data)
      useDictStore().setDict(dictArr)

      args.forEach((dictType, index) => {
        const dicts = useDictStore().getDict(dictType)
        res.value.push(dicts ? dicts : [])
      })
    })
  } else {
    args.forEach((dictType, index) => {
      const dicts = useDictStore().getDict(dictType)
      res.value.push(dicts ? dicts : [])
    })
  }
  return res.value
}

/**
 * 获取字典数据 async
 * setup中调用，需要在改组件的父组件中使用Suspense
 */
export const useDictAsync = (...args) => {
  return new Promise((resolve, reject) => {
    const res = ref([])
    const hasCachedDict = useDictStore().getAllDict()

    if (!hasCachedDict) {
      _configurationLoadAll().then((resp) => {
        const dictArr = rebuildDictArray(resp.Data)
        useDictStore().setDict(dictArr)

        args.forEach((dictType, index) => {
          const dicts = useDictStore().getDict(dictType)
          res.value.push(dicts ? dicts : [])
        })

        resolve(res.value)
      })
    } else {
      args.forEach((dictType, index) => {
        const dicts = useDictStore().getDict(dictType)
        res.value.push(dicts ? dicts : [])
      })
      resolve(res.value)
    }
  })
}

export const rebuildDictArray = (apiData) => {
  // [{
  //   available: true,
  //   baseid: 1,
  //   describes: "目录",
  //   groupname: "菜单类型",
  //   id: 1,
  //   ispublic: true,
  //   substance: "1",
  //   title: "目录"
  // }]
  const dictArray = formattingData(apiData, 'groupname')

  return dictArray
}

/**
 * 数据处理
 * @param arr [Array] 被处理的数组
 * @param group_key [String] 分组字段
 */
function formattingData(arr, group_key) {
  let map = {}
  let res = []

  if (arr.length) {
    for (let i = 0; i < arr.length; i++) {
      let ai = arr[i]
      if (!map[ai[group_key]]) {
        map[ai[group_key]] = [ai]
      } else {
        map[ai[group_key]].push(ai)
      }
    }
    Object.keys(map).forEach((key) => {
      res.push({
        [group_key]: key,
        list: map[key],
      })
    })
  }

  return res
}
