<script setup lang="ts">
import { computed, h, onMounted, readonly, ref, watch } from 'vue'
import { NTag, TreeSelectOption } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { fetchGetGeneralUsageData } from '@/apis/agent-analyze'
import { ChannelType } from '@/enums/channel'
import { useSystemLanguageStore } from '@/store/modules/system-language'
import UsagePanelItem from './components/usage-panel-item.vue'
import UsageTrendChart from './components/usage-trend-chart.vue'
import ChannelUserComparisonChart from './components/channel-user-comparison-chart.vue'
import ChannelUsageComparisonChart from './components/channel-usage-comparison-chart.vue'
import { UsageItemInfo } from './types'

const { t } = useI18n()

const { params } = useRoute()

const systemLanguageStore = useSystemLanguageStore()

const channelOptionList = [
  {
    label: t('analysis_module.agent_debug'),
    key: 'agent_preview',
    children: [
      {
        label: t('analysis_module.debug'),
        key: ChannelType.preview,
      },
      {
        label: t('analysis_module.multi_debug'),
        key: ChannelType.multi_preview,
      },
    ],
  },
  {
    label: t('analysis_module.usage_channel'),
    key: 'usage_channel',
    children: [
      {
        label: t('analysis_module.index'),
        key: ChannelType.index,
      },
      {
        label: t('analysis_module.agent_square'),
        key: ChannelType.mall,
      },
      {
        label: t('analysis_module.link_share'),
        key: ChannelType.link_share,
      },
      {
        label: t('analysis_module.api'),
        key: ChannelType.api,
      },
    ],
  },
]

const channelGroupList = readonly(channelOptionList.map((channelItem) => channelItem.key))
const allChannelList = handleGetAllChannelList(channelOptionList)
const selectChannelList = ref<string[]>([])
const generalUsageList = ref<UsageItemInfo[]>([])

const isEnLanguage = computed(() => {
  return systemLanguageStore.currentLanguageInfo.key === 'en'
})

watch(
  () => selectChannelList.value,
  () => {
    handleGetGeneralUsageData()
  },
)

onMounted(() => {
  selectChannelList.value = allChannelList
})

async function handleGetGeneralUsageData() {
  const res = await fetchGetGeneralUsageData<UsageItemInfo[]>(params.agentId as string, selectChannelList.value)

  if (res.code === 0) {
    generalUsageList.value = res.data
  }
}

function handleUpdateChannelList(channelList: string[]) {
  if (channelList.length === 0) {
    selectChannelList.value = allChannelList
    return
  }

  selectChannelList.value = channelList
}

function handleRenderChannelLabel({ option }: { option: TreeSelectOption }) {
  return h('span', { style: { marginRight: '24px' } }, { default: () => option.label as string })
}

function handleRenderSelectChannel({ option }: { option: TreeSelectOption }) {
  if (
    selectChannelList.value.length === allChannelList.length &&
    selectChannelList.value.every((item) => allChannelList.includes(item))
  ) {
    return option.key === allChannelList?.[0]
      ? h('span', { class: 'mb-[3px]' }, t('analysis_module.all_channels'))
      : null
  }

  return h(NTag, { class: 'mb-[3px] px-[10px]!' }, { default: () => option.label as string })
}

function handleGetAllChannelList(options: TreeSelectOption[]) {
  let channelList: string[] = []

  function recurseChannelList(channels: TreeSelectOption[]) {
    if (Array.isArray(channels)) {
      channels.forEach((channel) => {
        if (!channel.children || channel.children.length === 0) {
          channelList.push(channel.key as string)
        } else {
          recurseChannelList(channel.children)
        }
      })
    }
  }

  recurseChannelList(options)

  return channelList
}
</script>

<template>
  <div class="mx-auto flex flex-1 justify-center bg-[#F3F5F8]">
    <div class="w-full max-w-[1920px] overflow-y-auto bg-[#F3F5F8] p-6">
      <div class="mb-5 flex justify-end pr-[34px]">
        <div class="max-w-[300px]" :class="isEnLanguage ? 'min-w-[124px]' : 'min-w-[154px]'">
          <n-tree-select
            v-model:value="selectChannelList"
            multiple
            cascade
            checkable
            check-strategy="child"
            placement="bottom-end"
            max-tag-count="responsive"
            class="tree-tag"
            :options="channelOptionList"
            :menu-props="{ style: { marginTop: '6px', borderRadius: '5px' } }"
            :consistent-menu-width="false"
            :ellipsis-tag-popover-props="{ show: false }"
            :default-expanded-keys="channelGroupList"
            :render-label="handleRenderChannelLabel"
            :render-tag="handleRenderSelectChannel"
            @update:value="handleUpdateChannelList"
          >
          </n-tree-select>
        </div>
      </div>

      <div class="gap-4.5 flex h-[168px] w-full">
        <div v-for="(usageItem, index) in generalUsageList" :key="index" class="h-full flex-1 rounded-[20px] bg-white">
          <UsagePanelItem :usage-item="usageItem" />
        </div>
      </div>

      <div class="mt-5 w-full">
        <UsageTrendChart :channel="selectChannelList" />
      </div>

      <div class="mt-5 grid h-[330px] w-full grid-cols-2 gap-5">
        <div class="h-full">
          <ChannelUserComparisonChart />
        </div>

        <div class="h-full">
          <ChannelUsageComparisonChart />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@include custom-scrollbar(6px);

:deep(.tree-tag .n-base-selection) {
  --n-height: 36px !important;
  --n-color: #f3f5f8 !important;
  --n-color-active: #f3f5f8 !important;
  --n-border: 1px solid #ccc !important;

  .n-base-selection-tag-wrapper .n-tag {
    margin-right: 10px !important;
    background: #fff !important;
    border-radius: 5px !important;

    --n-border: none !important;
  }

  .n-base-selection-tag-wrapper {
    padding: 0;
  }
}
</style>
