import WujieVue from 'wujie-vue3'
import useMicro from '@fskj-admin/micro'
import { microList } from '@/config/mainMicro'
import { useUserStore } from '@/stores/user'

export const plugins = [
  {
    cssBeforeLoaders: [
      // 强制使子利用body定位是relative
      { content: 'body{position: relative !important}' }
    ]
  },
  {
    jsLoader: (code: any) => {
      // 替换popper.js内计算偏左侧偏移量
      const codes = code.replace(
        'left: elementRect.left - parentRect.left',
        'left: fixed ? elementRect.left : elementRect.left - parentRect.left'
      )
      // 替换popper.js内右侧偏移量
      return codes.replace('popper.right > data.boundaries.right', 'false')
    }
  }
]

// 主服务初始化
export const micro = useMicro(WujieVue)
export const initMicro = () => {
  micro.initMainMicro(microList, (bus: any) => {
    const userStore = useUserStore()
    // 监听退出登录
    bus.$on('logout', () => {
      userStore.logout()
    })

    // 监听token变化，同步给子应用
    watch(
      () => userStore.token,
      () => {
        WujieVue.bus.$emit('TOKEN', userStore.token)
      },
      {
        immediate: true
      }
    )
  })
}

export const isMicro = micro.isMicro

export const logout = () => {
  if (isMicro) {
    window.$wujie?.bus.$emit('logout')
  } else {
    const userStore = useUserStore()
    userStore.logout()
  }
}
