<script lang="ts" setup>
import type * as API from '@/service/types'

import { useQuery } from '@tanstack/vue-query'
import UniEcharts from 'uni-echarts'
import { computed, ref, watch } from 'vue'
import { useUserId } from '@/composables/useUserId'
import { teacherAnalysisTrendUsingPost } from '@/service/laoshichengjifenxi'
import { useHomeStore } from '@/store/home'

const props = defineProps<{
  selectedSubjectId: number
}>()

const emit = defineEmits<{
  openCompareClassDialog: []
}>()

// 类型别名
type TrendInfo = API.TrendInfo
type TrendDataItem = API.TrendDataItem

// 使用store
const homeStore = useHomeStore()

// 图表展示模式
type ChartMode = 'avg_score' | 'rank' | 'top_count'
const chartMode = ref<ChartMode>('avg_score')

// 年级前N名配置
const topN = ref(50)
const showTopNDialog = ref(false)

// 对比班级ID（内部状态，默认选择第一个）
const compareClassId = ref<number | null>(null)

// 初始化对比班级为第一个选项
watch(
  () => homeStore.classOptions,
  (options) => {
    if (options.length > 0 && !compareClassId.value) {
      // 排除当前选中的班级，选择第一个其他班级
      const otherClasses = options.filter(item => item.value !== homeStore.selectedClassId)
      if (otherClasses.length > 0) {
        compareClassId.value = otherClasses[0].value
      }
      else if (options.length > 0) {
        // 如果没有其他班级，就选第一个
        compareClassId.value = options[0].value
      }
    }
  },
  { immediate: true },
)

// 对比班级名称
const compareClassName = computed(() => {
  if (!compareClassId.value) {
    return '选择对比班级'
  }
  const cls = homeStore.classOptions.find(item => item.value === compareClassId.value)
  return cls?.label || '选择对比班级'
})

// 使用 TanStack Query 获取走势数据（包含本班和对比班级）
const {
  data: trendData,
  isLoading: loading,
  refetch: refetchData,
} = useQuery({
  queryKey: [
    'class-trend',
    useUserId(),
    homeStore.selectedClassId,
    homeStore.selectedGradeKey,
    compareClassId,
    props.selectedSubjectId,
    topN,
  ],
  queryFn: async () => {
    const response = await teacherAnalysisTrendUsingPost({
      body: {
        class_key: homeStore.selectedClassId,
        grade_key: homeStore.selectedGradeKey,
        class_key_compare: compareClassId.value!,
        subject_id: props.selectedSubjectId || 0,
        top_n: topN.value,
      },
    })

    return response || { trend_list: [] }
  },
  enabled: computed(() =>
    !!homeStore.selectedClassId
    && !!homeStore.selectedGradeKey
    && !!compareClassId.value,
  ),
  staleTime: 30000, // 30秒内不重新请求
})

// 计算走势列表
const trendList = computed(() => trendData.value?.trend_list || [])

// 图表标题
const chartTitle = computed(() => {
  if (chartMode.value === 'avg_score') {
    return '班级平均分'
  }
  else if (chartMode.value === 'rank') {
    return '平均分排名'
  }
  else {
    return `年级前${topN.value}名`
  }
})

