import dictEnum from '@/enum/dict'
import Vue from 'vue'
import {
	get,
	postJ
} from "@/utils/api.js";
const getSubListByParentId = function (id = 0){
	return get(Vue.prototype.apiUrl + `/classify/getSubListByParentId/${id}`)
}
const getDictListByMainCode = function (mainCode){
	return get(Vue.prototype.apiUrl + `/enumerationKeyvalue/getListByMainCode/${mainCode}`,undefined)
}
//非枚举定义
const otherDictConfig = {
	[dictEnum.物品类型]: {
		request: getSubListByParentId,
		dictCode: 'type',
		dictValue: 'name',
		resKey: '' //为空选 data
	}
}

const state = {}

const mutations = {
	//根据字典code 添加字典
	ADD_DICT: (state, {
		code,
		dict
	}) => {
		Vue.set(state, code, dict)
	}

	// // 根据字典enumName  和 dictCode 获取字典项
	// GET_DICT (state, { enumName, dictCode }) {
	//   return (
	//     (state[dictEnum[enumName]] || []).find(
	//       item => item.dictCode === dictCode
	//     ) || {}
	//   )
	// },
	// // 根据字典enumName  和 dictCode 获取字典 值（名称
	// GET_DICT_VALUE (state, { enumName, dictCode }) {
	//   const obj = (state[dictEnum[enumName]] || []).find(
	//     item => item.dictCode === dictCode
	//   )

	//   return obj && obj.dictValue
	// }
}

const actions = {
	// 根据字典enumName请求字典 已获取的不做重复请求
	async requestDict({
		commit,
		state
	}, enumName) {
		const code = dictEnum[enumName]

		if (state[code]?.length) return state[code]
		let res
		if (otherDictConfig[dictEnum[enumName]]) {
			const config = otherDictConfig[dictEnum[enumName]]
			console.log(config)
			//非枚举定义
			res = await config.request()
			if (res?.success) {
				let list = config.resKey ? res.data[config.resKey] : res.data
				commit('ADD_DICT', {
					code,
					dict: list.map(item => ({
						...item,
						dictCode: item[config.dictCode],
						dictValue: item[config.dictValue]
					}))
				})
				return res.list
			}
		} else {
			res = await getDictListByMainCode(code)
			if (res?.success) {
				commit('ADD_DICT', {
					code,
					dict: res.data
				})
				return res.data
			}
		}

		return []
	},
	// 更新字典
	async reloadRequestDict({
		commit
	}, enumName) {
		const code = dictEnum[enumName]
		const res = await getDictListByMainCode(code)
		if (res?.success) {
			commit('ADD_DICT', {
				code,
				dict: res.data
			})
			return res.data
		}

		return []
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}