import wx from 'weixin-js-sdk'
import { getWxSign } from '../api/wx'

const wxJs = () => {
  return new Promise((resolve, reject) => {
    getWxSign().then(res => {
      if (res.status) {
        resolve(res.data)
        return
      }
      reject(res)
    }).catch(err => {
      reject(err)
    })
  })
}
/**
 * wx-js-sdk 配置
 */
export const WxConfig = async () => {
  const { appId, timestamp, nonceStr, signature } = await wxJs()
  const wxParam = {
    debug: false,
    appId: appId,
    timestamp: timestamp,
    nonceStr: nonceStr,
    signature: signature,
    jsApiList: [
      'checkJsApi',
      'openLocation',
      'getLocation',
      'updateAppMessageShareData',
      'updateTimelineShareData',
      'onMenuShareAppMessage',
      'onMenuShareTimeline',
      'previewImage']
  }
  wx.config(wxParam)
  return wx
}

export const funWxShare = (title = '', desc = '', link = '', imgUrl = '') => {
  // 低版本微信兼容
  const appMessage = {
    title: title, // 分享标题
    desc: desc, // 分享描述
    link: link, // 分享链接
    imgUrl: imgUrl, // 分享图标
    success: function () {
    },
    cancel: function () {
    }
  }
  const timeline = {
    title: desc, // 分享标题
    link: link, // 分享链接
    imgUrl: imgUrl, // 分享图标
    success: function () {
    },
    cancel: function () {
    }
  }
  WxConfig().then(result => {
    window.wx = result
    result.ready(() => {
      // 分享给朋友
      result.updateAppMessageShareData ? result.updateAppMessageShareData(appMessage) : result.onMenuShareAppMessage(appMessage)
      // 分享到朋友圈
      result.updateTimelineShareData ? result.updateTimelineShareData(timeline) : result.onMenuShareTimeline(timeline)
    })
  })
}
