import qs from 'qs';
import { lbsDictionary } from '@/common/js/BaseDictionary';

export function getMobileOperatingSystem() {
  // #ifdef H5
  const userAgent = navigator.userAgent || navigator.vendor || window.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.MSStream) {
    return 'iOS';
  }

  return 'unknown';
  // #endif

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

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

//
export function isInWeixinH5() {
  // TODO: 发布前取消注释
  return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1;
  // return true;
}

// 判断当前运行平台
export function getPlatform() {
  const userAgent = navigator.userAgent.toLowerCase();
  // 微信小程序
  if (/miniprogram/g.test(userAgent)) {
    return 'miniprogram';
  }
  // 微信公众号
  if (/micromessenger/g.test(userAgent)) {
    return 'micromessenger';
  }
  return 'browser';
}

// 是否在微信小程序中运行
export function getIsMin() {
  const platform = getPlatform();
  return platform === 'miniprogram';
}

// 是否在微信公众号中运行
export function getIsWxh5() {
  const platform = getPlatform();
  return platform === 'micromessenger';
}

// 获取appid
export function getAppIdByGroupIdAndMallId({ groupId, mallId, type }) {
  const platform = getPlatform();
  if (platform === 'miniprogram') {
    return 'wx92c3e55fbef6b2af';
  }
  if (platform === 'micromessenger') {
    // 后期在其他公众号上线H5应用，appid需要根据地址栏的 project 动态处理, 已预留入口
    console.log(89);
    const env = window.env === 'qa' ? 'qa' : 'prod';
    let appInfo = {};
    Object.keys(lbsDictionary).forEach((lbsId) => {
      const elm = lbsDictionary[lbsId];
      console.log(92, env, elm[env].groupId, groupId, elm[env].mallId, mallId);
      if (elm[env].groupId === groupId && elm[env].mallId === mallId) {
        appInfo = {
          appid: elm.appid,
          secret: elm.secret,
          projectId: elm[env].projectId,
        };
      }
    });
    console.log(101, appInfo);
    if (JSON.stringify(appInfo) === '{}') {
      // groupId, mallId 错误
      return;
    }
    if (type === 'appid') {
      return appInfo.appid;
    }
    if (type === 'all') {
      return appInfo;
    }
    return 'wx907c27f16841a919';
  }
  return '';
}

export function getUrlParams(url = window.location.href) {
  const str = `${url}`.split('?')[1];
  if (!str) return {};
  return qs.parse(str);
}

// 根据不同环境和lsbid返回 groupId 和 mallId
export function getGroupIdAndMallIdByLsbId(lbsId) {
  const lbsObj = lbsDictionary[lbsId];
  if (window.env === 'prod') {
    return lbsObj['prod'];
  }
  return lbsObj['qa'];
}

// 微信小程序端登录之后的回调
export function wxToLoginCallback(path, callback) {
  // 如果是在微信小程序内部运行的话
  if (getIsMin()) {
    // 前往登录
    window.toWXSendMsg({
      type: 'toLogin',
      options: {
        path: path,
      },
    });
    window.subscribe('callback', (options) => {
      if (options.isReload) {
        window.location.reload();
      } else {
        callback && callback();
      }
    });
    return;
  }
  // 如果是在微信公众号环境运行的话
  /*if ( getIsWxh5() ) {
    return
  }*/
}
