/**
 * ruoyi字典数据仓库
 */
import { defineStore } from 'pinia'

import { getDicts } from '@/api/system/dict/data'

import { ref, toRefs } from 'vue'
/**
 * 授权仓库
 */
export const useDictStore = defineStore('useDictStore', {
	state: () => {
		return {
			dicts: {}
		}
	},
	//计算字段
	getters: {

	},
	//方法
	actions: {
		load(...args) {
			const res = ref({});
			return (() => {
				args.forEach((dictType, index) => {
					res.value[dictType] = [];
					if (this.dicts[dictType]) {
						res.value[dictType] = this.dicts[dictType];
					} else {
						this.listAsync(dictType).then(() => {
							res.value[dictType] = this.dicts[dictType];
						})
					}
				})
				return res.value;
			})()
		},
		listAsync(dictType) {
			return new Promise((resolve, reject) => {
				if (this.dicts[dictType] && this.dicts[dictType].length > 0) {
					resolve(this.dicts[dictType]);
				} else {
					getDicts(dictType).then(resp => {
						this.dicts[dictType] = resp.map(p => ({ label: p.dictLabel, value: Number(p.dictValue), type: p.listClass }))
						resolve(this.dicts[dictType]);
					}).catch(e => {
						reject(e);
					}
					);
				}
			});
		},
		list(dictType) {
			return this.load(dictType)[dictType];
		},
		getAsync(dictType, value) {
			return new Promise((resolve, reject) => {
				this.listAsync(dictType).then(list => {
					resolve(list.find(item => item.value == value));
				}).catch(e => {
					reject(e);
				}
				);
			});
		},
		get(dictType, value) {
			return this.load(dictType)[dictType].find(item => item.value == value);
		}




	},
	unistorage: false // 开启后对 state 的数据读写都将持久化

})