/*
 * @Author: Haijun Zhang
 * @Date: 2022-11-10 10:46:38
 * @LastEditTime: 2023-09-06 15:04:22
 * @LastEditors: Haijun Zhang
 * @Description:
 * @FilePath: \cmp-cored:\workspace\micro-web\main-web-qiankun\src\core\config.ts
 */
import mainRouter from '@/router/index'
import axios from 'axios'
import store from '../store'

export type IDeployConfig = {
  apps: IAppConfig[]
  plugins: IAppConfig[]
  deployAddress: string
  deployPort: number | { [key: string]: number }
  homePath: string
}
export type IAppConfig = {
  name: string
  entry?: string
  hasPlugin?: boolean
  activeRule?: string | string[]
}
function getAppDeployDir(name: string) {
  if (name.includes('-plugin')) return 'plugins'
  return 'sub-app'
}
export async function getMicroApp() {
  const { protocol, hostname, port } = location
  const prefix = `${protocol}//${hostname}`
  const {
    data: { deployAddress = prefix, homePath = '/sms-web/resource_dashboard', deployPort = Number(port) || (protocol === 'https:' ? 443 : 80), apps }
  }: {
    data: IDeployConfig
  } = await axios.get('/cof-web/app.json')
  // const port: number = isNaN(deployPort as number) ? (deployPort as any)[hostname] : deployPort
  const hasCos = Boolean(apps.find(item => item.name === 'cos-web'))
  store.commit('SET_APP_CONFIGS', { hasCos, homePath })
  return apps.map((item: IAppConfig) => {
    const { name, activeRule = `/${name}`, hasPlugin, entry = `${deployAddress}:${deployPort}/${getAppDeployDir(name)}/${name}/` } = item
    return {
      name,
      entry,
      container: '#subapp-viewport',
      activeRule: (location: any) => {
        if (hasPlugin && location.pathname.includes('-plugin')) return false
        return location.pathname.startsWith(activeRule)
      },
      props: {
        appPath: entry,
        mainRouter
      }
    }
  })
}