// uni-echarts 配置
const chartOption = computed(() => {
  if (trendList.value.length === 0) {
    return {}
  }

  // 获取考试名称作为横轴
  const categories = trendList.value.map(item => item.exam_name || '')

  // 提取本班数据（第一个）
  const getClassData = (dataKey: keyof TrendDataItem) => {
    return trendList.value.map((item) => {
      const classData = item.trend_data?.[0] // 第一个是本班
      return classData?.[dataKey] || 0
    })
  }

  // 提取对比班级数据（第二个）
  const getCompareData = (dataKey: keyof TrendDataItem) => {
    return trendList.value.map((item) => {
      const compareData = item.trend_data?.[1] // 第二个是对比班级
      return compareData?.[dataKey] || 0
    })
  }

  let dataKey: keyof TrendDataItem
  let yAxisName = ''
  let tooltipSuffix = ''

  if (chartMode.value === 'avg_score') {
    dataKey = 'class_avg_score'
    yAxisName = '分数'
    tooltipSuffix = '分'
  }
  else if (chartMode.value === 'rank') {
    dataKey = 'class_rank'
    yAxisName = '排名'
    tooltipSuffix = '名'
  }
  else {
    dataKey = 'class_top_count'
    yAxisName = '人数'
    tooltipSuffix = '人'
  }

  // 本班数据
  const classData = getClassData(dataKey)

  // 对比班级数据
  const compareData = getCompareData(dataKey)

  const series: any[] = [
    {
      name: '本班',
      type: 'bar',
      data: classData,
      itemStyle: { color: '#3b82f6' },
      barMaxWidth: 40,
    },
    {
      name: compareClassName.value,
      type: 'bar',
      data: compareData,
      itemStyle: { color: '#10b981' },
      barMaxWidth: 40,
    },
  ]

  const legendData = ['本班', compareClassName.value]

  return {
    tooltip: {
      trigger: 'axis',
      confine: true,
      axisPointer: {
        type: 'shadow',
      },
      formatter: (params: any) => {
        if (!Array.isArray(params))
          return ''
        let result = `${params[0].axisValue}`
        params.forEach((param: any) => {
          const value = chartMode.value === 'avg_score'
            ? param.value.toFixed(2)
            : param.value
          result += `\n${param.marker} ${param.seriesName}: ${value}${tooltipSuffix}`
        })
        return result
      },
    },
    legend: {
      data: legendData,
      top: 5,
      textStyle: {
        fontSize: 12,
      },
    },
    grid: {
      left: 45,
      right: 15,
      bottom: 30,
      top: 40,
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        rotate: 30,
        interval: 0,
        fontSize: 10,
      },
      axisLine: {
        lineStyle: {
          color: '#cccccc',
        },
      },
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      nameTextStyle: {
        fontSize: 11,
      },
      axisLabel: {
        fontSize: 10,
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#eeeeee',
        },
      },
      // 排名从大到小展示（数字小的排名高）
      inverse: chartMode.value === 'rank',
    },
    series,
  }
})

// 打开对比班级选择
function openCompareClassDialog() {
  emit('openCompareClassDialog')
}

// 切换图表模式
function setChartMode(mode: ChartMode) {
  if (mode === 'top_count') {
    // 点击年级前N名时，先打开弹窗设置N值
    showTopNDialog.value = true
  }
  else {
    chartMode.value = mode
  }
}

// 临时N值（弹窗中）
const tempTopN = ref(topN.value)

// 确认设置前N名
function confirmTopN() {
  topN.value = tempTopN.value
  chartMode.value = 'top_count'
  showTopNDialog.value = false
}

// 取消设置
function cancelTopN() {
  showTopNDialog.value = false
  tempTopN.value = topN.value
}

const showChart = computed(() => {
  return !loading.value && trendList.value.length > 0
})

// 图表容器引用
const chartRef = ref(null)

// 暴露方法给父组件
defineExpose({
  refetch: refetchData,
  compareClassId, // 暴露给父组件，允许外部修改对比班级
})
</script>

<template>
  <view class="rounded-xl bg-white p-4 shadow-sm">
    <!-- 标题和对比班级按钮 -->
    <view class="mb-4 flex items-center justify-between">
      <text class="text-lg text-slate-800 font-semibold">{{ chartTitle }}</text>
      <wd-button size="small" @click="openCompareClassDialog">
        {{ compareClassName }}
      </wd-button>
    </view>

    <!-- 图表模式切换按钮 -->
    <view class="mb-4 flex justify-center gap-2">
      <wd-button
        size="small"
        :type="chartMode === 'avg_score' ? 'primary' : 'default'"
        @click="setChartMode('avg_score')"
      >
        班级平均分
      </wd-button>
      <wd-button
        size="small"
        :type="chartMode === 'rank' ? 'primary' : 'default'"
        @click="setChartMode('rank')"
      >
        平均分排名
      </wd-button>
      <wd-button
        size="small"
        :type="chartMode === 'top_count' ? 'primary' : 'default'"
        @click="setChartMode('top_count')"
      >
        年级前{{ topN }}名
      </wd-button>
    </view>

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

    <!-- 暂无数据提示 -->
    <view v-if="trendList.length === 0 && !loading" class="py-8 text-center">
      <text class="text-sm text-gray-500">暂无数据</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="h-80 flex items-center justify-center">
      <wd-loading size="24" />
    </view>

    <!-- 设置年级前N名弹窗 -->
    <wd-popup v-model="showTopNDialog" position="center" :close-on-click-modal="false">
      <view class="w-70 rounded-2 bg-white p-6">
        <view class="mb-4 text-center">
          <text class="text-base text-slate-800 font-semibold">设置年级前N名</text>
        </view>
        <view class="mb-6 flex justify-center p-4">
          <wd-input-number v-model="tempTopN" :min="1" :max="200" :step="1" />
        </view>
        <view class="flex gap-3">
          <wd-button block type="default" @click="cancelTopN">
            取消
          </wd-button>
          <wd-button block type="primary" @click="confirmTopN">
            确定
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

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