import businessDEl from '@/api/business/dictionary.js'
import { clone } from '@/utils/systemUtils'

let cache = {}
let parentMap = {}
let enumMap = {}
let treeData = {}

export const loadFromStorage = () => {
	const data = localStorage.getItem('enumMaplist')
	if (data) {
		cache = JSON.parse(data)
		parentMap = cache?.parentMap
		enumMap = cache?.enumMap
	} else {
		cache = {}
		parentMap = {}
		enumMap = {}
	}
}

export const tryRefresh = () => {
	if (Object.keys(cache) <= 0) {
		loadFromStorage()
		if (Object.keys(cache) <= 0) {
			return businessDEl.getPersionsDEl().then((res) => {
				cache = res
				parentMap = cache?.parentMap
				enumMap = cache?.enumMap
			})
		}
	}

	return Promise.resolve(cache)
}

export const getEnumByEnumCode = (enumCode) => {
	return tryRefresh().then((_) => {
		for (const key of Object.keys(parentMap)) {
			const arr = parentMap[key]
			for (const enumData of arr) {
				if (enumData.enumcode === enumCode) {
					return enumData
				}
			}
		}
		console.warn('没有找到 enum code', enumCode)
		return null
	})
}

export const getEnumListByEnumId = (enumId) => {
	return tryRefresh().then((_) => {
		return parentMap[enumId]
	})
}

export const getNameById = (id) => {
	return tryRefresh().then((_) => {
		const name = enumMap[id]
		return { id, name }
	})
}

const buildTree = (data, rootId, valueIsName = false, enumData = false) => {
	let result = []

	if (data[rootId]) {
		data[rootId].forEach((item) => {
			let children = buildTree(data, item.enumid, valueIsName, enumData)
			if (children.length > 0) {
				item.children = children
			}
			if (enumData) {
				result.push(item)
			} else if (valueIsName) {
				result.push({
					label: item.enumname,
					value: item.enumname,
					id: item.enumname,
					children: item.children,
					raw: item
				})
			} else {
				result.push({
					label: item.enumname,
					value: item.enumid + '',
					id: item.enumid,
					children: item.children,
					raw: item
				})
			}
		})
	}

	return result
}

export const getTreeDataByEnumId = async (rootEnumId, valueIsName = false, enumData = false) => {
	if (treeData[rootEnumId]) return Promise.resolve(treeData[rootEnumId])
	return tryRefresh().then(() => {
		let data = parentMap[rootEnumId]
		if (!data) {
			return null
		}
		const ret = buildTree(clone(parentMap), rootEnumId, valueIsName, enumData)
		treeData[rootEnumId] = ret
		return ret
	})
}
