/*
 * @Descripttion: 工具集
 * @version: 1.1
 * @LastEditors: yubaoshan
 * @LastEditTime: 2022年4月19日10:58:41
 */
import dayjs from "dayjs";

const tool = {}

// localStorage
tool.data = {
	set(table, settings) {
		const _set = JSON.stringify(settings)
		return localStorage.setItem(table, _set)
	},
	get(table) {
		let data = localStorage.getItem(table)
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data
	},
	remove(table) {
		return localStorage.removeItem(table)
	},

	clear() {
		return localStorage.clear()
	}
}

// sessionStorage
tool.session = {
	set(table, settings) {
		const _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set)
	},
	get(table) {
		let data = sessionStorage.getItem(table)
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data
	},
	remove(table) {
		return sessionStorage.removeItem(table)
	},
	clear() {
		return sessionStorage.clear()
	}
}

// 千分符
tool.groupSeparator = (num) => {
	num = `${num}`
	if (!num.includes('.')) num += '.'

	return num
		.replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
			return `${$1},`
		})
		.replace(/\.$/, '')
}

// 获取所有字典数组
tool.dictDataAll = () => {
	return tool.data.get('DICT_TYPE_TREE_DATA')
}

// 字典翻译方法，界面插槽使用方法 {{ $TOOL.dictType('sex', record.sex) }}
tool.dictTypeData = (dictValue, value) => {
	const dictTypeTree = tool.dictDataAll()
	if (!dictTypeTree) {
		return '需重新登录'
	}
	const tree = dictTypeTree.find((item) => item.value === dictValue)
	if (!tree) {
		return '无此字典'
	}
	const children = tree.children
	const dict = children.find((item) => item.value === value)
	return dict ? dict.label : '无'
}

// 获取某个code下字典的列表，基于dictTypeList 改进，保留老的，逐步替换
tool.dictList = (dictValue) => {
	const dictTypeTree = tool.dictDataAll()
	if (!dictTypeTree) {
		return []
	}
	const tree = dictTypeTree.find((item) => item.value === dictValue)
	if (tree) {
		return tree.children.map((item) => {
			return {
				value: item['value'],
				label: item['name']
			}
		})
	}
	return []
}

// 树形翻译 需要指定最顶级的 parentValue  和当级的value
tool.translateTree = (parentValue, value) => {
	const tree = tool.dictDataAll().find((item) => item.dictValue === parentValue)
	const targetNode = findNodeByValue(tree, value)
	return targetNode ? targetNode.dictLabel : ''
}
const findNodeByValue = (node, value) => {
	if (node.dictValue === value) {
		return node
	}
	if (node.children) {
		for (let i = 0; i < node.children.length; i++) {
			const result = findNodeByValue(node.children[i], value)
			if (result) {
				return result
			}
		}
	}
	return null
}

// 通过身份证获取信息
tool.idCardTranslate = (idCard) => {
	if (idCard) {
		var sex = idCard.slice(16, 17);
		var date = idCard.slice(6, 14);
		return {
			sex: sex % 2 === 0 ? '女' : '男',
			birtyday: date.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1-$2-$3')
		}
	}
	return {
		sex: '',
		birtyday: ''
	}
}

// 计算当前相较于传入日期  过了多少年  不足一年按一年算
tool.betweenYear = (date) => {
	var day = 24 * 60 * 60 * 1000;

	var sDate = new Date(date);
	var eDate = new Date();

	//得到前一天(算头不算尾)
	sDate = new Date(sDate.getTime() - day);

	//获得各自的年、月、日
	var sY = sDate.getFullYear();
	var sM = sDate.getMonth() + 1;
	var sD = sDate.getDate();

	var eY = eDate.getFullYear();
	var eM = eDate.getMonth() + 1;
	var eD = eDate.getDate();

	var year = eY - sY;
	if (year > 0) {
		if (eM < sM) {
			year -= 1
		} else if (eM = sM && eD < sD) {
			year -= 1;
		}
	}
	return year;
}

/**
 * 日期数组  本周，本月，本年
 * @param date
 */
tool.dates = () => {
	const array = []
	array.push({label: '最近七天', value: [dayjs().add(-6,'day'), dayjs()]})
	array.push({label: '本周', value: [dayjs().startOf('week'), dayjs()]})
	array.push({label: '上周', value: [dayjs().add(-1, 'week').startOf('week'), dayjs().add(-1, 'week').endOf('week')]})
	array.push({label: '本月', value: [dayjs().startOf('month'), dayjs()]})
	array.push({label: '上月', value: [dayjs().add(-1, 'month').startOf('month'), dayjs().add(-1, 'month').endOf('month')]})
	array.push({label: '今年', value: [dayjs().startOf('year'), dayjs()]})
	array.push({label: '去年', value: [dayjs().add(-1, 'year').startOf('year'), dayjs().add(-1, 'year').endOf('year')]})
	return array;
}

export default tool
