import { getAPPUser, getAPPToken, getAPPUserDetail } from "../api/index";

export function formatDate(T) {
  let month = T.getMonth() + 1,
    day = T.getDate(),
    hour = T.getHours(),
    min = T.getMinutes();
  month > 9 ? "" : (month = "0" + month);
  day > 9 ? "" : (day = "0" + day);
  hour > 9 ? "" : (hour = "0" + hour);
  min > 9 ? "" : (min = "0" + min);
  return {
    D: [T.getFullYear(), month, day],
    T: [hour, min],
  };
}

export function urlSearchData() {
  let TextSearch = location ? location.href : "",
    search = {};
  const rex = new RegExp("https?://" + location.host + "/", "g");
  TextSearch = TextSearch.replace(rex, "").split("?");
  for (let i = 0; i < TextSearch.length; i++) {
    if (!TextSearch[i]) continue;
    const vs = TextSearch[i].split("=");
    if (!vs[1]) continue;
    const v = vs[1].split("#/")[0];
    search[vs[0]] = v;
  }
  return search;
}

export function isAndroid() {
  /* istanbul ignore next */
  return /android/.test(navigator.userAgent.toLowerCase());
}

export function isIOS() {
  /* istanbul ignore next */
  return /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase());
}

export function getUser(call) {
  let search = urlSearchData();
    if (!search.ticket) return;
  getAPPUser({
    ticket: search.ticket,
  }).then(r => {
    getAPPToken("rest/63bada00-7d01-4acc-ab2b-df8061eeeb8f").then(apptoken => {
      let APPToken = JSON.parse(apptoken || "{}");
      localStorage.token = APPToken.id || "";
      getAPPUserDetail({ loginName: r }).then(detail => {
        const D = JSON.parse(detail || "{}");
        if (D.success != false) localStorage.setItem("user", detail);
        call && call();
      });
    });
  });
}
