<template>
  <div class="system-monitor-container">
    <!-- 左侧导航树 -->
    <el-card class="tree-card">
      <h3>系统层级</h3>
      <el-tree
          :data="systemTree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <el-tag v-if="data.type === 'system'" size="small" type="primary">系统</el-tag>
            <el-tag v-if="data.type === 'subsystem'" size="small" type="success">子系统</el-tag>
          </span>
        </template>
      </el-tree>
    </el-card>

    <!-- 右侧监控展示 -->
    <el-card class="monitor-card">
      <h3>监控组态图</h3>
      <div class="config-info" v-if="currentSystem.config">
        <h4>组态配置</h4>
        <pre>{{ currentSystem.config }}</pre>
        <el-button type="primary" @click="editConfig">编辑配置</el-button>
      </div>
      <div class="chart-container" v-if="currentSystem.data">
        <h4>实时监控数据</h4>
        <div ref="chart" class="chart"></div>
      </div>
    </el-card>

    <!-- 组态编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑组态配置" width="50%">
      <el-form :model="configForm" label-width="120px">
        <el-form-item label="设备列表">
          <el-input v-model="configForm.devices" placeholder="逗号分隔的设备列表" />
        </el-form-item>
        <el-form-item label="布局">
          <el-select v-model="configForm.layout" placeholder="选择布局">
            <el-option label="网格" value="grid" />
            <el-option label="列表" value="list" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveConfig">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

// 模拟系统层级数据
const systemTree = ref([
  {
    id: 'sys1',
    label: '暖通空调系统',
    type: 'system',
    children: [
      { id: 'subsys1', label: '空调机组', type: 'subsystem' },
      { id: 'subsys2', label: '末端设备', type: 'subsystem' }
    ]
  },
  {
    id: 'sys2',
    label: '新风系统',
    type: 'system',
    children: [
      { id: 'subsys3', label: '新风机', type: 'subsystem' },
      { id: 'subsys4', label: '空气过滤器', type: 'subsystem' }
    ]
  },
  {
    id: 'sys3',
    label: '制冷机房',
    type: 'system',
    children: [
      { id: 'subsys5', label: '冷水机组', type: 'subsystem' },
      { id: 'subsys6', label: '冷却塔', type: 'subsystem' }
    ]
  },
  {
    id: 'sys4',
    label: '水系统',
    type: 'system',
    children: [
      { id: 'subsys7', label: '水泵', type: 'subsystem' },
      { id: 'subsys8', label: '水箱', type: 'subsystem' }
    ]
  },
  {
    id: 'sys5',
    label: '电梯系统',
    type: 'system',
    children: [
      { id: 'subsys9', label: '电梯A', type: 'subsystem' },
      { id: 'subsys10', label: '电梯B', type: 'subsystem' }
    ]
  },
  {
    id: 'sys6',
    label: '配电系统',
    type: 'system',
    children: [
      { id: 'subsys11', label: '配电柜', type: 'subsystem' },
      { id: 'subsys12', label: '断路器', type: 'subsystem' }
    ]
  },
  {
    id: 'sys7',
    label: '照明系统',
    type: 'system',
    children: [
      { id: 'subsys13', label: '照明A', type: 'subsystem' },
      { id: 'subsys14', label: '照明B', type: 'subsystem' }
    ]
  }
])

// 当前选中的系统
const currentSystem = ref({
  config: null,
  data: null
})

