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

export let dictCache = {}

const SESSION_KEY = 'dict_cache'

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() {
      // 优先从 sessionStorage 读取缓存
      const cached = sessionStorage.getItem(SESSION_KEY)
      if (cached) {
        try {
          dictCache = JSON.parse(cached)
          this.dicts = dictCache
          this.loaded = true
          return
        } catch (e) {
          sessionStorage.removeItem(SESSION_KEY)
        }
      }
      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
          sessionStorage.setItem(SESSION_KEY, JSON.stringify(dictCache))
        }
      } catch (e) {
        console.error('数据字典加载失败', e)
      }
    }
  }
})