<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as Home from '@/api/home'
import type { Ref } from 'vue'

interface LoanItem {
  day: string
  loanCount: number
  returnCount: number
}

const chartOptions: Ref<any> = ref({})

const colors = ['#5793f3', '#d14a61'] // 蓝色表示借出，红色表示归还

const setChartOptions = (data: LoanItem[]) => {
  const days = data.map(item => item.day)
  const loanCounts = data.map(item => item.loanCount)
  const returnCounts = data.map(item => item.returnCount)

  chartOptions.value = {
    color: colors,
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['借出数量', '归还数量']
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: days,
      axisTick: { alignWithLabel: true },
      axisLabel: {
        interval: 0,       // 显示每个日期
        rotate: 45        // 如果日期太密，可以旋转防止重叠
      },
      axisLine: {
        lineStyle: {
          color: '#5793f3' // 蓝色
        }
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      name: '数量',
      axisLine: {
        lineStyle: {
          color: '#5793f3' // 蓝色
        }
      }
    },
    series: [
      {
        name: '借出数量',
        type: 'bar',
        data: loanCounts
      },
      {
        name: '归还数量',
        type: 'bar',
        data: returnCounts
      }
    ]
  }
}

const fetchChartData = async () => {
  try {
    const now = new Date()
    const endTime = now.toISOString()
    const start = new Date()
    start.setMonth(start.getMonth() - 1)
    const startTime = start.toISOString()

    const chartData = await Home.getHomePage({ startTime, endTime })
    const loanList: LoanItem[] = chartData.loanList || []
    console.log(loanList,'图表数据有值吗')
    // 按日期排序，保证图表从旧到新
    loanList.sort((a, b) => new Date(a.day).getTime() - new Date(b.day).getTime())

    setChartOptions(loanList)
  } catch (error) {
    console.error('获取图表数据失败', error)
  }
}

onMounted(() => {
  fetchChartData()
})
</script>

<template>
  <Echart :options="chartOptions" />
</template>
