import { getUniversalZoomLevel } from '@/utils/tools'

const maxWidth = 1920;
const minWidth = 500;
let flexible = (designWidth = 1920) => {
	var doc = document, win = window, docEl = doc.documentElement, remStyle = document.createElement("style"), tid;
	function refreshRem() {
		var width = docEl.getBoundingClientRect().width;
		var height = docEl.getBoundingClientRect().height;
		width = getUniversalZoomLevel() * width
		height = getUniversalZoomLevel() * height
		if (width > maxWidth) width = maxWidth;
		if (width < minWidth) width = minWidth;
		var rem = (width * 10 / designWidth).toFixed(2);
		docEl.style.fontSize = rem + 'px'
	}
	//要等 wiewport 设置好后才能执行 refreshRem，不然 refreshRem 会执行2次；
	refreshRem();
	win.addEventListener("resize", function () {
		clearTimeout(tid); //防止执行两次
		tid = setTimeout(refreshRem, 200);
	}, false);

	win.addEventListener("pageshow", function (e) {
		if (e.persisted) { // 浏览器后退的时候重新计算
			clearTimeout(tid);
			tid = setTimeout(refreshRem, 200);
		}
	}, false);
};

export default flexible