import { getAllQueryString } from '@/utils/url-utils.ts'

/**
 * OpenInstall sdk 用于上报h5邀请参数
 * 自动注册openinstall sdk 挂在到window对象上 通过window.OI_SDK访问
 * sdk初始化时会自动检索url上的参数并作为拉起下载或唤醒app时的参数
 */
const script = document.createElement('script')
script.type = 'text/javascript'
script.charset = 'UTF-8'
script.src = 'https://web.cdn.openinstall.io/openinstall.js'
document.head.appendChild(script)

let resolveReady: (sdk: OpenInstallSdk) => void
window.OI_SDK_PROMISE = new Promise((resolve) => {
  resolveReady = resolve
})

script.addEventListener('load', () => {
  window.OI_SDK = new OpenInstallSdk(resolveReady)
})

class OpenInstallSdk {
  public urlQuery: any // openinstall.js中提供的api，解析当前网页url中的查询参数并对data进行赋值

  public OI: Record<string, any> // openinstall 实例

  public isReady = false

  constructor(private onReadyCallback?: (sdk: OpenInstallSdk) => void) {
    this.OI = {}
    this.urlQuery = window.OpenInstall.parseUrlParams()
    const ic = getAllQueryString('ic') || sessionStorage.getItem('ic') || 'uSSfg1Y1vt'
    if (ic) {
      this.urlQuery = {
        platform: 'download',
        inviteCode: ic,
      }
    }
    this.init()
  }

  async init() {
    const self = this
    try {
      this.OI = new window.OpenInstall(
        {
          appKey: 'alf57p',
          onready: function () {
            // 初始化成功回调方法。当初始化完成后，会自动进入
            // 注意：此时的 this 是 OpenInstall 的原始实例对象 (m)
            const m = this
            // m.schemeWakeup() // 尝试使用scheme打开App（主要用于Android以及iOS的QQ环境中）

            const button = document.getElementById('downloadButton_apple')
            const button_mac = document.getElementById('downloadButton_mac')
            const button1 = document.getElementById('downloadButton_android')
            const ic = getAllQueryString('ic') || 'uSSfg1Y1vt'

            const clickHandler = function () {
              if (ic) {
                m.wakeupOrInstall({ data: { platform: 'download', inviteCode: ic } })
              } else {
                m.wakeupOrInstall()
              }
              return false
            }

            if (button) button.onclick = clickHandler
            if (button_mac) button_mac.onclick = clickHandler
            if (button1) button1.onclick = clickHandler

            // 标记就绪并触发 Promise
            self.isReady = true
            if (self.onReadyCallback) {
              self.onReadyCallback(self)
            }
          },
        },
        this.urlQuery,
      ) // 初始化时传入data，作为一键拉起/App传参安装时候的参数
    } catch (e) {
      console.log(e, 'OpenInstall——sdk初始化失败')
    }
  }
}
