
/*
 * @Descripttion: 工具集
 * @version: 1.1
 * @LastEditors: yubaoshan
 * @LastEditTime: 2022年4月19日10:58:41
 */
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()
	}
}

// cookie操作
tool.cookie = {
	set(name, value, options = {}) {
		let expires = options.expires
		if (typeof expires === 'number') {
			const days = options.expires
			const date = new Date()
			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
			expires = options.expires = date
		}
		if (expires && expires.toUTCString) {
			options.expires = expires.toUTCString()
		}
		value = encodeURIComponent(value)
		let updatedCookie = name + '=' + value
		for (const propName in options) {
			updatedCookie += '; ' + propName
			const propValue = options[propName]
			if (propValue !== true) {
				updatedCookie += '=' + propValue
			}
		}
		document.cookie = updatedCookie
		return updatedCookie
	},
	get(name) {
		const matches = document.cookie.match(
			new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)')
		)
		return matches ? decodeURIComponent(matches[1]) : undefined
	},
	remove(name) {
		this.set(name, '', { expires: -1 })
	}
}

// 千分符
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.dictValue === dictValue)
	if (!tree) {
		return '无此字典'
	}
	const children = tree.children
	const dict = children.find((item) => item.dictValue === value)
	return dict ? dict.dictLabel : '无此字典项'
}

// 获取某个code下字典的列表，多用于字典下拉框
tool.dictTypeList = (dictValue) => {
	const dictTypeTree = tool.dictDataAll()
	if (!dictTypeTree) {
		return []
	}
	const tree = dictTypeTree.find((item) => item.dictValue === dictValue)
	if (tree && tree.children) {
		return tree.children
	}
	return []
}

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

// 生成UUID
tool.snowyUuid = () => {
	let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
		let r = (Math.random() * 16) | 0,
			v = c === 'x' ? r : (r & 0x3) | 0x8
		return v.toString(16)
	})
	// 首字符转换成字母
	return 'xn' + uuid.slice(2)
}

//格式化时间秒
tool.formatTimestamp = (timestamp) => {
	const date = new Date(timestamp)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	const seconds = String(date.getSeconds()).padStart(2, '0')
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

//格式化时间秒
tool.formatTimesYearMonthDay = (timestamp) => {
	const date = new Date(timestamp)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	const seconds = String(date.getSeconds()).padStart(2, '0')
	return `${year}-${month}-${day}`
}

//添加文本到剪切板
tool.writeText = (text) => {
	let copyInput = document.createElement('input')
	copyInput.value = text
	document.body.appendChild(copyInput)
	copyInput.select()
	document.execCommand('copy')
	document.body.removeChild(copyInput)
}
//字符串截取 ...
tool.truncateString = (str, maxLength) =>{
	if (str.length > maxLength) {
		return str.substring(0, maxLength) + '...';
	}
	return str;
}
/**
 * 将毫秒转换为时分秒格式
 * @param {number} milliseconds - 毫秒数
 * @returns {string} 格式化后的时间字符串 HH:mm:ss
 */
tool.formatMillisecondsToTime = (milliseconds) =>{
	// 确保输入是数字
	if (isNaN(milliseconds) || milliseconds < 0) {
		return '00:00:00';
	}

	// 计算小时、分钟、秒
	const seconds = Math.floor(milliseconds / 1000) % 60;
	const minutes = Math.floor(milliseconds / (1000 * 60)) % 60;
	const hours = Math.floor(milliseconds / (1000 * 60 * 60));

	// 补零并格式化
	const formatHours = hours.toString().padStart(2, '0');
	const formatMinutes = minutes.toString().padStart(2, '0');
	const formatSeconds = seconds.toString().padStart(2, '0');

	return `${formatHours}:${formatMinutes}:${formatSeconds}`;
}
// 添加上面的 formatValue 函数
tool.formatValue = (value) => {
	if (value === 0 || value === '0') {
		return '0'+'%';
	}

	const num = typeof value === 'string' ? parseFloat(value) : value;
	const result = num * 100;

	// 转为带两位小数的字符串，然后去除末尾不必要的0
	let formatted = result.toFixed(2);
	if (formatted.endsWith('.00')) {
		formatted = formatted.slice(0, -3); // 去掉 .00
	} else if (formatted.endsWith('0')) {
		formatted = formatted.slice(0, -1); // 去掉末尾的0
	}

	return formatted + '%';
}
export default tool
