/**
 * 数据相关-本地持久化，global data...
 */
import globalData from '@/util/globalData'
import {
	get,
	cloneDeep,
	identity,
	pickBy
} from 'lodash'

// 本地存储
export const setStorage = (key, data) => {
	uni.setStorage({
		key,
		data
	})
}

// 删除本地和global data
export const clearStorageSync = () => {
	try {
		globalData = {}
		uni.clearStorageSync()
	} catch (e) {
		// Do something when catch error
	}
}

// global data set
export const saveGlobalDataByKey = (key, value) => {
	globalData[key] = value
}

// global data get
export const getGlobalDataByKey = (key) => {
	return globalData[key]
}

// global data delete
export const deleteGlobalDataByKey = (key, value) => {
	delete globalData[key]
}

// 同步delete
export const removeStorageSync = (key) => {
	try {
		deleteGlobalDataByKey(key)
		uni.removeStorageSync(key)
	} catch (e) {
		// Do something when catch error
	}
}

// 同步set
export const setStorageSync = (key, data) => {
	saveGlobalDataByKey(key, data)
	uni.setStorageSync(key, data)
}

// 同步get
export const getStorageSync = (key) => {
	const data = getGlobalDataByKey(key)
	if (data) {
		return data
	}
	try {
		var value = uni.getStorageSync(key)
		if (value) {
			saveGlobalDataByKey(key, value)
			return value
		}
	} catch (e) {}
}


export const deleteGlobalDataByIds = (key, ids) => {
	const n = ids.split(',')
	const array = uni.getStorageSync(key)
	if (!array) {
		return
	}
	const newArray = cloneDeep(array)
	n.forEach((id) => {
		const index = newArray.findIndex((j) => j.id === id)
		if (index !== -1) {
			newArray.splice(index, 1)
		}
	})

	uni.setStorageSync(key, newArray)
}


export const getTimeStr = (str) => {
	if (str == '2099-12-31') {
		return '长期有效'
	}
	return str
}

export const formatCurrency = (num) => {
	num = num.toString().replace(/\$|\,/g, '');
	if (isNaN(num))
		num = "0";
	let sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	let cents = num % 100;
	num = Math.floor(num / 100).toString();
	if (cents < 10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ',' +
		num.substring(num.length - (4 * i + 3));
	return (((sign) ? '' : '-') + num + '.' + cents);
}
