"use strict";

/**
 * @export 设置高分屏方案函数
 * @param {Boolean} [normal = false] - 默认开启页面压缩以使页面高清;
 * @param {Number} [baseFontSize = 100] - 基础fontSize, 默认100px;
 * @param {Number} [fontscale = 1] - 有的业务希望能放大一定比例的字体;
 */
export function setFlexRem (normal, baseFontSize, fontscale) {
  const win = window;
  const _baseFontSize = baseFontSize || process.env.VUE_APP_REM_UNIT;
  const _fontscale = fontscale || 1;

  const doc = win.document;
  const ua = navigator.userAgent;
  const matches = ua.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i);
  const UCversion = ua.match(/U3\/((\d+|\.){5,})/i);
  const isUCHd =
    UCversion && parseInt(UCversion[1].split(".").join(""), 10) >= 80;
  const isIos = navigator.appVersion.match(/(iphone|ipad|ipod)/gi);
  let dpr = win.devicePixelRatio || 1;
  if (!isIos && !(matches && matches[1] > 534) && !isUCHd) {
    // 如果非iOS, 非Android4.3以上, 非UC内核, 就不执行高分屏, dpr设为1;
    dpr = 1;
  }
  const scale = normal ? 1 : 1 / dpr;

  let metaEl = doc.querySelector('meta[name="viewport"]');
  if (!metaEl) {
    metaEl = doc.createElement("meta");
    metaEl.setAttribute("name", "viewport");
    doc.head.appendChild(metaEl);
  }
  metaEl.setAttribute(
    "content",
    `width=device-width,user-scalable=no,initial-scale=${scale},maximum-scale=${scale},minimum-scale=${scale}`
  );
  doc.documentElement.style.fontSize = normal
    ? "50px"
    : `${_baseFontSize * dpr * _fontscale}px`;
  // 通过resize还原document.body.clientWidth, 以兼容@media失效
  store.commit("config/SET_REAL_WID", document.body.clientWidth * scale);
  console.info(
    "高分屏方案: dpr =",
    scale,
    ", 1rem =",
    doc.documentElement.style.fontSize
  );
}

// setFlexRem 防抖和节流
import { debounce, throttle } from "@/utils/optimize";
import { isNative } from "@/utils/device";
import bus from "@/config/event-bus";
import store from "@/store";

// 节流: 初始化和 onresize 加载时
const initLayout = throttle(isEmit => {
  setFlexRem();
  store.commit("config/SET_IS_NATIVE", isNative());
  if (isEmit) bus.$vm.$emit(bus.$sel.window_resize); // 响应式更新
}, 400);

// 初始化
initLayout();
// 兼容 onresize 改变窗口全局调用: 防抖
window.onresize = debounce(() => initLayout(true));
// 响应式需要调用resize事件以响应加载时更新
window.onload = () => {
  bus.$vm.$emit(bus.$sel.window_onload);
  bus.$vm.$emit(bus.$sel.window_resize);
};

// import bus from "@/config/event-bus";
// bus.$vm.$on(bus.$sel.window_resize, () => { }); // 响应resize
// bus.$vm.$on(bus.$sel.window_onload, () => { }); // 响应onload
