<template>
  <el-card>
    <el-form :inline="true">
      <el-form-item label="时间范围">
        <el-select v-model="timeRange" placeholder="请选择">
          <el-option
              v-for="item in timeRangeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="exportReport">导出报告</el-button>
      </el-form-item>
    </el-form>

    <div ref="chart" style="width: 100%; height: 400px;"></div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 初始化选项
const timeRange = ref('month')
const timeRangeOptions = [
  { value: 'month', label: '月度' },
  { value: 'quarter', label: '季度' },
  { value: 'year', label: '年度' },
]

const chart = ref(null)

function fetchData() {
  // 这里应该调用后端API获取数据
  // 模拟数据
  const data = generateData()
  initChart(data)
}

function initChart(data) {
  const myChart = echarts.init(chart.value)
  const option = {
    title: {
      text: '考核结果',
    },
    tooltip: {},
    xAxis: {
      data: data.units,
    },
    yAxis: {},
    series: [
      {
        name: '得分',
        type: 'bar',
        data: data.scores,
      },
    ],
  }
  myChart.setOption(option)
}

function generateData() {
  const units = ['单位A', '单位B', '单位C', '单位D', '单位E']
  const scores = units.map(() => Math.floor(Math.random() * 100))
  return { units, scores }
}

function exportReport() {
  if (!chartInstance) {
    ElMessage.error('请先加载图表数据')
    return
  }
  // 导出图表为图片
  chartInstance.exportImage({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff',
    callback: function (dataUrl) {
      // 下载图片
      downloadImage(dataUrl)
    },
  })
}

function downloadImage(dataUrl) {
  const link = document.createElement('a')
  link.href = dataUrl
  link.download = 'evaluation-report.png'
  link.click()
}

let chartInstance = null

onMounted(() => {
  fetchData()
  chartInstance = echarts.init(chart.value)
})

// 监听图表更新
watch(() => chart.value, () => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  chartInstance = echarts.init(chart.value)
})
</script>

<style scoped>
.el-card {
  margin: 20px;
}
</style>