<script setup lang="ts">
import { computed, h, onMounted, readonly, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { DropdownOption } from 'naive-ui'
import { sidebarMenus } from '@/router/index'
import CustomIcon from '@/components/custom-icon/custom-icon.vue'
import { useUserStore } from '@/store/modules/user'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { formatDateTime } from '@/utils/date-formatter'
import { fetchPublishApplication } from '@/apis/agent-application'

const defaultAvatar = 'https://gsst-poe-sit.gz.bcebos.com/data/20240910/1725952917468.png'

interface Emits {
  (e: 'changeAgentAppTabKey', value: string): void
}

const emit = defineEmits<Emits>()

const router = useRouter()

const userStore = useUserStore()
const personalAppConfigStore = usePersonalAppConfigStore()

const avatarOptions = readonly([
  {
    label: '退出登录',
    key: 'logout',
    icon: () => h(CustomIcon, { icon: 'teenyicons:logout-solid' }),
  },
])

const modifiedTime = ref(personalAppConfigStore.modifiedTime)

const isInitGetAgentAppDetail = ref(false)

const isUpdateAgentAppConfig = ref(false)

const currentAgentAppTabKey = ref('config')

const publishBtnloading = ref(false)

const agentAppOptionList = [
  {
    value: 'config',
    label: '配置',
  },
  {
    value: 'publish',
    label: '发布',
  },
]

const personalAppConfig = computed(() => personalAppConfigStore.$state)

const menuOptions = computed(() => {
  return sidebarMenus.map((item) => {
    return {
      label: item.label,
      key: item.key,
      routeName: item.routeName,
      icon: () => h(CustomIcon, { icon: item.icon || 'icon-home' }),
    }
  })
})

const isShowModifiedTime = computed(() => {
  return isUpdateAgentAppConfig.value && personalAppConfigStore.baseInfo.agentId
})

const publishBtnText = computed(() => {
  return personalAppConfigStore.baseInfo.agentPublishStatus === 'publish' ? '更新发布' : '发 布'
})

const isShowPublishBtn = computed(() => {
  return currentAgentAppTabKey.value === 'config'
})

const isAllowClickPublish = computed(() => {
  return personalAppConfigStore.baseInfo.agentId && personalAppConfigStore.baseInfo.agentPublishStatus === 'publish'
})

watch(
  () => personalAppConfig.value,
  () => {
    if (isInitGetAgentAppDetail.value) {
      isInitGetAgentAppDetail.value = false
      return
    }

    modifiedTime.value = new Date()
    !isUpdateAgentAppConfig.value && (isUpdateAgentAppConfig.value = true)
  },
  { deep: true },
)

onMounted(() => {
  if (router.currentRoute.value.params.agentId) {
    isInitGetAgentAppDetail.value = true
  }

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

function handleMenuSelect(_key: number, option: DropdownOption) {
  router.replace({ name: option.routeName as string })
}

function handleBackPreviousPage() {
  router.go(-1)
}

function handleDropdownSelect(key: number) {
  if (key === 1) {
    userStore.logout().then(() => {
      router.push({ name: 'Login' })
    })
  }
}

function handleSwtichAgentAppOption(currentTabKey: string) {
  if (!isAllowClickPublish.value) return

  currentAgentAppTabKey.value = currentTabKey

  router.replace({
    name: router.currentRoute.value.name as string,
    query: { tabKey: currentTabKey },
    params: { ...router.currentRoute.value.params },
  })

  emit('changeAgentAppTabKey', currentTabKey)
}

async function handlePublishApplication() {
  if (!personalAppConfig.value.baseInfo.agentTitle) {
    window.$message.warning('应用名称不能为空')
    return
  }

  publishBtnloading.value = true

  const res = await fetchPublishApplication(personalAppConfig.value).finally(() => (publishBtnloading.value = false))

  if (res.code === 0) {
    window.$message.success('发布成功')

    currentAgentAppTabKey.value = 'publish'
    router.replace({
      name: router.currentRoute.value.name as string,
      query: { tabKey: 'publish' },
      params: { agentId: personalAppConfig.value.baseInfo.agentId },
    })

    personalAppConfig.value.baseInfo.agentPublishStatus = 'publish'

    emit('changeAgentAppTabKey', 'publish')
  }
}
</script>

<template>
  <header class="h-navbar flex w-full items-center justify-between bg-[#f2f5f9] px-5 shadow-[inset_0_-1px_#e8e9eb]">
    <div class="flex flex-1 items-center">
      <NDropdown trigger="hover" :options="menuOptions" @select="handleMenuSelect">
        <CustomIcon
          icon="weui:back-outlined"
          class="hover:text-theme-color mr-5 outline-none"
          @click="handleBackPreviousPage"
        />
      </NDropdown>

      <div class="flex flex-col items-start justify-center">
        <NPopover trigger="hover">
          <template #trigger>
            <span class="font-500 line-clamp-1 max-w-[200px] break-words text-base text-[#000]">
              {{ personalAppConfigStore.baseInfo.agentTitle }}
            </span>
          </template>
          <span>{{ personalAppConfigStore.baseInfo.agentTitle }}</span>
        </NPopover>

        <div class="flex items-center text-xs">
          <NPopover trigger="hover">
            <template #trigger>
              <span class="line-clamp-1 max-w-[200px] break-words text-[#84868c]">
                {{ personalAppConfigStore.baseInfo.agentDesc || '暂无描述' }}
              </span>
            </template>
            <span>{{ personalAppConfigStore.baseInfo.agentDesc || '暂无描述' }}</span>
          </NPopover>

          <div
            v-show="personalAppConfigStore.baseInfo.agentId"
            class="ml-3 h-5 rounded bg-white px-2 leading-5 text-[#5c5f66]"
          >
            已变更
          </div>
          <div v-show="isShowModifiedTime" class="ml-3 h-5 rounded-md bg-white px-2 leading-5 text-[#151b26]">
            自动保存于 {{ formatDateTime(modifiedTime, 'HH:mm:ss') }}
          </div>
        </div>
      </div>
    </div>

    <div class="flex h-[38px] rounded-lg bg-[#e3e8f0] p-0.5">
      <div
        v-for="optionItem in agentAppOptionList"
        :key="optionItem.value"
        :value="optionItem.value"
        :label="optionItem.label"
        class="flex w-20 items-center justify-center rounded-lg"
        :class="[
          currentAgentAppTabKey === optionItem.value ? 'text-theme-color bg-white' : 'text-[#84868c]',
          isAllowClickPublish ? 'hover:text-theme-color cursor-pointer' : 'cursor-not-allowed',
        ]"
        @click="handleSwtichAgentAppOption(optionItem.value)"
      >
        <NPopover v-if="!isAllowClickPublish" trigger="hover">
          <template #trigger>
            {{ optionItem.label }}
          </template>
          <span>请先完成发布</span>
        </NPopover>
        <div v-if="isAllowClickPublish">{{ optionItem.label }}</div>
      </div>
    </div>

    <div class="flex flex-1 items-center justify-end">
      <NButton
        v-show="isShowPublishBtn"
        type="primary"
        class="h-[32px]! min-w-20! rounded-md!"
        :disabled="!personalAppConfig.baseInfo.agentId"
        :loading="publishBtnloading"
        @click="handlePublishApplication"
      >
        {{ publishBtnText }}
      </NButton>
      <NDropdown trigger="click" :options="avatarOptions" @select="handleDropdownSelect">
        <div class="ml-10 flex h-full cursor-pointer items-center">
          <NAvatar round :size="30" object-fit="cover" :src="userStore.userInfo.avatarUrl || defaultAvatar" />
        </div>
      </NDropdown>
    </div>
  </header>
</template>
