<script setup lang="ts">
import { onMounted, reactive, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { fetchGetMonthConsumePointCount, fetchGetMonthSendMessageCount } from '@/apis/agent-analyze'
import CustomEchart from '@/components/custom-echart/custom-echart.vue'
import { ChannelText, ChannelType } from '@/enums/channel'
import { type EChartsOption } from '@/utils/echarts'
import AnalysisContentTitle from './analysis-content-title.vue'
import { ChannelCountItem } from '../types'

const { t } = useI18n()

const { params } = useRoute()

const channelUsageChartRef = useTemplateRef<InstanceType<typeof CustomEchart> | null>('channelUsageChartRef')

const defaultEchartOption: EChartsOption = {
  title: [
    {
      subtext: t('analysis_module.send_messages'),
      left: '26.8%',
      top: '175px',
      subtextStyle: {
        fontSize: 14,
        color: '#333333',
      },
      textAlign: 'center',
    },
    {
      subtext: t('analysis_module.consume_points'),
      left: '72%',
      top: '175px',
      subtextStyle: {
        fontSize: 14,
        color: '#333333',
      },
      textAlign: 'center',
    },
  ],
  legend: {
    top: '20px',
    right: '54px',
  },
  color: ['#454FFF', '#00C2FF'],
  tooltip: {
    trigger: 'item',
    textStyle: {
      fontWeight: 'normal',
    },
  },
  series: [
    {
      type: 'pie',
      top: '60px',
      radius: ['50%', '70%'],
      center: ['50%', '50%'],
      encode: { value: 'count1', itemName: 'channel' },
      clockwise: false,
      label: {
        position: 'outer',
        alignTo: 'labelLine',
        formatter: '{d}%',
        bleedMargin: 5,
      },
      left: 0,
      right: '45%',
    },
    {
      type: 'pie',
      top: '60px',
      radius: ['50%', '70%'],
      center: ['50%', '50%'],
      encode: { value: 'count2', itemName: 'channel' },
      clockwise: false,
      label: {
        position: 'outer',
        alignTo: 'labelLine',
        formatter: '{d}%',
        bleedMargin: 5,
      },
      left: '45%',
      right: 0,
    },
  ],
}
const channelUsageChartOption = reactive<EChartsOption>({ ...defaultEchartOption })

const sendMessageChannelCountList = ref<ChannelCountItem[]>([])
const consumePointChannelCountList = ref<ChannelCountItem[]>([])

onMounted(() => {
  handleGetMonthChannelProportion()
})

async function handleGetMonthChannelProportion() {
  channelUsageChartRef.value?.echartShowLoading()

  await handleGetMonthSendMessageCount()
  await handleGetMonthConsumePointCount()

  const channelMap = new Map(sendMessageChannelCountList.value.map((item) => [item.channel, item]))

  const dataSource = consumePointChannelCountList.value.map((consumePointChannelCountItem) => {
    const sendMessageChannelCountItem = channelMap.get(consumePointChannelCountItem.channel)

    return {
      channel: consumePointChannelCountItem.channel,
      count1: parseFloat((sendMessageChannelCountItem?.count || 0).toFixed(2)),
      count2: parseFloat((consumePointChannelCountItem?.count || 0).toFixed(2)),
    }
  })

  const newDataSource = handleDataSourceSort(dataSource)

  newDataSource.forEach((item) => {
    ;(item.channel as string) = t(ChannelText[item.channel])
  })

  channelUsageChartOption.dataset = {
    source: dataSource,
  }

  channelUsageChartRef.value?.echartHideLoading()
}

function handleDataSourceSort(dataSource: { channel: ChannelType; count1: number; count2: number }[]) {
  const channelSortMap = {
    [ChannelType.link_share]: 1,
    [ChannelType.mall]: 2,
    [ChannelType.index]: 3,
    [ChannelType.api]: 4,
    [ChannelType.preview]: 5,
    [ChannelType.multi_preview]: 6,
  }

  return dataSource.sort((a, b) => channelSortMap[a.channel] - channelSortMap[b.channel])
}

async function handleGetMonthSendMessageCount() {
  const res = await fetchGetMonthSendMessageCount<ChannelCountItem[]>(params.agentId as string, [
    ChannelType.link_share,
    ChannelType.mall,
  ])

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

async function handleGetMonthConsumePointCount() {
  const res = await fetchGetMonthConsumePointCount<ChannelCountItem[]>(params.agentId as string, [
    ChannelType.link_share,
    ChannelType.mall,
  ])

  if (res.code === 0) {
    consumePointChannelCountList.value = res.data
  }
}
</script>

<template>
  <div class="relative h-full w-full rounded-[20px] bg-white">
    <div class="z-99 absolute left-[34px] top-5 mr-[270px]">
      <AnalysisContentTitle
        :title="t('analysis_module.monthly_proportion_of_messages_sent_and_points_consumed_by_channel')"
      />
    </div>

    <div class="h-full w-full">
      <CustomEchart ref="channelUsageChartRef" :option="channelUsageChartOption" />
    </div>
  </div>
</template>
