/* eslint-disable prettier/prettier */
import { isApp, isWxMp, isH5Normal } from './validation.service';
import Bridge from '@qg/js-bridge';
import MpBridge from '@/service/mp';
import commonCfg from '@/config/common.setting';
import qs from 'qs';
import localStorage from '@/service/localStorage.service'
function getTokenFromNative(resolve = () => {}, reject = () => {}) {
  const nativeBridge = new Bridge();
  window.xyqbNativeEvent = function(res) {
    const json = typeof res === 'string' ? JSON.parse(res) : res;
    console.log(json, 'res');
    if (json.event === 'getTokenSuccess'||json.event === 'loginAndLogoutNotification') {
      const appData = json.data || {};
      if (appData && appData.token) {
        localStorage.set('vccToken', appData.token);
        resolve(appData.token);
      } else {
        reject();
      }
    } else {
      reject();
    }

  }
  nativeBridge.getToken();
}

function getTokenFromWxMp(resolve = () => {}, reject = () => {}, clearToken) {
  const mpBridge = new MpBridge();
  mpBridge.getToken(res => {
    if (res && res.vccToken) {
      localStorage.set('vccToken', res.vccToken);
      resolve(res.vccToken);
    } else {
      reject();
    }
  }, clearToken);
}
// 获取token从app
export function getTokenFromApp(clearToken = false) {
  if (clearToken) {
    localStorage.remove('vccToken');
  }
  return new Promise((resolve, reject) => {
    if (localStorage.get('vccToken')) {
      resolve(localStorage.get('vccToken'));
      return;
    }
    if (isApp) {
      console.log('is app');
      getTokenFromNative(resolve, reject);
    } else if (isWxMp) {
      console.log('is wxmp');
      getTokenFromWxMp(resolve, reject, clearToken);
    } else {
      // h5暂不做处理
      console.log('not app or wxmp');
      reject();
    }
  });
}

// 自动跳转对应平台页面

export function jumpTargetPlatformPage(schemeName = '', data = {}, exit = false) {
  if (!schemeName || isH5Normal) return;
  const query = qs.stringify(data, { encode: true, addQueryPrefix: true });
  if (isApp && commonCfg.APP_URL_MAP[schemeName]) {
    console.log('isApp goto ' + commonCfg.APP_URL_MAP[schemeName] + query);
    const nativeBridge = new Bridge();
    nativeBridge.openNewUrl({
      data: {
        newUrl: commonCfg.APP_URL_MAP[schemeName] + query
      }
    });
  } else if (isWxMp && commonCfg.MP_URL_MAP[schemeName]) {
    console.log('isWxMp goto ' + commonCfg.APP_URL_MAP[schemeName] + query);
    const mpBridge = new MpBridge();
    mpBridge.openNewUrl(commonCfg.MP_URL_MAP[schemeName] + query);
  }
  if (exit) {
    window.history.back();
  }
}
