// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import wx from 'weixin-js-sdk'
import Config from '../config'
import NewAxiosInstanceFunc from 'Service/NewAxiosInstance'
import { INewResponse } from 'Service/INewResponse'

const baseTitle = `${Config.titleGenerateHz}${Config.titleGenerateYj}`
const baseImgUrl = 'https://hzstatic.hzinsights.com/cygx_web/ico/logo.png'

export const checkWechat = (): boolean => /MicroMessenger/i.test(window.navigator.userAgent)

export interface IJssign {
  AppId: string
  NonceStr: string
  Timestamp: number
  Url: string
  Signature: string
  RawString: string
}

export interface IShareMsg {
  url: string
  title: string
  imgurl: string | undefined
  desc: string
}

const getJssign = (url: string): INewResponse<IJssign> =>
  NewAxiosInstanceFunc({
    url: `/wechat/getWxSign`,
    method: 'get',
    params: {
      Url: url
    }
  })

/**
 * 分享信息配置
 * @param shareMsg 分享信息对象
 */
export const shareConfig = (shareMsg: IShareMsg): void => {
  getJssign(shareMsg.url).then(result => {
    wx.config({
      debug: false,
      appId: result.data.Data.AppId || 'wx2f85cdbe74585222',
      timestamp: result.data.Data.Timestamp,
      nonceStr: result.data.Data.NonceStr,
      signature: result.data.Data.Signature,
      jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
    })
  })
  wx.ready(() => {
    wx.updateAppMessageShareData({
      title: shareMsg.title ? shareMsg.title : baseTitle,
      desc: shareMsg.desc ? shareMsg.desc : '', // 分享描述
      link: shareMsg.url,
      imgUrl: shareMsg.imgurl || baseImgUrl,
      success: function () {
        // 设置成功
      }
    })

    wx.updateTimelineShareData({
      title: shareMsg.title ? shareMsg.title : baseTitle,
      link: shareMsg.url,
      imgUrl: shareMsg.imgurl || baseImgUrl,
      success: function () {
        // 设置成功
      }
    })
  })
}
/**
 * 设置调用微信分享函数
 * @param title 标题
 * @param desc  描述
 * @param imgurl   小图
 */
export const setWxShare = (title: string, desc: string, imgurl: string | undefined): void => {
  const shareMsg = {
    url: window.location.href.split('#')[0],
    desc: desc,
    title: title,
    imgurl: imgurl
  }
  shareConfig(shareMsg)
}

export const prepareForWechatTag = async () => {
  const result = await getJssign(window.location.href.split('#')[0])
  wx.config({
    debug: true,
    appId: result.data.Data.AppId || 'wx2f85cdbe74585222',
    timestamp: result.data.Data.Timestamp,
    nonceStr: result.data.Data.NonceStr,
    signature: result.data.Data.Signature,
    jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
    openTagList: ['wx-open-audio']
  })
  await new Promise<void>((res, rej) => {
    wx.ready((...params: any[]) => {
      console.log(params)
      res()
    })
    wx.error((...params: any[]) => {
      console.log(params)
      rej()
    })
  })
}
