import wx from 'weixin-js-sdk';
import { http } from '@/utils/request';
import { wechatConfig } from '@/api/common';

export function isWechat() {
  // #ifdef H5
  const ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/micromessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
  // #endif
}

export function weixinLogin() {
  const baseHref = window.location.href.split('#')[0];
  const redirect_uri = encodeURIComponent(`${baseHref}#${window.location.href.split('#')[1]}`);
  const state = 1;
  window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?&appid=wxe87236d542cd0f94&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`);
}

export async function wxConfigH5(url) {
  if (!isWechat()) {
    return;
  }
  const jsApiList = [
    'chooseWXPay',
    'chooseImage',
    'scanQRCode',
    'updateAppMessageShareData',
    'updateTimelineShareData',
    'getLocalImgData',
    'uploadImage'
  ];
  http.get(`${wechatConfig}`, {
    // url: url,
    url: url,
    // baseUrl: 'https://app.zaojiao.net/'
  })
  .then(r=> {
    wx.config({
      debug: false,
      appId: r.data.appId,
      timestamp: r.data.timestamp,
      nonceStr: r.data.nonceStr,
      signature: r.data.signature,
      jsApiList: jsApiList,
      openTagList: ["wx-open-launch-weapp"]
    });
    wx.error((err) => {
      console.log('err', err);
    });
  }).catch(() => {
    console.log('catch')
  })
}

export function wxShare(title, imgUrl, desc, link) {
  const url = window.location.href.split('#')[0];
  const shareTitle = title || '中德智慧教育';
  const shareDesc = desc || '全球思维儿童教育专家 全球优质教育内容输出平台';
  const shareLink = link || url;
  const shareImgUrl = imgUrl || 'http://res.training.luojigou.vip/FiLdD-zXCwM6A6JkVzAp8nKM7WLx';
  wx.ready(() => {
    wx.onMenuShareTimeline({
      title: shareTitle, // 分享时的标题
      link: shareLink, // 分享时的链接
      imgUrl: shareImgUrl, // 分享时的图标
      success() {
        // Toast('分享成功');
        console.log('分享成功');
      },
      cancel() {
        // Toast('取消分享');
        console.log('取消分享');
      },
    });
    // 分享给朋友
    wx.onMenuShareAppMessage({
      title: shareTitle,
      desc: shareDesc,
      link: shareLink,
      imgUrl: shareImgUrl,
      type: '',
      dataUrl: '',
      success() {
        // Toast('分享成功');
        console.log('分享成功');
      },
      cancel() {
        // Toast('取消分享');
        console.log('取消分享');
      },
    });
  });
}

export function getQueryString(name) {
  let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  let r = window.location.search.substr(1).match(reg); // 获取url中"?"符后的字符串并正则匹配
  let context = '';
  if (r != null) { context = r[2]; }
  reg = null;
  r = null;
  return context == null || context == '' || context == 'undefined' ? '' : context;
}
