
import request from "./request"

const jsApiList = [
  'updateAppMessageShareData',
  'updateTimelineShareData',
  'onMenuShareTimeline',
  'onMenuShareAppMessage',
  'onMenuShareQQ',
  'onMenuShareWeibo',
  'onMenuShareQZone'
]

function initSDK (url) {
  request(`https://api.h5.njyunzhi.com/mp/jssdk?url=${encodeURIComponent(url)}`).then((res) => {
    window.wx.config({
      debug: process.env.NODE_ENV === 'development', // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: res.appId, // 必填，公众号的唯一标识
      timestamp: res.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.nonceStr, // 必填，生成签名的随机串
      signature: res.signature, // 必填，签名
      jsApiList // 必填，需要使用的JS接口列表
    })
  })
}

/**
 * 分享
 * @param {*} opt
 */
export function share (opt) {
  initSDK(opt.link)
  window.wx.ready(function () {
    jsApiList.map((apiName) => {
      const api = window.wx[apiName]
      api({
        title: opt.title || '', // 分享标题
        link: opt.link || '', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: opt.imgUrl || '', // 分享图标
        desc: opt.desc || ''
      })
    })
  })
}

/**
 * 获取 code
 * @returns 
 */
function getCode () {
  const matched = /[?&]*code=([^&]+)/.exec(location.search)
  if (matched) {
    return decodeURIComponent(matched[1])
  }
}

/**
 * 跳转授权页面
 */
export function redirect () {
  if (process.env.NODE_ENV === 'development') return;

  const originCode = localStorage.getItem('wxcode');
  const queryCode = getCode();
  localStorage.setItem('wxcode', queryCode)

  if (!queryCode || queryCode === originCode) {
    const local = encodeURIComponent(location.origin + location.pathname)
    const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd3bab568bc42d1de&redirect_uri=${local}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
    window.location.href = url
  }
}

/**
 * 获取 openid
 * @returns 
 */
export function getOpenId () {
  if (process.env.NODE_ENV === 'development') return Promise.resolve('123');

  const code = getCode()
  if (!code) {
    return Promise.reject("获取用户信息失败, 请刷新重试")
  }

  return request(`https://api.h5.njyunzhi.com/mp/openid?code=${encodeURIComponent(code)}`)
}
