import API from '@/api'
import storage from '../utils/storage'

export default {
  data() {
    return {
      plugins: {},
      pluginList: [],
      inited: false,
      pluginConfigMap: {
        fpsController: {
          icon: 'kexianchengyun',
          config: {},
        },
        miniMap: {
          icon: 'ditu',
          config: {
            layout: [260, 50],
          },
        },
      },
    }
  },
  computed: {
    parsedPluginConfigMap() {
      const parsedMap = {}
      for (let i in this.pluginConfigMap) {
        parsedMap[i] = this.pluginConfigMap[i]
      }
      return parsedMap
    },
  },
  methods: {
    change(data) {
      const plugin = this.pluginList.find((item) => item.name === data.name)
      if (!plugin) return
      plugin.active = !plugin.active

      if (plugin.active) {
        app.loadBundle(
          plugin.usePath,
          this.pluginConfigMap[plugin.name]?.config
        )
      } else {
        app.unloadBundle(plugin.usePath)
      }

      this.storageActivePlugin()
    },
    storageActivePlugin() {
      const activePlugins = this.pluginList.reduce((a, b) => {
        if (b.active) {
          a[b.name] = true
        }
        return a
      }, {})

      storage.setItem('activePlugins', activePlugins)
    },
    async getPluginList() {
      try {
        const res = await API.getLocalPluginList()
        res.items.forEach((item) => {
          item.active = false
          item.icon = this.parsedPluginConfigMap[item.name]?.icon
        })

        // 设置 icon
        this.pluginList = res.items
      } catch (e) {
        console.warn(`获取插件列表失败`, e)
      }
    },
    initPluginList() {
      const activePlugins = storage.getItem('activePlugins')

      if (activePlugins) {
        Object.keys(activePlugins).forEach((name) => {
          this.change({ name })
        })
      }
    },
  },
  async mounted() {
    await this.getPluginList()

    this.initPluginList()

    this.inited = true
  },
}
