<script setup lang="ts">
import { inject, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Emitter } from 'mitt'
import { useI18n } from 'vue-i18n'
import PageNarBar from './components/page-narbar.vue'
import AgentConfig from './components/agent-config/agent-config.vue'
import AgentPublish from './components/agent-publish/agent-publish.vue'
import AgentAnalysis from './components/agent-analysis/agent-analysis.vue'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { fetchGetDebugApplicationInfo } from '@/apis/agent-application'

const { t } = useI18n()

const router = useRouter()

const personalAppConfigStore = usePersonalAppConfigStore()

const emitter = inject<Emitter<MittEvents>>('emitter')

const currentAgentAppTabKey = ref('')
const isAgentInitLoading = ref(false)

watch(
  () => currentAgentAppTabKey.value,
  () => {
    nextTick(() => {
      emitter?.emit('isGetAgentDetail')
    })
  },
)

onMounted(async () => {
  if (router.currentRoute.value.params.agentId) {
    await handleGetAgentDetail(router.currentRoute.value.params.agentId as string)
  }

  if (router.currentRoute.value.query.tabKey) {
    currentAgentAppTabKey.value = router.currentRoute.value.query.tabKey as string
  } else {
    currentAgentAppTabKey.value = 'config'
  }
})

onUnmounted(() => {
  personalAppConfigStore.resetPersonalAppConfigState()
})

async function handleGetAgentDetail(agentId: string) {
  isAgentInitLoading.value = true
  await fetchGetDebugApplicationInfo<PersonalAppConfigState>(agentId)
    .then((res) => {
      if (res.code === 0) {
        isAgentInitLoading.value = false
        personalAppConfigStore.updatePersonalAppConfigState({
          ...res.data,
          baseInfo: {
            ...res.data.baseInfo,
            agentAvatar:
              res.data.baseInfo.agentAvatar || 'https://gsst-poe-sit.gz.bcebos.com/data/20240911/1726041369632.webp',
          },
          databaseConfig: {
            ...res.data.databaseConfig,
            ids: res.data?.databaseConfig?.ids || [],
          },
        })
      }
    })
    .catch(() => {
      router.replace({ name: 'Root' })
    })
}

function handleChangeAgentAppTabKey(currentTabKey: string) {
  currentAgentAppTabKey.value = currentTabKey
}
</script>

<template>
  <main class="relative h-full min-w-[1280px]">
    <PageNarBar @change-agent-app-tab-key="handleChangeAgentAppTabKey" />

    <div class="h-content flex w-full flex-1">
      <div v-if="currentAgentAppTabKey === 'config'" class="flex h-full w-full flex-1">
        <AgentConfig />
      </div>

      <div v-if="currentAgentAppTabKey === 'publish'" class="flex h-full w-full flex-1">
        <AgentPublish />
      </div>

      <div v-if="currentAgentAppTabKey === 'analysis'" class="flex h-full w-full flex-1">
        <AgentAnalysis />
      </div>
    </div>

    <Transition name="mask" mode="out-in">
      <div
        v-show="isAgentInitLoading"
        class="z-100 bg-background-color absolute inset-0 flex flex-col items-center justify-center"
      >
        <n-spin :size="38" />

        <div class="text-theme-color mt-[30px] text-[14px]">{{ t('common_module.loading') }}...</div>
      </div>
    </Transition>
  </main>
</template>

<style lang="scss" scoped>
.mask-enter-active,
.mask-leave-active {
  transition-timing-function: ease-in-out;
  transition-duration: 0.2s;
  transition-property: opacity;
}

.mask-enter-from,
.mask-leave-to {
  opacity: 0;
}
</style>
