<script setup lang="ts">
import type * as API from '@/service/types'
import UniEcharts from 'uni-echarts'
import { computed } from 'vue'

const props = defineProps<{
  data: API.ScoreTrendItem[] | undefined
}>()

// 图表配置
const chartOption = computed(() => {
  if (!props.data || props.data.length === 0) {
    return {}
  }

  const categories = props.data.map(item => item.exam_name || '')
  const values = props.data.map(item => item.total_score || 0)

  return {
    tooltip: {
      trigger: 'axis',
      confine: true,
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985',
        },
      },
      formatter: (params: any) => {
        if (!Array.isArray(params) || params.length === 0)
          return ''
        const param = params[0]
        const item = props.data?.[param.dataIndex]
        return `${param.axisValue}\n${item?.exam_date || ''}\n${param.marker} 成绩：${param.value}分`
      },
    },
    grid: {
      left: 45,
      right: 15,
      bottom: 40,
      top: 20,
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        rotate: 30,
        interval: 0,
        fontSize: 10,
      },
      axisLine: {
        lineStyle: {
          color: '#cccccc',
        },
      },
    },
    yAxis: {
      type: 'value',
      name: '分数',
      nameTextStyle: {
        fontSize: 11,
      },
      axisLabel: {
        fontSize: 10,
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#eeeeee',
        },
      },
    },
    series: [
      {
        type: 'line',
        data: values,
        smooth: true,
        lineStyle: {
          color: '#10b981',
          width: 3,
        },
        itemStyle: {
          color: '#10b981',
          borderWidth: 2,
          borderColor: '#fff',
        },
        symbolSize: 8,
      },
    ],
  }
})

const showChart = computed(() => {
  return props.data && props.data.length > 0
})
</script>

<template>
  <view class="rounded-xl bg-white p-4 shadow-sm">
    <view class="mb-4">
      <text class="text-lg text-slate-800 font-semibold">成绩趋势</text>
    </view>

    <!-- 图表 -->
    <view v-if="showChart" class="chart-container">
      <uni-echarts :option="chartOption" custom-class="chart" />
    </view>

    <!-- 暂无数据 -->
    <view v-else class="h-60 flex items-center justify-center rounded-lg bg-gray-50">
      <text class="text-sm text-gray-400">暂无数据</text>
    </view>
  </view>
</template>

<style scoped>
.chart {
  width: 100%;
  height: 250px;
}
</style>
