import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDict as getDictApi } from '@/api'
import { removeCache, ArrToObj } from '@/utils'
// import { SOCKET_STATUS } from '@/types';
import db from '@/utils/db'

export const global = defineStore('global', () => {
  const dictData = ref((db.get('dict') || {}) as any)
  // 获取字典列表
  const getDicts = async () => {
    const res = await getDictApi()
    dictData.value = res.data
    db.set('dict', res.data)
  }

  // 获取字典
  const getDict = (key: string, full = false) => {
    const d = dictData.value.find((i: any) => i.code === key)
    const child = d ? d.children : []
    if (full) {
      return {
        dict: child,
        dictObj: ArrToObj(child, 'value', 'code'),
      }
    }
    return child
  }

  const clear = () => {
    dictData.value = {}
    removeCache('dict')
  }

  return {
    dict: dictData,
    getDicts,
    getDict,
    clear,
  }
})
