<template>
  <div class="micro-app-container">
    <micro-app
      iframe
      name="label-app"
      :url="baseUrl"
      @mounted="onMicroAppMounted"
      @unmount="onMicroAppUnmount"
      @error="onMicroAppError"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import microApp from '@micro-zoe/micro-app'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 子应用地址
const baseUrl = ref('')

// 开发环境子应用地址
const devUrl = 'https://aistudio.ngsk.tech:7001/labelapp/'

onMounted(() => {
  // 根据路由构建子应用URL
  const subPath = route.params.pathMatch
    ? Array.isArray(route.params.pathMatch)
      ? route.params.pathMatch.join('/')
      : route.params.pathMatch
    : ''

  baseUrl.value = devUrl + subPath
})

// 处理子应用数据
const handleDataListener = (data: any) => {
  console.log('[主应用] 收到子应用数据:', data)

  switch (data.type) {
    case 'RETURN_TO_TASK_LIST':
      router.push('/label-app')
      break

    case 'BACK':
      router.back()
      break

    case 'SAVE':
      if (data.status) {
        ElMessage.success(data.msg || '保存成功')
      } else {
        ElMessage.error(data.msg || '保存失败')
      }
      break

    default:
      break
  }
}

const onMicroAppMounted = () => {
  console.log('[主应用] label-app 已挂载')

  // 向子应用发送初始化数据
  microApp.setData('label-app', {
    type: 'INIT',
    storage_dataset_base_url: localStorage.getItem('storage_dataset_base_url')
  })

  // 监听子应用数据
  microApp.addDataListener('label-app', handleDataListener)
}

const onMicroAppUnmount = () => {
  console.log('[主应用] label-app 已卸载')
}

const onMicroAppError = (e: any) => {
  console.error('[主应用] label-app 加载错误:', e)
  ElMessage.error('子应用加载失败')
}

onUnmounted(() => {
  microApp.clearDataListener('label-app')
})
</script>

<style scoped>
.micro-app-container {
  height: 100%;
  width: 100%;
}

.micro-app-container micro-app {
  display: block;
  height: 100%;
  width: 100%;
}
</style>
