<script setup lang="ts">
import { reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import ContentTitle from '../../components/content-title.vue'
import { IPlatformPointTrendItem } from '../../type'
import { type EChartsOption } from '@/utils/echarts'
import CustomEchart from '@/components/custom-echart/custom-echart.vue'
import DataSelectSearch from '@/components/date-select-search/data-select-search.vue'
import { RangType } from '@/components/date-select-search/type.d'
import { ChannelText, ChannelType } from '@/enums/channel'
import { fetchGetPlatformPointTrend } from '@/apis/statistic'

interface Props {
  channel: string[]
}

const { t } = useI18n()

const props = defineProps<Props>()

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

const currentTime = ref<RangType>(RangType.week)
const selectDateRange = ref<[string, string]>(['', ''])

const defaultEchartOption: EChartsOption = {
  legend: {
    top: '36px',
  },
  tooltip: {
    trigger: 'axis',
    textStyle: {
      fontWeight: 'normal',
    },
  },
  xAxis: { type: 'category' },
  yAxis: { gridIndex: 0 },
  grid: { top: '100px', left: '110px', right: '70px', bottom: '40px' },
  color: ['#e94540', '#6ea2ff', '#ba68ff', '#ff61c1', '#2db70e', '#eda030'],
  series: [
    {
      type: 'line',
      smooth: true,
      seriesLayoutBy: 'row',
      emphasis: { focus: 'series' },
    },
    {
      type: 'line',
      smooth: true,
      seriesLayoutBy: 'row',
      emphasis: { focus: 'series' },
    },
    {
      type: 'line',
      smooth: true,
      seriesLayoutBy: 'row',
      emphasis: { focus: 'series' },
    },
    {
      type: 'line',
      smooth: true,
      seriesLayoutBy: 'row',
      emphasis: { focus: 'series' },
    },
    {
      type: 'line',
      smooth: true,
      seriesLayoutBy: 'row',
      emphasis: { focus: 'series' },
    },
    {
      type: 'line',
      smooth: true,
      seriesLayoutBy: 'row',
      emphasis: { focus: 'series' },
    },
  ],
}

const pointUsageTrendEchartsOption = reactive<EChartsOption>({ ...defaultEchartOption })

watch(
  () => props.channel,
  () => {
    handleGetPlatformPointTrend(currentTime.value, selectDateRange.value[0], selectDateRange.value[1])
  },
)

async function handleGetPlatformPointTrend(rangType: RangType, startTime: string, endTime: string) {
  if (!props.channel.length) {
    return
  }

  currentTime.value = rangType
  selectDateRange.value = [startTime, endTime]
  pointUsageTrendRef.value?.echartShowLoading()

  const res = await fetchGetPlatformPointTrend<IPlatformPointTrendItem[]>({
    channel: props.channel,
    timeRange: {
      rangType,
      startTime,
      endTime,
    },
  })

  if (res.code === 0) {
    const dataSourceSort = handleDataSourceSort(res.data)

    const dateList = [...new Set(dataSourceSort.flatMap((item) => item.pointUsages.map((usage) => usage.date)))].sort()

    const dataSource: [string[], ...[string, ...number[]][]] = [['product', ...dateList]]

    dataSourceSort.forEach((item) => {
      const row: [string, ...number[]] = [t(ChannelText[item.channel])]

      dateList.forEach((date) => {
        const count = item.pointUsages.find((usage) => usage.date === date)?.count || 0
        row.push(count)
      })

      dataSource.push(row)
    })

    pointUsageTrendEchartsOption.dataset = {
      source: dataSource,
    }

    pointUsageTrendRef.value?.echartHideLoading()
  }
}

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

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

<template>
  <div class="relative h-[455px] w-full rounded-[20px] bg-white py-5">
    <div class="absolute left-0 right-0 z-10">
      <div class="mx-[34px] flex items-start justify-between">
        <ContentTitle :title="t('statistic_module.platform_point_trend')" />

        <DataSelectSearch @update-search-list="handleGetPlatformPointTrend" />
      </div>
    </div>

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