let doc = window.document;
let docEl = doc.documentElement;
let metaEl = doc.querySelector('meta[name="viewport"]');
let dpr = 0;
let scale = 0;
let tid;
let flexRem = 0;
const orgMetaElContent = metaEl && metaEl.getAttribute("content");

function refreshRem() {
  let width = docEl.getBoundingClientRect().width;
  if (width / dpr > 540) {
    width = 540 * dpr;
  }
  const rem = width / 10;
  console.log(width, rem);
  docEl.style.fontSize = rem + "px";
  flexRem = rem;
}

function domResize() {
  clearTimeout(tid);
  tid = setTimeout(refreshRem, 300);
}

const init = () => {
  if (!dpr && !scale) {
    // const isAndroid = window.navigator.appVersion.match(/android/gi);
    const isIPhone = window.navigator.appVersion.match(/iphone/gi);
    const devicePixelRatio = window.devicePixelRatio;
    if (isIPhone) {
      // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
      if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
        dpr = 3;
      } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
        dpr = 2;
      } else {
        dpr = 1;
      }
    } else {
      // 其他设备下，仍旧使用1倍的方案
      dpr = 1;
    }
    scale = 1 / dpr;
  }

  docEl.setAttribute("data-dpr", dpr);
  const meteContent =
    "initial-scale=" +
    scale +
    ", maximum-scale=" +
    scale +
    ", minimum-scale=" +
    scale +
    ", user-scalable=no";
  if (!metaEl) {
    metaEl = doc.createElement("meta");
    metaEl.setAttribute("content", meteContent);
    if (docEl.firstElementChild) {
      docEl.firstElementChild.appendChild(metaEl);
    } else {
      const wrap = doc.createElement("div");
      wrap.appendChild(metaEl);
      doc.write(wrap.innerHTML);
    }
  } else {
    metaEl.setAttribute("content", meteContent);
  }

  window.addEventListener("resize", domResize, false);
  if (doc.readyState === "complete") {
    doc.body.style.fontSize = 12 * dpr + "px";
  } else {
    doc.addEventListener(
      "DOMContentLoaded",
      function(e) {
        doc.body.style.fontSize = 12 * dpr + "px";
      },
      false
    );
  }
  refreshRem();
};

const destroy = () => {
  window.removeEventListener("resize", domResize, false);
  metaEl.setAttribute("content", orgMetaElContent);
  docEl.removeAttribute("data-dpr");
  docEl.style.fontSize = null;
};

const rem2px = function(d) {
  var val = parseFloat(d) * flexRem;
  if (typeof d === "string" && d.match(/rem$/)) {
    val += "px";
  }
  return val;
};
const px2rem = function(d) {
  var val = parseFloat(d) / flexRem;
  if (typeof d === "string" && d.match(/px$/)) {
    val += "rem";
  }
  return val;
};

export default {
  init,
  destroy,
  rem2px,
  px2rem
};
