<script setup lang="ts">
import { reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { fetchGetAgentDataTrend } from '@/apis/agent-analyze'
import CustomEchart from '@/components/custom-echart/custom-echart.vue'
import { type EChartsOption } from '@/utils/echarts'
import AnalysisContentTitle from './analysis-content-title.vue'

enum RangType {
  week = 'week',
  month = 'month',
  customize = 'customize',
}

interface Props {
  channel: string[]
}

interface AgentTrendDateItem {
  date: string
  usersCount: number
  usageCount: number
  totalPoints: number
}

const { t } = useI18n()

const { params } = useRoute()

const props = defineProps<Props>()

const usageEchartRef = useTemplateRef<InstanceType<typeof CustomEchart> | null>('usageEchartRef')
const sendMessagesEchartRef = useTemplateRef<InstanceType<typeof CustomEchart> | null>('sendMessagesEchartRef')
const consumePointsEchartRef = useTemplateRef<InstanceType<typeof CustomEchart> | null>('consumePointsEchartRef')

const currentRangType = ref(RangType.week)
const selectDateRange = ref<[string, string]>(['', ''])
const rangTypeOptionList = [
  {
    label: t('common_module.last_week'),
    value: RangType.week,
  },
  {
    label: t('common_module.last_month'),
    value: RangType.month,
  },
  {
    label: t('common_module.custom'),
    value: RangType.customize,
  },
]

const usageEchartOption = reactive<EChartsOption>({
  ...defaultEchartOption(t('analysis_module.agent_users'), { x: 'date', y: 'usersCount' }),
})
const sendTimesEchartOption = reactive<EChartsOption>({
  ...defaultEchartOption(t('analysis_module.send_messages'), { x: 'date', y: 'usageCount' }),
})
const consumePointsEchartOption = reactive<EChartsOption>({
  ...defaultEchartOption(t('analysis_module.consume_points'), { x: 'date', y: 'totalPoints' }),
})

const disableDateRange = (ts: number, type: 'start' | 'end', range: [number, number] | null) => {
  if (type === 'start' && range !== null) {
    return range[1] - ts >= 86400000 * 365 || ts > Date.now()
  }
  if (type === 'end' && range !== null) {
    return ts - range[0] >= 86400000 * 365 || ts > Date.now()
  }

  return ts > Date.now()
}

watch(
  () => props.channel,
  () => {
    handleGetAgentDataTrend()
  },
)

watch(
  () => currentRangType.value,
  () => {
    currentRangType.value !== RangType.customize && handleGetAgentDataTrend()
  },
)

function defaultEchartOption(
  seriesName: string = '',
  encode: { x: string; y: string } = { x: 'date', y: 'usersCount' },
): EChartsOption {
  return {
    xAxis: {
      type: 'category',
    },
    yAxis: {},
    series: [
      {
        name: seriesName,
        encode,
        type: 'line',
        lineStyle: {
          color: '#000DFF',
        },
        label: {
          show: true,
          position: 'top',
        },
      },
    ],
    tooltip: {
      trigger: 'axis',
      textStyle: {
        fontWeight: 'normal',
      },
    },
    grid: {
      left: '58px',
      right: '40px',
      bottom: '20px',
    },
    color: ['#000DFF'],
  }
}

async function handleGetAgentDataTrend() {
  usageEchartRef.value?.echartShowLoading()
  sendMessagesEchartRef.value?.echartShowLoading()
  consumePointsEchartRef.value?.echartShowLoading()

  const res = await fetchGetAgentDataTrend<AgentTrendDateItem[]>({
    agentId: params.agentId as string,
    channel: props.channel,
    timeRange: {
      rangType: currentRangType.value,
      startTime: selectDateRange.value[0],
      endTime: selectDateRange.value[1],
    },
  })

  if (res.code === 0) {
    const dataSource = res.data.map((item) => ({
      date: item.date,
      usersCount: item.usersCount,
      usageCount: item.usageCount,
      totalPoints: item.totalPoints,
    }))

    usageEchartOption.dataset = {
      source: dataSource,
    }

    sendTimesEchartOption.dataset = {
      source: dataSource,
    }

    consumePointsEchartOption.dataset = {
      source: dataSource,
    }

    usageEchartRef.value?.echartHideLoading()
    sendMessagesEchartRef.value?.echartHideLoading()
    consumePointsEchartRef.value?.echartHideLoading()
  }
}

function handleUpdateRangType(rangType: string) {
  if (rangType !== RangType.customize) {
    selectDateRange.value = ['', '']
  }
}

async function handleUpdateDateRange(_value: [number, number], formattedValue: [string, string]) {
  if (formattedValue && formattedValue[0] && formattedValue[1]) {
    selectDateRange.value = formattedValue
    await handleGetAgentDataTrend()
  }
}
</script>

<template>
  <div class="flex h-[356px] w-full flex-col rounded-[20px] bg-white">
    <div class="mx-[34px] flex justify-between py-5">
      <AnalysisContentTitle :title="t('analysis_module.usage_trend_chart')" />

      <div class="flex gap-3">
        <n-select
          v-model:value="currentRangType"
          :options="rangTypeOptionList"
          class="w-[124px]! text-[#84868c]! time-range-select"
          @update:value="handleUpdateRangType"
        />

        <n-date-picker
          v-show="currentRangType === 'customize'"
          :is-date-disabled="disableDateRange"
          type="daterange"
          clearable
          class="w-[250px]! customize-date-picker"
          @update:value="handleUpdateDateRange"
        />
      </div>
    </div>

    <div class="mb-10 grid h-full grid-cols-3">
      <div class="text-font-color relative h-full w-full border-r border-r-[#E2E2E2]">
        <div class="absolute left-1/2 flex translate-x-[-50%] items-center gap-[5px]">
          <i class="iconfont icon-user text-[14px]" />
          <span>{{ t('analysis_module.agent_users') }}</span>
        </div>
        <div class="h-full w-full">
          <CustomEchart ref="usageEchartRef" :option="usageEchartOption" />
        </div>
      </div>

      <div class="text-font-color relative h-full border-r border-r-[#E2E2E2]">
        <div class="absolute left-1/2 flex translate-x-[-50%] items-center gap-[5px]">
          <i class="iconfont icon-send-times text-[14px]" />
          <span>{{ t('analysis_module.send_messages') }}</span>
        </div>
        <div class="h-full w-full">
          <CustomEchart ref="sendMessagesEchartRef" :option="sendTimesEchartOption" />
        </div>
      </div>

      <div class="relative h-full">
        <div class="absolute left-1/2 flex translate-x-[-50%] items-center gap-[5px]">
          <i class="iconfont icon-consume text-[14px]" />
          <span>{{ t('analysis_module.consume_points') }}</span>
        </div>
        <div class="h-full w-full">
          <CustomEchart ref="consumePointsEchartRef" :option="consumePointsEchartOption" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.time-range-select .n-base-selection),
:deep(.customize-date-picker.n-date-picker .n-input) {
  --n-height: 36px !important;
}
</style>
