<template>
  <el-card>
    <el-form :inline="true">
      <el-form-item label="区域">
        <el-select v-model="selectedRegion" placeholder="请选择">
          <el-option
              v-for="region in regions"
              :key="region.value"
              :label="region.label"
              :value="region.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div class="charts-container">
      <div ref="deploymentsChart" class="chart" style="height: 300px;"></div>
      <div ref="alertsChart" class="chart" style="height: 300px;"></div>
      <div ref="operationsChart" class="chart" style="height: 300px;"></div>
      <div ref="casesChart" class="chart" style="height: 300px;"></div>
    </div>
  </el-card>
</template>

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

// 初始化选项
const selectedRegion = ref('city')
const regions = [
  { value: 'city', label: '全市' },
  { value: 'district1', label: '区县1' },
  { value: 'district2', label: '区县2' },
  { value: 'district3', label: '区县3' },
]

const deploymentsChart = ref(null)
const alertsChart = ref(null)
const operationsChart = ref(null)
const casesChart = ref(null)

function fetchData(region) {
  // 这里应该调用后端API获取数据
  // 模拟数据
  return generateData(region)
}

function generateData(region) {
  const deployments = { labels: ['1月', '2月', '3月'], values: [100, 200, 150] }
  const alerts = { labels: ['1月', '2月', '3月'], values: [10, 5, 20] }
  const operations = { labels: ['1月', '2月', '3月'], values: [50, 60, 40] }
  const cases = { labels: ['1月', '2月', '3月'], values: [20, 15, 25] }
  return { deployments, alerts, operations, cases }
}

function initChart(chartRef, data, title) {
  const myChart = echarts.init(chartRef.value)
  const option = {
    title: {
      text: title,
    },
    tooltip: {},
    xAxis: {
      data: data.labels,
    },
    yAxis: {},
    series: [
      {
        name: '数量',
        type: 'bar',
        data: data.values,
      },
    ],
  }
  myChart.setOption(option)
  return myChart
}

function updateCharts() {
  const data = fetchData(selectedRegion.value)
  const deploymentsChartInstance = initChart(deploymentsChart, data.deployments, '设备部署情况')
  const alertsChartInstance = initChart(alertsChart, data.alerts, '告警情况')
  const operationsChartInstance = initChart(operationsChart, data.operations, '运维情况')
  const casesChartInstance = initChart(casesChart, data.cases, '案件处置情况')
}

onMounted(() => {
  updateCharts()
})

watch(selectedRegion, () => {
  updateCharts()
})
</script>

<style scoped>
.el-card {
  margin: 20px;
}
.charts-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.chart {
  width: calc(50% - 10px);
  margin-bottom: 20px;
}
</style>