<template>
  <div class="driving-container" v-loading="loading" element-loading-text="数据加载中..."
    element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>告警数据驾驶舱</h2>
      <div class="header-right">
        <el-date-picker disabled v-model="currentDate" type="datetime" placeholder="选择日期时间" format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss" style="width: 200px; margin-right: 10px">
        </el-date-picker>
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新</el-button>
        <!-- <el-checkbox v-model="autoRefresh" style="margin-left: 10px">自动刷新</el-checkbox> -->
      </div>
    </div>

    <!-- 第一行：指标分类数据获取情况 + 实时告警列表 + 七日告警数据分布 -->
    <div class="row row-1">
      <!-- 指标分类数据获取情况 -->
      <div class="col col-1">
        <div class="card">
          <div class="card-header">
            <h3>指标分类数据获取情况</h3>
          </div>
          <div class="card-body">
            <div class="category-charts-container">
              <div class="chart-item">
                <div ref="contentChart" class="chart"></div>
                <div class="chart-title">内容类</div>
              </div>
              <div class="chart-item">
                <div ref="thresholdChart" class="chart"></div>
                <div class="chart-title">阈值类</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 实时告警列表 -->
      <div class="col col-2">
        <div class="card">
          <div class="card-header">
            <h3>实时告警列表</h3>
          </div>
          <div class="card-body">
            <div class="alarm-list" ref="alarmList">
              <div class="alarm-items-container">
                <div v-for="alarm in realTimeAlarms" :key="alarm.id" class="alarm-item">
                  <div class="alarm-indicator">{{ alarm.indicator }}</div>
                  <div class="alarm-time">{{ alarm.occurTime }}/{{ alarm.alarmType }}</div>
                  <div class="alarm-status">
                    <el-tag type="danger"> 未处理 </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 七日告警数据分布 -->
      <div class="col col-3">
        <div class="card">
          <div class="card-header">
            <h3>七日告警数据分布</h3>
          </div>
          <div class="card-body">
            <!-- <div class="total-alarms">
              <div class="total-label">七日内总告警数</div>
              <div class="total-count">{{this.alarmDistribution.reduce((acc, item) => acc + item.value, 0)}}</div>
            </div> -->
            <div class="chart-wrapper">
              <div ref="distributionChart"></div>
            </div>
            <!-- <div class="legend">
              <div v-for="item in alarmDistribution" :key="item.name" class="legend-item">
                <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
                <span class="legend-text">{{ item.name }}: {{ item.value }}%</span>
              </div>
            </div> -->
          </div>
        </div>
      </div>
    </div>

    <!-- 第二行：七日告警趋势分析 + 各系统七日告警 -->
    <div class="row row-2">
      <!-- 七日告警趋势分析 -->
      <div class="col col-4">
        <div class="card">
          <div class="card-header">
            <h3>七日告警趋势分析</h3>
          </div>
          <div class="card-body">
            <div class="chart-wrapper">
              <div ref="trendChart"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 各系统七日告警 -->
      <div class="col col-5">
        <div class="card">
          <div class="card-header">
            <h3>各系统七日告警</h3>
          </div>
          <div class="card-body">
            <div class="chart-wrapper">
              <div ref="systemChart"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
// import { getRealTimeAlarm, getAlarmDashboard } from '@/api/newApi/driving'
import { getDashboardDashboard } from '@/api/newApi/driving'

