import { browser, getRandomKey } from '@/helpers/utils'

export interface IPostMessage {
  api: string
  content?: any
}

/**
 * 劫持postMessage
 */

const originalPostMessage = window.postMessage

window.postMessage = (message: IPostMessage) => {
  // console.log('通过劫持', message)
  originalPostMessage(message, '*')
}

/**
 *
 * 目前已支持API
 *
 * openWebView
 *
 */

type CallBack = (evt?: IPostMessage) => void

// eslint-disable-next-line @typescript-eslint/no-empty-function
const loop = () => {}

const calls: { [key: string]: CallBack | CallBack[] } = {}

const browserInfo = browser()
if (browserInfo.isApp) {
  window.addEventListener('message', evt => {
    try {
      console.log(evt, 'message', evt.data)
      const data = evt.data
        ? typeof evt.data === 'object'
          ? evt.data
          : JSON.parse(evt.data)
        : {}
      const uuid = data.content?.uuid || data.uuid
      console.log(uuid, data.content, 'uuid')
      try {
        if (data.content) {
          data.content = JSON.parse(data.content)
        }
      } catch (error) {
        //
      }
      if (data?.content?.uuid) {
        console.log('data', data)
      }
      if (!uuid) {
        const keys = Object.keys(calls).filter(
          key => key.indexOf(data.api) === 0
        )
        console.log(keys, 'keys')
        console.log(data, 'data')
        for (const key of keys) {
          const callback = calls[key] || loop
          typeof callback === 'function' && callback(data)
        }
        return
      }
      const callId = data.content?.uuid || data.uuid || data.api + data.uuid
      const callback = calls[callId] || loop
      console.log(data, 'data')
      typeof callback === 'function' && callback(data)
    } catch (error) {
      console.error('通信消息解析错误', error)
    }
  })
}

const instance: any =
  (window as any).DAYA || (window as any).webkit?.messageHandlers?.DAYA

export const postMessage = (data: IPostMessage, callback?: CallBack) => {
  if (browserInfo.isApp) {
    const uuid = getRandomKey()
    calls[uuid] = callback || loop
    data.content = data.content ? { ...data.content, uuid } : { uuid }
    instance.postMessage(JSON.stringify(data))
    console.log('send:', JSON.stringify(data))
  }
}

// export const listenerMessage = (api: string, callback: CallBack) => {
//   console.log(browserInfo, 'browserInfo', api, 'api', callback)
//   if (browserInfo.isApp) {
//     const uuid = api
//     if (!calls[uuid]) {
//       calls[uuid] = []
//     }
//     ;(calls[uuid] as CallBack[]).push(callback || loop)
//   }
// }
export const listenerMessage = (api: string, callback: CallBack) => {
  if (browserInfo.isApp) {
    const uuid = api + getRandomKey()
    calls[uuid] = callback || loop
  }
}

export const removeListenerMessage = (api: string, callback: CallBack) => {
  if (browserInfo.isApp) {
    const uuid = api
    if (Array.isArray(calls[uuid])) {
      const indexOf = (calls[uuid] as CallBack[]).indexOf(callback)
      ;(calls[uuid] as CallBack[]).splice(indexOf, 1)
    }
  }
}

export const promisefiyPostMessage = (
  data: IPostMessage
): Promise<IPostMessage | undefined> => {
  return new Promise(resolve => {
    postMessage(data, res => resolve(res))
  })
}
