import { getWxSignature } from '@/api'
import * as ww from '@wecom/jssdk'

let wxConfigPromise: Promise<void> | null = null

export function initWxConfig() {
  if (wxConfigPromise) return wxConfigPromise

  wxConfigPromise = new Promise((resolve, reject) => {
    ;(async () => {
      try {
        const url = location.href.split('#')[0]
        const { data } = await getWxSignature(url!)
        let resolved = false
        const timer = window.setTimeout(() => {
          if (!resolved) {
            resolved = true
            console.warn('企业微信 SDK 初始化未返回成功回调，继续执行后续操作')
            resolve()
          }
        }, 3000)

        const handleFail = (error: unknown) => {
          window.clearTimeout(timer)
          wxConfigPromise = null
          reject(error)
        }

        const handleConfigSuccess = () => {
          if (!resolved) {
            resolved = true
            window.clearTimeout(timer)
            resolve()
          }
        }

        const signature = {
          timestamp: data.timestamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
        }

        ww.register({
          corpId: data.corpid,
          agentId: data.agentid,
          jsApiList: ['shareAppMessage', 'selectEnterpriseContact'],
          getConfigSignature() {
            return signature
          },
          getAgentConfigSignature() {
            return signature
          },
          onConfigSuccess: handleConfigSuccess,
          onAgentConfigSuccess: handleConfigSuccess,
          onConfigFail: handleFail,
          onAgentConfigFail(error) {
            console.warn(error)
          },
        })
      } catch (error) {
        console.error(error)
        wxConfigPromise = null
        reject(error)
      }
    })()
  })

  return wxConfigPromise
}