export default {
  data() {
    return {
      currentDate: new Date(),
      autoRefresh: false,
      refreshInterval: null,
      activeCategoryTab: 'content',


      loading: true,//全局加载状态
      realTimeAlarms: [],//实时告警列表


      sevenDayTotalAlarms: 365,
      // 图表实例
      charts: {},


      alarmDistribution: [],//告警分布
      metricCategory: {},//指标分类数据
      alarmList: [],//告警列表
      monitorPointCounts: [],//监测点数量
      trend: {},//趋势数据
      systemCategories: [],//系统分类数据
    }
  },
  mounted() {

    this.initCharts()
    // 只有在autoRefresh为true时才启动自动刷新
    if (this.autoRefresh) {
      this.startAutoRefresh()
    }
    // 添加窗口大小变化监听器
    window.addEventListener('resize', this.handleResize)
    // 初始化时执行一次缩放
    this.handleResize()
  },
  beforeDestroy() {
    this.stopAutoRefresh()
    this.destroyCharts()
    // 移除窗口大小变化监听器
    window.removeEventListener('resize', this.handleResize)
  },
  watch: {
    autoRefresh(val) {
      if (val) {
        this.startAutoRefresh()
      } else {
        this.stopAutoRefresh()
      }
    },
    '$store.state.app.sidebar.opened'() {
      this.handleResize()
    }
  },
  methods: {
    async initCharts() {
      this.loading = true
      try {
        await this.getAlarmEvent()
        this.initCategoryCharts()
        this.initDistributionChart()
        this.initTrendChart()
        this.initSystemChart()
      } finally {
        this.loading = false
      }
    },
    async getAlarmEvent() {
      try {
        // const res = await getAlarmDashboard()
        const res = await getDashboardDashboard()
        if (res && res.code === 200) {
          console.log('告警数据驾驶舱全量数据:', res)
          let resData = res.data

          // 指标分类数据
          if (resData.metricCategory) {
            this.metricCategory = resData.metricCategory
            console.log('指标分类数据:', this.metricCategory)
          }

          // 告警列表
          if (resData.alarmList && resData.alarmList.length > 0) {
            this.alarmList = resData.alarmList
            console.log('告警列表:', this.alarmList)
            // 处理实时告警列表
            this.realTimeAlarms = resData.alarmList.map(alarm => ({
              indicator: alarm.monitorName,
              occurTime: alarm.triggerTime,
              alarmType: alarm.category,
              status: alarm.alarmStatus
            }))
          }

          // 监测点数量
          if (resData.monitorPointCounts && resData.monitorPointCounts.length > 0) {
            this.monitorPointCounts = resData.monitorPointCounts
            console.log('监测点数量:', this.monitorPointCounts)
          }

          // 趋势数据
          if (resData.trend) {
            this.trend = resData.trend
            console.log('趋势数据:', this.trend)
          }

          // 系统分类数据
          if (resData.systemCategories && resData.systemCategories.length > 0) {
            this.systemCategories = resData.systemCategories
            console.log('系统分类数据:', this.systemCategories)
          }

          // 告警分布
          this.alarmDistribution = resData.monitorPointCounts.map(item => ({
            value: item.count,
            name: item.monitorName,
          }))

          this.sevenDayTotalAlarms = resData.monitorPointCounts.reduce((acc, cur) => acc + cur.count, 0)
        }
      } catch (error) {
        console.error('获取告警数据失败:', error)
      }
    },
    initCategoryCharts() {
      // 同时初始化内容类和阈值类图表
      this.initCategoryChart('content')
      this.initCategoryChart('threshold')
    },

    initDistributionChart() {
      const chartRef = this.$refs.distributionChart
      // console.log('初始化分布图表:', chartRef)
      if (!chartRef) {
        console.error('未找到分布图表引用')
        return
      }

      // 确保容器有正确的尺寸
      chartRef.style.width = '100%'
      chartRef.style.height = '100%'
      chartRef.style.minHeight = '200px'

      try {
        const distributionChart = echarts.init(chartRef)
        // console.log('分布图表初始化成功')
        distributionChart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'right'
          },
          series: [
            {
              name: '告警分布',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['25%', '50%'],
              label: {
                show: true,
                position: 'center',
                formatter: function () {
                  const total = this.sevenDayTotalAlarms;
                  return total + '\n七日告警数分布';
                }.bind(this),
                fontSize: 16,
              },
              data: this.monitorPointCounts.map(point => ({
                name: point.monitorName,
                value: point.count
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })
        this.charts.distributionChart = distributionChart
        // console.log('分布图表配置设置成功')
      } catch (error) {
        console.error('初始化分布图表时出错:', error)
      }
    },

    initTrendChart() {
      const chartRef = this.$refs.trendChart
      // console.log('初始化趋势图表:', chartRef)
      if (!chartRef) {
        console.error('未找到趋势图表引用')
        return
      }

      // 确保容器有正确的尺寸
      chartRef.style.width = '100%'
      chartRef.style.height = '100%'
      chartRef.style.minHeight = '200px'

      try {
        const trendChart = echarts.init(chartRef)
        // console.log('趋势图表初始化成功')
        trendChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: ['内容类', '阈值类', '存在性']
          },

          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              data: this.trend.dates || []
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          // dataZoom: [
          //   {
          //     type: 'slider',
          //     orient: 'horizontal',
          //     xAxisIndex: 0,
          //     start: 0,
          //     end: 50
          //   }
          // ],
          series: [
            {
              name: '内容类',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this.trend.contentCounts || [],
              lineStyle: {
                color: '#ee6666'
              },
              itemStyle: {
                color: '#ee6666'
              }
            },
            {
              name: '阈值类',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this.trend.thresholdCounts || [],
              lineStyle: {
                color: '#5470c6'
              },
              itemStyle: {
                color: '#5470c6'
              }
            },
            {
              name: '存在性',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: this.trend.existenceCounts || [],
              lineStyle: {
                color: '#91cc75'
              },
              itemStyle: {
                color: '#91cc75'
              }
            }
          ]
        })
        this.charts.trendChart = trendChart
        // console.log('趋势图表配置设置成功')
      } catch (error) {
        console.error('初始化趋势图表时出错:', error)
      }
    },

    initSystemChart() {
      const chartRef = this.$refs.systemChart
      // console.log('初始化系统图表:', chartRef)
      if (!chartRef) {
        console.error('未找到系统图表引用')
        return
      }

      // 确保容器有正确的尺寸
      chartRef.style.width = '100%'
      chartRef.style.height = '100%'
      chartRef.style.minHeight = '200px'

      try {
        const systemChart = echarts.init(chartRef)
        // console.log('系统图表初始化成功')
        systemChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['内容类', '阈值类', '存在性']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: this.systemCategories.map(system => system.systemName)
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          dataZoom: [
            {
              type: 'slider',
              orient: 'horizontal',
              xAxisIndex: 0,
              start: 0,
              end: 50
            }
          ],
          series: [
            {
              name: '内容类',
              type: 'bar',
              emphasis: {
                focus: 'series'
              },
              data: this.systemCategories.map(system => system.contentCount || 0),
              itemStyle: {
                color: '#ee6666'
              }
            },
            {
              name: '阈值类',
              type: 'bar',
              emphasis: {
                focus: 'series'
              },
              data: this.systemCategories.map(system => system.thresholdCount || 0),
              itemStyle: {
                color: '#5470c6'
              }
            },
            {
              name: '存在性',
              type: 'bar',
              emphasis: {
                focus: 'series'
              },
              data: this.systemCategories.map(system => system.existenceCount || 0),
              itemStyle: {
                color: '#91cc75'
              }
            }
          ]
        })
        this.charts.systemChart = systemChart
        // console.log('系统图表配置设置成功')
      } catch (error) {
        console.error('初始化系统图表时出错:', error)
      }
    },

    handleTabClick(tab) {
      // 当切换选项卡时，确保图表能够正确显示
      setTimeout(() => {
        // 无论之前是否存在图表实例，都重新初始化图表
        if (tab.name === 'content' && this.$refs.contentChart) {
          // 销毁旧图表实例
          if (this.charts.contentChart) {
            this.charts.contentChart.dispose()
            this.charts.contentChart = null
          }
          // 创建新图表实例
          this.initCategoryChart('content')
        } else if (tab.name === 'threshold' && this.$refs.thresholdChart) {
          // 销毁旧图表实例
          if (this.charts.thresholdChart) {
            this.charts.thresholdChart.dispose()
            this.charts.thresholdChart = null
          }
          // 创建新图表实例
          this.initCategoryChart('threshold')
        }
      }, 100)
    },

    initCategoryChart(type) {
      // 初始化单个分类图表
      const chartRef = this.$refs[`${type}Chart`]
      // console.log('初始化图表类型:', type, '图表引用:', chartRef)
      if (!chartRef) {
        console.error('未找到图表引用，类型:', type)
        return
      }

      // 确保容器有正确的尺寸
      chartRef.style.width = '100%'
      chartRef.style.height = '100%'
      chartRef.style.minHeight = '200px'

      try {
        const chart = echarts.init(chartRef)
        // console.log('图表初始化成功:', type)
        let option = {}

        if (type === 'content') {
          const contentData = this.metricCategory.content || {}
          option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'horizontal',
              bottom: 0,
              data: ['正常', '未配置', '无数据'],
              width: '100%',
              itemWidth: 10,
              itemHeight: 10,
              textStyle: {
                fontSize: 12
              }
            },
            series: [
              {
                name: '内容类',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderRadius: 0,
                  borderColor: '#fff',
                  borderWidth: 0
                },
                label: {
                  show: false
                },
                emphasis: {
                  label: {
                    show: false
                  }
                },
                labelLine: {
                  show: false
                },
                data: [
                  {
                    value: contentData.configuredCount || 0, name: '正常'
                  },
                  {
                    value: contentData.unconfiguredCount || 0, name: '未配置'
                  },
                  {
                    value: contentData.noDataCount || 0, name: '无数据'
                  }
                ],
                color: ['#8BC34A', '#fafa03', '#F44336']
              }
            ]
          }
        } else if (type === 'threshold') {
          const thresholdData = this.metricCategory.threshold || {}
          option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'horizontal',
              bottom: 0,
              data: ['正常', '未配置', '无数据'],
              width: '100%',
              itemWidth: 10,
              itemHeight: 10,
              textStyle: {
                fontSize: 12
              }
            },
            series: [
              {
                name: '阈值类',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderRadius: 0,
                  borderColor: '#fff',
                  borderWidth: 0
                },
                label: {
                  show: false
                },
                emphasis: {
                  label: {
                    show: false
                  }
                },
                labelLine: {
                  show: false
                },
                data: [
                  {
                    value: thresholdData.configuredCount || 0, name: '正常'
                  },
                  {
                    value: thresholdData.unconfiguredCount || 0, name: '未配置'
                  },
                  {
                    value: thresholdData.noDataCount || 0, name: '无数据'
                  }
                ],
                color: ['#8BC34A', '#fafa03', '#F44336']
              }
            ]
          }
        }

        if (option && chart) {
          chart.setOption(option)
          this.charts[`${type}Chart`] = chart
          // console.log('图表配置设置成功:', type)
        }
      } catch (error) {
        console.error('初始化图表时出错:', type, error)
      }
    },

    async refreshData() {
      // 模拟数据刷新
      console.log('刷新数据...')
      this.currentDate = new Date().toISOString().slice(0, 19).replace('T', ' ')
      this.loading = true

      try {
        // 重新获取数据
        await this.initCharts()
      } finally {
        this.loading = false
      }
    },

    startAutoRefresh() {
      this.stopAutoRefresh()
      this.refreshInterval = setInterval(() => {
        this.refreshData()
      }, 5000)
    },

    stopAutoRefresh() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
    },

    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        chart.resize()
      })
    },

    destroyCharts() {
      Object.values(this.charts).forEach(chart => {
        chart.dispose()
      })
    },

    formatTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    getRealEvent() {
      // 这里可以添加获取实时事件的逻辑
      return Promise.resolve()
    },

    handleResize() {
      // 设计稿尺寸
      const designWidth = 1920
      const designHeight = 1080

      // 获取侧边栏宽度
      const sidebarWidth = this.$store.state.app.sidebar.opened ? 200 : 54
      
      // 获取窗口实际尺寸
      const windowWidth = window.innerWidth - sidebarWidth
      const windowHeight = window.innerHeight
      
      // 计算缩放比例 - 以宽度为基准，确保内容横向铺满
      const scale = windowWidth / designWidth

      // 获取容器元素
      const container = document.querySelector('.driving-container')
      if (container) {
        // 应用缩放变换 - 以宽度为基准
        container.style.transform = `scale(${scale})`
        container.style.transformOrigin = 'top left'

        // 调整容器尺寸以保持布局
        container.style.width = `${designWidth}px`
        container.style.height = `${designHeight}px`

        // 不需要居中偏移，从左上角开始缩放
        container.style.position = 'relative'
        container.style.left = '0'
        container.style.top = '0'
      }

      // 调整图表大小
      this.resizeCharts()
    }
  }
}
</script>

