<template>
  <div class="learning-progress">
    <div class="progress-header">
      <div class="header-left">
        <h3 class="progress-title">学习进度</h3>
        <p class="update-time">更新时间：{{ updateTime || '-' }}</p>
      </div>
      <div class="tab-buttons">
        <button v-for="(tab, index) in tabs" :key="index" :class="['tab-btn', { active: activeTab === index }]"
          @click="handleTabChange(index)">
          {{ tab }}
        </button>
      </div>
    </div>

    <div class="chart-container" ref="chartRef"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import dayjs from 'dayjs';
import { learningTaskApi } from '@/apis/study/learning-task';

const tabs = ref(['今日', '近一周', '近一月']);
const activeTab = ref(0);
const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 后端返回的数据结构映射为图表数据
const chartData = ref<{ name: string; value: number; highlight: boolean }[]>([]);

const updateTime = ref('');

async function loadStatistics() {
  // 根据当前 tab 计算时间范围
  const now = dayjs();
  let start: dayjs.Dayjs;

  if (activeTab.value === 0) {
    // 今日：从今天 00:00:00 到现在
    start = now.startOf('day');
  } else if (activeTab.value === 1) {
    // 近一周：过去 7 天
    start = now.subtract(6, 'day').startOf('day');
  } else {
    // 近一月：过去 30 天
    start = now.subtract(29, 'day').startOf('day');
  }

  const startTime = start.format('YYYY-MM-DD HH:mm:ss');
  const endTime = now.format('YYYY-MM-DD HH:mm:ss');

  const res = await learningTaskApi.getMyStatistics(startTime, endTime);
  if (res.code === 200 && res.data) {
    const list = (res.data.tagProgressList || []) as { tagName: string; avgProgress: number }[];
    chartData.value = list.map(item => ({
      name: item.tagName,
      value: Number(item.avgProgress ?? 0),
      highlight: false,
    }));
    updateTime.value = now.format('YYYY-MM-DD HH:mm:ss');
  } else {
    chartData.value = [];
  }
}

// 图表配置
function getChartOption(): EChartsOption {
  const data = chartData.value;
  
  return {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function(params: any) {
        const item = params[0];
        return `${item.name}: ${item.value}%`;
      }
    },
    grid: {
      left: '0',
      right: '20px',
      top: '20px',
      bottom: '40px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#979797',
        fontSize: 14,
        fontFamily: 'PingFang SC'
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      interval: 20,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#979797',
        fontSize: 14,
        fontFamily: 'PingFang SC'
      },
      splitLine: {
        lineStyle: {
          color: '#D4D4D5',
          type: 'dashed'
        }
      }
    },
    series: [{
      type: 'bar',
      data: data.map(item => ({
        value: item.value,
        itemStyle: {
          color: item.highlight ? '#FF6B6B' : '#C62828',
          borderRadius: [8, 8, 0, 0]
        }
      })),
      barWidth: 40,
      label: {
        show: false
      }
    }]
  };
}

const chartOption = computed(getChartOption);

// 初始化图表
function initChart() {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption(chartOption.value);

  // 自动调整大小
  window.addEventListener('resize', handleResize);
}

// 处理窗口大小变化
function handleResize() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

// 处理标签切换
async function handleTabChange(index: number) {
  activeTab.value = index;
  await loadStatistics();
  if (chartInstance) {
    chartInstance.setOption(chartOption.value, true);
  }
}

// 监听配置变化
watch(() => chartOption.value, () => {
  if (chartInstance) {
    chartInstance.setOption(chartOption.value, true);
  }
}, { deep: true });

onMounted(async () => {
  initChart();
  await loadStatistics();
  if (chartInstance) {
    chartInstance.setOption(chartOption.value, true);
  }
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style lang="scss" scoped>
.learning-progress {
  width: 100%;
  height: 371px;
  background: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  padding: 30px 30px 40px 30px;

  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 30px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .progress-title {
      font-family: 'PingFang SC';
      font-weight: 600;
      font-size: 20px;
      line-height: 38px;
      color: #141F38;
      margin: 0;
    }

    .update-time {
      font-family: 'PingFang SC';
      font-weight: 400;
      font-size: 14px;
      line-height: 22px;
      color: #B4B8BF;
      margin: 0;
    }
  }

  .tab-buttons {
    display: flex;
    gap: 4px;
    background: #F9F9F9;
    border: 1px solid #EBEBEB;
    border-radius: 8px;
    padding: 4px;

    .tab-btn {
      padding: 8px;
      min-width: 71px;
      height: 40px;
      background: transparent;
      border: none;
      border-radius: 6px;
      font-family: 'PingFang SC';
      font-weight: 600;
      font-size: 14px;
      line-height: 22px;
      color: #B4B8BF;
      cursor: pointer;
      transition: all 0.3s;

      &.active {
        background: #FFFFFF;
        color: #C62828;
      }

      &:hover:not(.active) {
        color: #141F38;
      }
    }
  }
}

  .chart-container {
    height: 243px;
  }
</style>
