// @ts-nocheck
import ProgressBar from '@/common/services/progress-bar'
import loginService from '@/login/login-service'
import store from '@/common/store'
import qs from 'qs'
import { router } from '../router-ready'

function openAsTrustId(url, srcTrustId, target = '_blank', notifyChangeKey) {
  // target如果是undefined，ie里打开的都是同一个窗口
  if (srcTrustId === null) {
    srcTrustId = undefined
  }
  if (!srcTrustId) {
    srcTrustId = loginService.getRunAs()
  }
  let query = qs.stringify({ srcTrustId, notifyChangeKey })
  query = query ? '?' + query : ''
  if (srcTrustId) {
    url = (url.startsWith('http') ? url : router.resolve(url).href)
      .replace('#/', `${query}#/`)
      .replace(/\/sd-frame\//, '/')
    if (store.state.sd.common.userInfo[srcTrustId]) {
      window.open(url, target)
    } else {
      // 这个兼职身份的信息还没有，发请求获取
      ProgressBar.start()
      Promise.all([loginService.getUserInfo(srcTrustId), loginService.getUserPerms(srcTrustId)])
        .then(() => {
          window.open(url, target)
        })
        .finally(() => ProgressBar.done())
    }
  } else {
    // sd-frame开头的本窗口打开
    if (url.startsWith('/sd-frame')) {
      router.push(url)
    } else {
      window.open(
        (url.startsWith('http') ? url : router.resolve(url).href).replace('#/', `${query}#/`),
        target
      )
    }
  }
}
export default openAsTrustId
