import tool from '@/utils/tool'
import * as all from '@/components/CommonSelector/data'

let keySeed = 0

export const clone = (obj) => {
	return JSON.parse(JSON.stringify(obj))
}

export const genKey = (prefix = 'sys-key') => {
	return `${prefix}-${keySeed++}`
}

export const parseField2Float = (obj, field) => {
	parseField2SomeType(obj, field, parseFloat)
}

export const parseField2Integer = (obj, field) => {
	parseField2SomeType(obj, field, parseInt)
}

export const parseField2String = (obj, field) => {
	parseField2SomeType(obj, field, (d) => {
		return d + ''
	})
}

export const parseField2SomeType = (obj, field, convertor) => {
	if (typeof field === 'string') {
		if (obj[field]) obj[field] = convertor(obj[field])
	} else if (Array.isArray(field)) {
		for (let f of field) {
			if (obj[f]) obj[f] = convertor(obj[f])
		}
	}
}

export const convertAll = (arrs, fun) => {
	const ret = []
	for (const d of arrs) {
		ret.push(fun(d))
	}
	return ret
}

export const convertAllByField = (arrs, field, convertor) => {
	for (const d of arrs) {
		parseField2SomeType(d, field, convertor)
	}
}

export const deleteField = (obj, field) => {
	if (typeof field === 'string') {
		delete obj[field]
	} else if (Array.isArray(field)) {
		for (let f of field) {
			delete obj[f]
		}
	}
}

export const deleteListField = (list, field) => {
	if (list && list.length > 0) {
		list.forEach((d) => {
			deleteField(d, field)
		})
	}
}

const flatDictData = {}

export const flatDict = (dict) => {
	dict.forEach((d) => {
		flatDictData[d.id] = {
			name: d.name,
			dictLabel: d.dictLabel,
			dictValue: d.dictValue
		}
		if (d.children) {
			flatDict(d.children)
		}
	})
}

export const getFlatDictData = () => {
	if (Object.keys(flatDictData) <= 0) {
		flatDict(tool.dictDataAll())
	}
	return flatDictData
}

export const dictItem = (id) => {
	const d = getFlatDictData()
	return d[id]
}

const parseOptions = (options) => {
	return options.map((d) => {
		const ret = {
			label: d.dictLabel,
			value: d.id,
			sortCode: d.sortCode || 99,
			raw: d
		}
		if (d.children && d.children.length > 0) {
			ret.children = parseOptions(d.children)
			ret.isLeaf = false
		} else {
			ret.isLeaf = true
		}
		return ret
	})
}

let regionOptions = []
export const getRegionOptions = (rootId = '1781533421287342082') => {
	if (regionOptions.length <= 0) {
		const root = tool.dictDataAll().find((d) => d.id === rootId)
		const opts = clone(root.children)
		console.log('tree', opts)
		regionOptions = parseOptions(opts)
	}
	return regionOptions
}

export const staticName = (type, val, def) => {
	if (all[type]) {
		const opts = all[type]
		const t = opts.find((d) => d.value == val)
		if (t) {
			return t.label
		} else {
			return def
		}
	} else {
		return def
	}
}
