import qs from 'qs'
import MD5 from 'crypto-js/md5'
import openAsTrustId from './open-as-trust-id'
const promiseMap = {}
const funMap = {}
window.addEventListener(
  'message',
  (event) => {
    const data = event.data
    if (data.type === 'updateTask') {
      promiseMap[data.handler]?.(data.postData)
      delete promiseMap[data.handler]
      funMap[data.handler]?.(data.postData)
    }
  },
  false
)
function shouldUpdateTask(key) {
  return new Promise((resolve, reject) => {
    promiseMap[key] = resolve
  })
}

function waitForChanged(url, srcTrustId, target) {
  const notifyChangeKey = MD5(url).toString()
  openAsTrustId(url, srcTrustId, target || notifyChangeKey, notifyChangeKey)
  return shouldUpdateTask(notifyChangeKey)
}
function subscribeChange({ url, srcTrustId, target, callback }) {
  const notifyChangeKey = MD5(url).toString()
  openAsTrustId(url, srcTrustId, target || notifyChangeKey, notifyChangeKey)
  funMap[notifyChangeKey] = callback
}
function notifyChange(key, flag = false) {
  const query = qs.parse(window.location?.search?.replace('?', ''))
  try {
    // @ts-ignore
    window?.opener?.sdPostMessage({
      type: 'updateTask',
      postData: arguments[1] || arguments[0],
      handler: query?.notifyChangeKey,
    })
  } catch (e) {
    window?.opener?.postMessage(
      {
        type: 'updateTask',
        postData: arguments[1] || arguments[0],
        handler: query?.notifyChangeKey,
      },
      '*' // 跨域通知，IE现不支持
    )
  }
}
var crossWindowWatcher = { shouldUpdateTask, waitForChanged, notifyChange, subscribeChange }
export default crossWindowWatcher