<style scoped>
.driving-container {
  padding: 20px;
  background-color: #f5f7fa;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s ease;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
}

.row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex: 1;
  min-height: 0;
}

.row-1 {
  flex: 1;
  min-height: 300px;
}

.row-2 {
  flex: 1;
  min-height: 350px;
}

.col {
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  flex: 1;
  min-width: 0;
}

.category-charts-container {
  display: flex;
  gap: 20px;
  padding: 10px;
  height: 100%;
  min-height: 250px;
}

.chart-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 200px;
}

.chart-title {
  margin-top: 10px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  display: flex;
  flex-direction: column;
}

.col-1,
.col-2,
.col-3,
.col-4,
.col-5 {
  flex: 1;
}

.card {
  height: 100%;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.card-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
  flex-shrink: 0;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.card-body {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.el-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.el-tabs__header {
  flex-shrink: 0;
}

.el-tabs__content {
  flex: 1;
  overflow: hidden;
  display: flex;
}

.el-tab-pane {
  flex: 1;
  display: flex;
}

.chart-wrapper {
  flex: 1;
  min-height: 200px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-wrapper>div {
  width: 100%;
  height: 100%;
  min-height: 200px;
}

.alarm-list {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.alarm-items-container {
  height: 100%;
  animation: scroll 20s linear infinite;
}

.alarm-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.alarm-indicator {
  flex: 1;
  font-weight: 500;
}

.alarm-time {
  width: 180px;
  font-size: 12px;
  color: #909399;
}

.alarm-status {
  width: 80px;
  text-align: right;
}

.total-alarms {
  text-align: center;
  margin-bottom: 20px;
}

.total-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.total-count {
  font-size: 36px;
  font-weight: bold;
  color: #303133;
}

.legend {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  margin-right: 5px;
}

@keyframes scroll {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-100%);
  }
}

/* 全局样式调整 */
body {
  margin: 0;
  padding: 0;
  background-color: #f5f7fa;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
}

/* 响应式设计 - 配合等比缩放 */
@media screen and (max-width: 1200px) {

  /* 等比缩放已经处理了布局，这里可以保留一些微调 */
  .driving-container {
    padding: 15px;
  }
}

@media screen and (max-width: 768px) {

  /* 等比缩放已经处理了布局，这里可以保留一些微调 */
  .driving-container {
    padding: 10px;
  }

  .card-body {
    padding: 15px;
  }
}
</style>