const CHAT_KEY_PREFIX = 'hl88msg:message_'

function decimalPlaces(n) {
	const parts = String(n).split('.')
	return parts.length > 1 ? parts[1].length : 0
}

function scaleFactor(a, b) {
	return Math.pow(10, Math.max(decimalPlaces(a), decimalPlaces(b)))
}

function stripDot(n) {
	return Number(String(n).replace('.', ''))
}

export function persistChatMessage(payload, direction) {
	const peerId = direction === 'send' ? payload.to_id : payload.form.id
	const storageKey = CHAT_KEY_PREFIX + peerId
	uni.getStorage({
		key: storageKey,
		success(res) {
			const history = res.data.slice(-96)
			history.push(payload)
			uni.setStorageSync(storageKey, history)
		},
		fail() {
			uni.setStorageSync(storageKey, [payload])
		}
	})
	return payload
}

export const decimalAdd = (a, b) => {
	const factor = scaleFactor(a, b)
	return (decimalMul(a, factor) + decimalMul(b, factor)) / factor
}

export const decimalSub = (a, b) => {
	const factor = scaleFactor(a, b)
	return (decimalMul(a, factor) - decimalMul(b, factor)) / factor
}

export const decimalMul = (a, b) => {
	let precision = 0
	const sa = String(a)
	const sb = String(b)
	try { precision += sa.split('.')[1].length } catch (_) {}
	try { precision += sb.split('.')[1].length } catch (_) {}
	return stripDot(sa) * stripDot(sb) / Math.pow(10, precision)
}

export const decimalDiv = (a, b) => {
	let pa = 0
	let pb = 0
	try { pa = String(a).split('.')[1].length } catch (_) {}
	try { pb = String(b).split('.')[1].length } catch (_) {}
	const na = stripDot(a)
	const nb = stripDot(b)
	return decimalMul(na / nb, Math.pow(10, pb - pa))
}
