<template>
    <div class="chart-container">
      <h3>设备月度利用率变化趋势</h3>
         <v-chart :option="chartOption" autoresize  />
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { use } from 'echarts/core'
  import VChart from 'vue-echarts'
  import * as api from '../api';
  import {
    CanvasRenderer
  } from 'echarts/renderers'
  import {
    LineChart
  } from 'echarts/charts'
  import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent
  } from 'echarts/components'
  
  use([
    CanvasRenderer,
    LineChart,
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent
  ])



  interface MonthlyUtilization {
    month: string
    rate: number
  }
  
  const rawData = ref<MonthlyUtilization[]>([])
  
  const fetchData = async () => {
    const res = await api.GetUtilizationList()
    if (res.code === 2000) {
        rawData.value = res.data.monthly_utilization


    }

  }


  
  
  onMounted(fetchData)
  
  const chartOption = computed(() => {
    const months = rawData.value.map(item => item.month)
    const rates = rawData.value.map(item => item.rate)
    console.log("rates:::",rates);
    const diffs = rawData.value.map((item, index, arr) => {
      if (index === 0) return 0
      return +(item.rate - arr[index - 1].rate).toFixed(2)
    })
  
    return {
      title: {
        text: '设备利用率提升幅度',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const rate = params[0].data
          const diff = diffs[params[0].dataIndex]
          const sign = diff > 0 ? '+' : ''
          return `
            月份：${params[0].name}<br/>
            利用率：${rate}<br/>
            提升幅度：${sign}${diff}
          `
        }
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value',
        name: '利用率'
      },
      series: [
        {
          name: '月度利用率',
          type: 'line',
          data: rates,
          smooth: true,
          label: {
            show: true,
            formatter: '{c}'
          },
          lineStyle: {
            color: '#5470C6'
          },
          itemStyle: {
            color: '#91cc75'
          }
        }
      ]
    }
  })
  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    height: 400px;
    margin: 0 auto;
  }
  </style>
  