export function pxToRpx(px: number) {
  let ratio = 2;
  try {
    const systemInfo = uni.getSystemInfoSync();
    ratio = 750 / systemInfo.screenWidth;
  } catch { }

  return Number((px * ratio).toFixed(5));
}

export function getQueryParam() {
  let query: Record<string, string> = {};
  query = location.search
    .slice(1)
    .split('&')
    .map((p) => p.split('='))
    .reduce((obj: Record<string, string>, pair) => {
      const [key, value] = pair.map(decodeURIComponent);
      obj[key] = value;
      return obj;
    }, {});
  return query;
}

export function isInWeixinH5() {
  // #ifdef H5
  // TODO-webview 在小程序webview里面，因为引入了 jweixin-1.6.0.js，返回值也是 true
  return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  // #endif

  // #ifndef H5
  return false;
  // #endif
}

export function isInWeixinMpWebView() {
  // #ifdef H5
  // TODO-webview app 启动时，jweixin-1.6.0.js 可能还未加载完毕，所以要用 query string 中特殊 key 来 hack 一下
  const query = getQueryParam();
  return query.wxMpWebview == 'true' || (window as any).__wxjs_environment === 'miniprogram';
  // #endif

  // #ifndef H5
  return false;
  // #endif
}

export function isInAppWebView() {
  // #ifdef H5
  // TODO-webview app 启动时，UniAppJSBridgeReady 可能还未触发，所以要用 query string 中特殊 key 来 hack 一下
  const query = getQueryParam();
  return query.appWebview == 'true' || (window as any).isInPlusWebView == true;
  // #endif

  // #ifndef H5
  return false;
  // #endif
}

export function getMobileOperatingSystem() {
  // #ifdef H5
  const userAgent = navigator.userAgent || navigator.vendor || (window as any).opera;

  // Windows Phone must come first because its UA also contains "Android"
  if (/windows phone/i.test(userAgent)) {
    return "Windows Phone";
  }

  if (/android/i.test(userAgent)) {
    return "Android";
  }

  // iOS detection from: http://stackoverflow.com/a/9039885/177710
  if (/iPad|iPhone|iPod/.test(userAgent) && !(window as any).MSStream) {
    return "iOS";
  }

  return "unknown";
  // #endif

  // #ifndef H5
  return "unknown";
  // #endif
}

export function isAppInstalled(app: 'weixin'|'alipay') {
  // #ifdef APP-PLUS
  if (app == 'weixin') {
    return plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' });
  } else if (app == 'alipay') {
    return plus.runtime.isApplicationExist({ pname: 'com.eg.android.AlipayGphone', action: 'alipay://' });
  }
  // #endif

  return false;
}

export function uuid() {
  let u = '';
  let i = 0;
  while (i++ < 36) {
    const c = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'[i - 1], r = Math.random() * 16 | 0;
    const v = c == 'x' ? r : (r & 0x3 | 0x8);
    u += (c == '-' || c == '4') ? c : v.toString(16)
  }
  return u;
}