// 组态配置映射（模拟数据）
const systemConfigMap = {
  'subsys1': {
    config: { devices: ['ac_unit1', 'fan1'], layout: 'grid' },
    data: {
      temperature: [22, 23, 21, 24, 22, 23, 21],
      humidity: [45, 50, 55, 48, 49, 47, 50]
    }
  },
  'subsys2': {
    config: { devices: ['end_device1', 'end_device2'], layout: 'list' },
    data: {
      temperature: [20, 21, 22, 20, 21, 22, 20],
      humidity: [55, 60, 65, 62, 63, 61, 64]
    }
  },
  'subsys3': {
    config: { devices: ['ventilator1', 'filter1'], layout: 'custom' },
    data: {
      airflow: [100, 110, 120, 105, 115, 125, 110]
    }
  },
  'subsys4': {
    config: { devices: ['filter2', 'filter3'], layout: 'grid' },
    data: {
      airflow: [90, 95, 100, 92, 97, 102, 95]
    }
  },
  'subsys5': {
    config: { devices: ['chiller1', 'chiller2'], layout: 'list' },
    data: {
      temperature: [18, 19, 17, 18, 19, 17, 18]
    }
  },
  'subsys6': {
    config: { devices: ['cooling_tower1', 'cooling_tower2'], layout: 'custom' },
    data: {
      temperature: [25, 26, 24, 25, 26, 24, 25]
    }
  },
  'subsys7': {
    config: { devices: ['pump1', 'pump2'], layout: 'grid' },
    data: {
      flow_rate: [50, 55, 60, 52, 57, 62, 55]
    }
  },
  'subsys8': {
    config: { devices: ['tank1', 'tank2'], layout: 'list' },
    data: {
      water_level: [80, 85, 90, 82, 87, 92, 85]
    }
  },
  'subsys9': {
    config: { devices: ['elevator_a1', 'elevator_a2'], layout: 'custom' },
    data: {
      status: ['正常', '正常', '正常', '正常', '正常', '正常', '正常']
    }
  },
  'subsys10': {
    config: { devices: ['elevator_b1', 'elevator_b2'], layout: 'grid' },
    data: {
      status: ['正常', '正常', '正常', '正常', '正常', '正常', '正常']
    }
  },
  'subsys11': {
    config: { devices: ['switchboard1', 'switchboard2'], layout: 'list' },
    data: {
      voltage: [220, 225, 230, 222, 227, 232, 225]
    }
  },
  'subsys12': {
    config: { devices: ['breaker1', 'breaker2'], layout: 'custom' },
    data: {
      current: [10, 12, 11, 10, 12, 11, 10]
    }
  },
  'subsys13': {
    config: { devices: ['light_a1', 'light_a2'], layout: 'grid' },
    data: {
      power_usage: [50, 55, 60, 52, 57, 62, 55]
    }
  },
  'subsys14': {
    config: { devices: ['light_b1', 'light_b2'], layout: 'list' },
    data: {
      power_usage: [40, 45, 50, 42, 47, 52, 45]
    }
  }
}

// 组态编辑对话框显示控制
const dialogVisible = ref(false)

// 当前编辑的配置
const configForm = ref({
  devices: '',
  layout: ''
})

// ECharts 实例
const chart = ref(null)
let chartInstance = null

// 处理树节点点击事件
const handleNodeClick = (data) => {
  if (data.type === 'subsystem') {
    // 加载对应子系统的组态配置和监控数据
    const systemData = systemConfigMap[data.id]
    if (systemData) {
      currentSystem.value = systemData
      configForm.value.devices = systemData.config.devices.join(', ')
      configForm.value.layout = systemData.config.layout
      nextTick(() => {
        initChart(systemData.data)
      })
    } else {
      currentSystem.value = { config: null, data: null }
    }
  } else {
    // 如果是系统节点，清空监控数据
    currentSystem.value = { config: null, data: null }
  }
}

// 初始化 ECharts 图表
const initChart = (data) => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  chartInstance = echarts.init(chart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: Object.keys(data)
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: Object.keys(data).map(key => ({
      name: key,
      type: 'line',
      data: data[key]
    }))
  }
  chartInstance.setOption(option)
}

// 编辑配置
const editConfig = () => {
  if (currentSystem.value.config) {
    dialogVisible.value = true
  } else {
    ElMessage.warning('请先选择一个子系统以编辑配置')
  }
}

// 保存配置
const saveConfig = () => {
  if (currentSystem.value.config) {
    currentSystem.value.config.devices = configForm.value.devices.split(',').map(device => device.trim())
    currentSystem.value.config.layout = configForm.value.layout
    ElMessage.success('配置保存成功')
    dialogVisible.value = false
  }
}

// 页面加载时初始化图表
onMounted(() => {
  // 可以在这里加载默认的子系统数据
  // 例如：handleNodeClick(systemTree.value[0].children[0])
})
</script>

<style scoped lang="scss">
.system-monitor-container {
  display: flex;
  height: 100vh;
  padding: 20px;

  .tree-card {
    width: 300px;
    margin-right: 20px;

    h3 {
      margin-bottom: 10px;
      font-size: 18px;
      color: #333;
    }

    .custom-tree-node {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }
  }

  .monitor-card {
    flex: 1;

    h3 {
      margin-bottom: 10px;
      font-size: 18px;
      color: #333;
    }

    .config-info {
      pre {
        background-color: #f5f5f5;
        padding: 10px;
        border-radius: 5px;
        font-size: 14px;
        overflow-x: auto;
      }

      .el-button {
        margin-top: 10px;
      }
    }

    .chart-container {
      margin-top: 20px;

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