import { computed } from 'vue'
import { useDictStore } from '@/stores/dict'
/**
* 字典 Composable:把「加载 + 取值 + 文案/标签色查询」收敛成一行调用。
*
* 用法:
* const { items, options, label, tagType } = useDictionary('payment_channel')
* // 模板:
* // {{ label(row.status) }}
*
* @param {string} code 字典编码(库里真实的 dict_code)
*/
export function useDictionary(code) {
const dictStore = useDictStore()
// setup 阶段同步触发加载:缓存命中时不发请求,首次会自动拉取并响应式刷新
dictStore.ensure(code)
/** 字典项原始数组(含 item_value / item_label / tag_type 等) */
const items = computed(() => dictStore.getDictItemsSync(code))
/** el-select / el-option 直接可用的 { label, value } 列表 */
const options = computed(() => items.value.map((it) => ({
label: it.item_label,
value: it.item_value,
tag_type: it.tag_type
})))
return {
items,
options,
label: (value, fallback) => dictStore.getDictLabel(code, value, fallback),
tagType: (value, fallback) => dictStore.getDictTagType(code, value, fallback),
find: (value) => dictStore.getDictItem(code, value)
}
}
/**
* 只要「值 → 文案」或「值 → 标签色」时的轻量用法。
* const channelLabel = useDictLabel('payment_channel')
*/
export function useDictLabel(code) {
const dictStore = useDictStore()
dictStore.ensure(code)
return (value, fallback) => dictStore.getDictLabel(code, value, fallback)
}
export function useDictTagType(code) {
const dictStore = useDictStore()
dictStore.ensure(code)
return (value, fallback) => dictStore.getDictTagType(code, value, fallback)
}
/** 预加载多个字典(页面 onMounted 里调用,一次批量请求) */
export function useDictPreload(codes) {
const dictStore = useDictStore()
return () => dictStore.preloadDicts(codes)
}
export default useDictionary