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

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

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

  const categories = props.data.data.map(item => item.score_scope || '')
  const values = props.data.data.map(item => item.student_num || 0)

  // 找到学生所在的分数段索引
  const studentIndex = props.data.data.findIndex((item) => {
    const allScore = props.data?.all_score || 0
    const [min, max] = (item.score_scope || '').split('~').map(Number)
    return allScore >= min && allScore <= max
  })

  return {
    tooltip: {
      trigger: 'axis',
      confine: true,
      axisPointer: {
        type: 'cross',
      },
      formatter: (params: any) => {
        if (!Array.isArray(params) || params.length === 0)
          return ''
        const param = params[0]
        return `${param.axisValue}\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: '#3b82f6',
          width: 2,
        },
        itemStyle: {
          color: '#3b82f6',
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(59, 130, 246, 0.3)' },
              { offset: 1, color: 'rgba(59, 130, 246, 0.05)' },
            ],
          },
        },
        markPoint: studentIndex >= 0
          ? {
              symbol: 'pin',
              symbolSize: 50,
              itemStyle: {
                color: '#f59e0b',
              },
              label: {
                formatter: '我',
                fontSize: 12,
                color: '#fff',
              },
              data: [
                {
                  coord: [studentIndex, values[studentIndex]],
                },
              ],
            }
          : undefined,
      },
    ],
  }
})

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

// 计算分数段信息
const scoreRangeInfo = computed(() => {
  if (!props.data?.data || !props.data?.all_score)
    return null

  const allScore = props.data.all_score
  const item = props.data.data.find((d) => {
    const [min, max] = (d.score_scope || '').split('-').map(Number)
    return allScore >= min && allScore <= max
  })

  if (!item)
    return null

  return {
    range: item.score_scope.split('-').join('~'),
    gradeCount: item.student_num || 0,
    classCount: 0, // TODO: 接口暂无此数据
  }
})
</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 v-if="scoreRangeInfo" class="mt-4 rounded-lg from-blue-50 to-indigo-50 bg-gradient-to-r p-4">
      <view class="flex items-center gap-2">
        <view class="h-1 w-1 rounded-full bg-blue-500" />
        <text class="text-sm text-slate-700">
          本人所在分数段: <text class="text-blue-600 font-semibold">{{ scoreRangeInfo.range }}</text>
        </text>
      </view>
      <view class="mt-2 flex items-center gap-2">
        <view class="h-1 w-1 rounded-full bg-blue-500" />
        <text class="text-sm text-slate-700">
          本分数段年级学生数: <text class="text-blue-600 font-semibold">{{ scoreRangeInfo.gradeCount }}</text>人，其中本班占<text class="text-blue-600 font-semibold">{{ scoreRangeInfo.classCount }}</text>人
        </text>
      </view>
    </view>
  </view>
</template>

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