import { defineStore } from 'pinia'
import { get } from '@/api/http'

// Module level cache for quick access
export let dictCache = {}

export const useDatadicStore = defineStore('datadic', {
  state: () => ({
    dicts: {},
    loaded: false
  }),
  getters: {
    getByCode: (state) => (code) => {
      return dictCache[code] || null
    },
    getContent: (code) => {
      const item = dictCache[code]
      return item ? item.contents : ''
    }
  },
  actions: {
    async init() {
      if (this.loaded) return
      try {
        const res = await get('/v1/client/CDatadicsClient')
        if (res.status === 200 && res.data) {
          res.data.forEach(item => {
            dictCache[item.code] = item
          })
          this.dicts = dictCache
          this.loaded = true
        }
      } catch (e) {
        console.error('数据字典加载失败', e)
      }
    }
  }
})