/*
 * @Description: h5 与 mp 交互
 * @Date: 2021-04-29 15:19:37
 * @LastEditors: gzw
 * @LastEditTime: 2021-06-07 19:30:02
 */
import qs from 'qs';
import commonCfg from '../config/common.setting';
const { MP_URL_MAP } = commonCfg;
class Mp {
  constructor() {
    this.callbackQueue = {};
    this.wx = require('weixin-js-sdk');
  }
  // 小程序中postMessage在特定时机（小程序后退、组件销毁、分享）触发； 如果需要立即触发，需要navigateTo跳转
  run(data, callback, immediate = false) {
    const { wx } = this;
    console.log(data.event);
    if (immediate) {
      const url = `${MP_URL_MAP.middleWay}${qs.stringify(data, {
        encode: true,
        addQueryPrefix: true
      })}`;
      if (callback) this.callbackQueue[data.event] = callback;
      wx.miniProgram.navigateTo({
        url,
        success: () => {
          this.bindListener();
        }
      });
    } else {
      wx.miniProgram.postMessage({ data });
    }
  }
  getToken(callback = () => {}) {
    this.run({ event: 'getToken' }, callback, true);
  }
  closeBrowser() {
    const { wx } = this;
    wx.miniProgram.navigateBack();
  }
  openNewUrl(data = {}) {
    const { wx } = this;
    const { newUrl } = data;
    console.log(newUrl);
    if (/(https|http):\/\//gi.test(newUrl)) {
      // window.location.href = newUrl;
      wx.miniProgram.navigateTo({
        url: `${MP_URL_MAP['webview']}?url=${encodeURIComponent(JSON.stringify(newUrl))}`
      });
    } else if (/xyqb:\/\//gi.test(newUrl)) {
      let urlTag = '';
      if (/goodsdetail|goodsDetail/gi.test(newUrl)) {
        urlTag = 'goodDetail';
      } else if (/goodsList/gi.test(newUrl)) {
        urlTag = 'landPage';
      } else if (/discover|homepage/gi.test(newUrl)) {
        urlTag = 'home';
      } else {
        urlTag = 'home';
      }
      if (urlTag) {
        const url = `${MP_URL_MAP[urlTag]}?${newUrl.split('?')[1]}`;
        wx.miniProgram[urlTag === 'home' ? 'reLaunch' : 'navigateTo']({ url });
      }
    } else {
      wx.miniProgram[data.type || 'navigateTo']({
        url: newUrl
      });
    }
  }
  getHashData(that, currentHref) {
    const hashArr = decodeURIComponent(currentHref).split('#/');
    const lastHashStr = hashArr[hashArr.length - 1];
    const hashData = qs.parse(lastHashStr);
    this.callbackQueue[hashData.event](hashData.data);
    this.unBindListener();
  }
  // TODO hashchange使用非匿名函数，获取location是异步的
  bindListener() {
    window.addEventListener(
      'hashchange',
      () => {
        this.getHashData(this, window.location.href);
      },
      false
    );
  }
  // TODO
  unBindListener() {
    window.removeEventListener(
      'hashchange',
      () => {
        this.getHashData(this, window.location.href);
      },
      false
    );
  }
}

export default Mp;
