<template>
  <div>
    <div v-if="loading" class="flex justify-center items-center h-64">
      <span>加载中...</span>
    </div>
    <div v-else>
          <EchartsUI ref="chartRef" class="w-full h-80" />
      <div class="mt-4 flex justify-center">
        <Button 
          type="primary" 
          @click="loadMore" 
          :loading="loadingMore" 
          :disabled="!hasMore"
        >
          {{ loadingMore ? '加载中...' : '加载更多' }}
        </Button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import { AnalysisChartCard } from '@vben/common-ui';
import { Button } from 'ant-design-vue';
import { homePage } from '#/api';
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

const loading = ref(false);
const loadingMore = ref(false);
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
const liveRoomStatistics = ref<any[]>([]);
const hasMore = ref(true);
const currentPage = ref(1);

onMounted(() => {
  getLiveRoomStatistics(true);
});

async function getLiveRoomStatistics(init = false) {
  if (init) {
    loading.value = true;
    currentPage.value = 1;
    liveRoomStatistics.value = [];
  } else {
    loadingMore.value = true;
  }
  
  try {
    const res = await homePage.getLiveRoomStatistics({
      pageNum: currentPage.value,
      pageSize: 10
    });
    
    if (!res.error && res.data) {
      const data = res.data;
      if (init) {
        liveRoomStatistics.value = data.liveRoomStatistics || [];
      } else {
        liveRoomStatistics.value = [...liveRoomStatistics.value, ...(data.liveRoomStatistics || [])];
      }
      
      hasMore.value = liveRoomStatistics.value.length < (data.total || 0);
      currentPage.value++;
      
      nextTick(() => {
        renderChart();
      });
    }
  } catch (error) {
    console.error('获取直播间统计信息失败:', error);
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
}

async function loadMore() {
  if (!hasMore.value || loadingMore.value) return;
  await getLiveRoomStatistics(false);
}

function renderChart() {
  const yAxisData = liveRoomStatistics.value.map(item => item.liveRoomName);
  const seriesData = liveRoomStatistics.value.map(item => item.robotCount || 0);
  
  renderEcharts({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        const data = params[0];
        const index = params[0].dataIndex;
        const liveRoom = liveRoomStatistics.value[index];
        return `${liveRoom.liveRoomName}<br/>机器人数量：${data.value}<br/>主播：${liveRoom.anchorName}`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '机器人数量'
    },
    yAxis: {
      type: 'category',
      data: yAxisData,
      axisLabel: {
        interval: 0,
        rotate: 0,
        formatter: function(value: string) {
          // 限制直播间名称长度，超过 10 个字符显示省略号
          return value.length > 10 ? value.substring(0, 10) + '...' : value;
        }
      }
    },
    series: [
      {
        name: '机器人数量',
        type: 'bar',
        data: seriesData,
        label: {
          show: true,
          position: 'right',
          formatter: '{c}'
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: '#83bff6'
              },
              {
                offset: 0.5,
                color: '#188df0'
              },
              {
                offset: 1,
                color: '#188df0'
              }
            ]
          }
        },
        emphasis: {
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: '#2378f7'
                },
                {
                  offset: 0.7,
                  color: '#2378f7'
                },
                {
                  offset: 1,
                  color: '#83bff6'
                }
              ]
            }
          }
        }
      }
    ]
  });
}
</script>
