import wx from 'weixin-js-sdk'

import { getWxShareSecret } from '@/api/modules/common'

class WxShare {
  constructor() {
    this.wxShareInfo = WxShare.translatorInitInfo()
    this.config = {
      jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData'],
    }
  }

  init(initInfo, initParams) {
    const info = WxShare.translatorInitInfo(initInfo)
    const params = WxShare.translatorInitParams(initParams)
    this.getWxJsApiSecret(params)
    wx.ready(() => {
      wx.updateTimelineShareData(info) // 分享至好友
      wx.updateAppMessageShareData(info) // 分享至朋友圈
    })
    wx.error((err) => {
      console.log(err)
    })
  }

  // 接口获取验证token
  getWxJsApiSecret(params) {
    getWxShareSecret(params).then((res) => {
      const { code, errorCode, data, errorMessage } = res
      if (code === 200 && errorCode === 0) {
        if (typeof data !== 'string') {
          this.setWxSDKConfig(data)
        }
      } else {
        console.error(errorMessage)
      }
    })
  }

  // 通过config接口注入权限验证配置
  setWxSDKConfig(info) {
    const defConfig = {
      debug: false,
      appId: info?.appId || '',
      timestamp: info?.timestamp || '',
      nonceStr: info?.nonceStr || '',
      signature: info?.signature || '',
      jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData'],
    }
    wx.config({
      ...defConfig,
      ...this.config,
    })
  }

  static translatorInitInfo(info) {
    return {
      link: info?.link || window.location.href,
      title: info?.title || '分享',
      desc: info?.desc || window.location.href, // 副标题
      imgUrl: info?.imgUrl || `${window.location.protocol}${process.env.OSS_DOMAIN}/common/img/shop_share.png`,
      success: info?.success || function () {},
      fail: info?.fail || function () {},
    }
  }

  static translatorInitParams(params) {
    return {
      uin: params?.uin || 0,
      href: params?.href || window.location.href,
    }
  }
}

export default new WxShare()
