/* eslint-disable no-param-reassign */
import CONFIG from '@/config'
import { getWxShareInfo } from '@/api/modules/common'
import { Toast } from 'vant'

const common = {
  state: {
    isPageLoading: true, // 加载动画
    wxShareInfo: {
      link: window.location.href, // 访问链接
      title: '', // 标题
      desc: '', // 副标题
      imgUrl: CONFIG.defShareImg, // 分享图
      // eslint-disable-next-line no-empty-function
      success() {},
      // eslint-disable-next-line no-empty-function
      fail() {}
    }
  },
  mutations: {
    SET_ISPAGELOADING: (state, isLoading) => {
      state.isPageLoading = isLoading
    },
    SET_WXSHAREINFO: (state, info) => {
      const newObj = { ...state.wxShareInfo, ...info }
      state.wxShareInfo = newObj
    }
  },
  actions: {
    /* 填入分享信息，需主动调用 */
    initWXShare({ dispatch }, data) {
      const { info, params } = data
      dispatch('getWxJsApiToken', params)
      window.wx.ready(() => {
        window.wx.updateTimelineShareData(info) // 分享至好友
        window.wx.updateAppMessageShareData(info) // 分享至朋友圈
      })
      window.wx.error(err => {
        console.log(err)
      })
    },
    /* 请求授权 */
    getWxJsApiToken({ dispatch }, params = {}) {
      const obj = { href: window.location.href, ...params }
      getWxShareInfo(obj).then(res => {
        const { code, errorCode, data, errorMessage } = res
        if (code === 200 && errorCode === 0) {
          if (typeof data !== 'string') {
            dispatch('initWXSDK', data)
          }
        } else {
          Toast.fail(errorMessage)
        }
      })
    },
    /* 初始化微信分享 */
    // eslint-disable-next-line no-unused-vars
    initWXSDK({ state }, info) {
      window.wx.config({
        debug: false,
        appId: info.appId,
        timestamp: info.timestamp,
        nonceStr: info.nonceStr,
        signature: info.signature,
        jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData']
      })
    }
  },
  getters: {
    isPageLoading: state => state.isPageLoading, // 是否加载
    wxShareInfo: state => state.wxShareInfo // 是否加载
  }
}

export default common
