<template>
  <div class="page-container bag-monitoring-container" data-testid="bag-monitoring-container">
    <div class="header" data-testid="bag-monitoring-header">
      <div class="select-container" data-testid="device-select-container">
        <span class="select-label">检测仪器</span>
        <el-select v-model="selectedDevice" placeholder="1#布袋检测仪" @change="handleDeviceChange" data-testid="device-select">
          <el-option
            v-for="item in deviceList"
            :key="item.deviceNo"
            :label="item.deviceName"
            :value="item.deviceNo"
            :data-testid="`device-option-${item.deviceNo}`"
          ></el-option>
        </el-select>
      </div>
      <div class="title" data-testid="monitoring-title">BME布袋监测 - {{ dusterName }}</div>
    </div>

    <div class="chart-container" data-testid="chart-container">
      <div class="chart-wrapper" ref="chartRef" data-testid="chart-wrapper"></div>
      <div class="chart-wrapper no-data" v-if="chartData.xData.length === 0" data-testid="no-data-wrapper">
        <div class="no-data-text" data-testid="no-data-text">暂无数据</div>
      </div>
    </div>

    <div class="data-panel" :class="{ collapsed: !isPanelOpen }" data-testid="data-panel">
      <div
        class="panel-toggle"
        :class="{
          'collapsed-icon': !isPanelOpen,
          'expanded-icon': isPanelOpen,
        }"
        @click="togglePanel"
        data-testid="panel-toggle"
      >
        <el-icon v-if="isPanelOpen"><ArrowRightBold /></el-icon>
        <el-icon v-if="!isPanelOpen"><ArrowLeftBold /></el-icon>
      </div>
      <div class="data-box" data-testid="data-box">
        <div class="data-item" data-testid="data-item-1">
          <div>时间: {{ currentData.time }}</div>
          <div>仓室: {{ currentData.compartNo }}</div>
          <div>反吹: {{ currentData.blowBack }}</div>
        </div>

        <div class="data-item" data-testid="data-item-2">
          <div>DI3: {{ currentData.di3 }}</div>
          <div>排: {{ currentData.row }}</div>
          <div>实时值: {{ currentData.realData }}</div>
        </div>
        <div class="data-item" data-testid="data-item-3">
          <div>基线值: {{ currentData.baseline }}</div>
          <div>Delay: {{ currentData.delay }}</div>
          <div>totaltime: {{ currentData.totalTime }}</div>
        </div>
        <div class="data-item" data-testid="data-item-4">
          <div>next:{{ currentData.next }}</div>
          <div>valve:{{ currentData.valveNo }}</div>
          <div>DI_TIME={{ currentData.diTime }}</div>
        </div>
        <div class="data-item" data-testid="data-item-5">
          <div>peak={{ currentData.peak }}</div>
        </div>
      </div>

      <!-- <div class="data-box second-box">
          <div>时间:{{ secondaryData.time }}, 仓室: {{ secondaryData.chamber }}, 反吹: {{ secondaryData.backwash }}, 谷值: {{ secondaryData.valleyValue }}, 仓室状态阀门{{ secondaryData.status }}False{{ secondaryData.falseVal }}</div>
        </div> -->
    </div>

    <div class="time-controls" data-testid="time-controls">
        <div class="time-desc" data-testid="time-desc">
          <span class="icon"></span>
          <span class="time-desc-text">当前实时信号：</span>
          <span class="time-desc-value">{{ currentData.compartNo }}仓 / {{ currentData.row }}排</span>
        </div>
        <div data-testid="navigation-controls">
          <el-button @click="navigateBackward" data-testid="navigate-backward-button">
            <el-icon><ArrowLeftBold />向前</el-icon>
          </el-button>
          <el-button @click="navigateForward" data-testid="navigate-forward-button">
            <el-icon><ArrowRightBold />向后</el-icon>
          </el-button>
          <span class="time-label" data-testid="time-label">间隔</span>
          <el-input v-model="timeInterval" class="time-input" data-testid="time-interval-input"></el-input>
          <span class="time-unit" data-testid="time-unit">分钟</span>

          <el-button @click="reset" data-testid="reset-button">重置</el-button>
        </div>
      </div>
    <div class="data-table" data-testid="data-table">


      <table data-testid="monitoring-table">
        <thead data-testid="table-head">
          <tr data-testid="table-header-row">
            <th data-testid="table-header-name">名称</th>
            <th v-for="(value, index) in tableData" :key="index" :data-testid="`table-header-${index}`">
              {{ value.compartName }}
            </th>
          </tr>
        </thead>
        <tbody data-testid="table-body">
          <tr data-testid="peak-value-r-row">
            <td data-testid="peak-value-r-label">峰值{{ currentData.row }}排_R</td>
            <td
              v-for="(value, index) in tableData"
              :key="'r' + index"
              :class="{
                'online-style': value.compartNo === currentData.compartNo,
              }"
              :data-testid="`peak-value-r-${index}`"
            >
              {{ value.peakValueR }}
            </td>
          </tr>
          <tr data-testid="peak-value-h-row">
            <td data-testid="peak-value-h-label">峰值_H</td>
            <td v-for="(value, index) in tableData" :key="'h' + index" :data-testid="`peak-value-h-${index}`">
              {{ value.peakValueH }}
            </td>
          </tr>
          <tr data-testid="status-row">
            <td data-testid="status-label">状态</td>
            <td
              v-for="(value, index) in tableData"
              :key="'s' + index"
              :class="{ error: value.status === 1 }"
              :data-testid="`status-${index}`"
            >
              {{ value.status === 1 ? "故障" : "正常" }}
            </td>
          </tr>
          <tr data-testid="blow-back-row">
            <td data-testid="blow-back-label">反吹中</td>
            <td v-for="(value, index) in tableData" :key="'b' + index" :data-testid="`blow-back-${index}`">
              {{ value.blowBack }}
            </td>
          </tr>
          <tr data-testid="valley-value-row">
            <td data-testid="valley-value-label">谷值</td>
            <td v-for="(value, index) in tableData" :key="'v' + index" :data-testid="`valley-value-${index}`">
              {{ value.valleyValue}}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
import moment from "moment";
import { ArrowRightBold, ArrowLeftBold } from "@element-plus/icons-vue";
import { getBagMonitoringChartOption } from "@/utils/chart.js";
import {
  getMonitorToday,
  getMonitorList,
  getMonitorRealtime,
} from "@/request/api/bagMonitor";
import { useRoute } from "vue-router";

// 获取路由参数
const route = useRoute();

// 设备选择
const selectedDevice = ref(null);

const isPanelOpen = ref(true);

// 图表相关
const chartRef = ref(null);
let chartInstance = null;
let updateTimer = null; // 定时器引用

let lastTimePoint = null;
// 控制是否获取实时设备状态数据
let showRealtimeDeviceStatus = true;

// 从路由参数获取dusterNo
const dusterNo = ref(
  route.params.dusterNo || route.query.dusterNo || ""
); // 默认值作为fallback
const dusterName = ref(
  route.params.dusterName || route.query.dusterName || ""
);

// 图表数据
const chartData = reactive({
  xData: [],
  seriesData: [],
});
const deviceList = ref([]);
const currentTime = ref(null);

// 当前数据面板
const currentData = ref({
  realtime: "",
  time: "",
  compartNo: "",
  blowBack: "",
  di3: "",
  row: "",
  realData: "",
  baseline: "",
  delay: "",
  totalTime: "",
  next: "",
  valveNo: "",
  diTime: "",
  peak: "",
});

// 表格数据
const tableData = ref([
  {
    compartName: "默认",
    peakValueR: 0,
    peakValueH: 0,
    status: 0,
    blowBack: 0,
    valleyValue: 0,
  },
]);

// 时间控制
const timeInterval = ref("10");

const togglePanel = () => {
  isPanelOpen.value = !isPanelOpen.value;
};

const handleDeviceChange = (value) => {
  initChart();
};

// 初始化图表
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 初始化图表数据
  initChartData();
};

// 初始化图表数据
const initChartData = () => {
  if (!dusterNo.value || !selectedDevice.value) {
    console.warn("缺少dusterNo或deviceNo，无法获取数据");
    return;
  }

  // 获取昨天这个之前的数据
  const startTime = moment()
    .subtract(5, "minutes")
    .format("YYYY-MM-DD HH:mm:ss");
  const endTime = moment().format("YYYY-MM-DD HH:mm:ss");
  chartData.xData = [];
  chartData.seriesData = [];
  getMonitorToday({
    dusterNo: dusterNo.value,
    deviceNo: selectedDevice.value,
    startTime: startTime,
    // endTime: endTime,
  })
    .then((res) => {
      // 将data中的date和realData数据添加到chartData中，要求大数据量下速度快
      if (res.data && res.data.length > 0) {
        res.data.forEach((item) => {
          chartData.xData.push(item.date);
          chartData.seriesData.push(item.realData);
        });
        // 当前时间
        currentTime.value = res.data[res.data.length - 1].date;
        chartInstance = echarts.init(chartRef.value);
        // 启动定时更新
        startRealTimeUpdates();
      } else {
        console.warn("未获取到初始数据");
      }
    })
    .catch((err) => {
      console.error("获取初始数据失败:", err);
    });
};

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(
      getBagMonitoringChartOption(chartData.xData, chartData.seriesData)
    );
  }
};

// 启动实时更新
const startRealTimeUpdates = () => {
  if (updateTimer) {
    clearInterval(updateTimer);
  }

  updateTimer = setInterval(() => {
    updateFunction();
  }, 1000);

  showRealtimeDeviceStatus = true;
};

// 更新函数
const updateFunction = () => {
  if (!dusterNo.value || !selectedDevice.value) return;

  // 从API获取实时数据

  getMonitorRealtime({
    dusterNo: dusterNo.value,
    deviceNo: selectedDevice.value,
  })
    .then((res) => {
      if (res.data) {
        // 更新数据面板
        if (res.data.realtimeCompart) {
          tableData.value = res.data.realtimeCompart;
        }
        if (res.data.realtimePanel) {
          currentData.value = res.data.realtimePanel;
        }
      }
    })
    .catch((err) => {
      console.error("获取实时数据失败:", err);
    });

  if (showRealtimeDeviceStatus) {
    // 结束时间往后推一秒
    let endTime = moment(new Date(currentTime.value))
      .add(1, "seconds")
      .format("YYYY-MM-DD HH:mm:ss");
    getMonitorToday({
      dusterNo: dusterNo.value,
      deviceNo: selectedDevice.value,
      startTime: currentTime.value,
      endTime: endTime,
    }).then((res) => {
      if (res.data && res.data.length > 0) {
        const item = res.data[res.data.length - 1];
        chartData.xData.push(item.date);
        chartData.seriesData.push(item.realData || 0);

        // 移除最旧的数据点以保持固定长度
        if (chartData.xData.length > 301) {
          // 保持300秒的数据
          chartData.xData.shift();
          chartData.seriesData.shift();
        }
        currentTime.value = endTime;
        // 更新图表
        updateChart();
      }
    });
  }
};


// 向前导航（查看更早的数据）
const navigateBackward = () => {
  // 不完全关闭轮询，只禁用实时设备状态获取
  showRealtimeDeviceStatus = false;

  // 获取时间间隔（分钟）
  const interval = parseInt(timeInterval.value) || 10;
  const intervalMs = interval * 60 * 1000;

  // 如果是第一次点击，以当前最后一条数据的时间为参考
  if (lastTimePoint === null && chartData.xData.length > 0) {
    const lastTimeString = chartData.xData[chartData.xData.length - 1];
    lastTimePoint = new Date(lastTimeString);
  } else if (lastTimePoint === null) {
    // 如果没有数据，使用当前时间
    lastTimePoint = new Date();
  }

  // 计算新的时间范围
  const endTime = new Date(lastTimePoint.getTime() - intervalMs);
  lastTimePoint = endTime;


  // 重新生成数据
  generateHistoricalData(endTime, interval);
};

// 向后导航（查看更近的数据）
const navigateForward = () => {
  // 不完全关闭轮询，只禁用实时设备状态获取
  showRealtimeDeviceStatus = false;

  // 获取时间间隔（分钟）
  const interval = parseInt(timeInterval.value) || 10;
  const intervalMs = interval * 60 * 1000;

  // 如果是第一次点击，以当前最后一条数据的时间为参考
  if (lastTimePoint === null && chartData.xData.length > 0) {
    const lastTimeString = chartData.xData[chartData.xData.length - 1];
    lastTimePoint = new Date(lastTimeString);
  } else if (lastTimePoint === null) {
    // 如果没有数据，使用当前时间
    lastTimePoint = new Date();
  }

  // 计算新的时间范围
  let endTime = new Date(lastTimePoint.getTime() + intervalMs);

  // // 如果新的结束时间超过当前时间，则切换回实时模式
  const now = moment();
  if (endTime > now) {
    lastTimePoint = new Date(now);
    endTime = new Date(now);
    // // showRealtimeDeviceStatus = true;
    // return;
  } else {
    lastTimePoint = endTime;
  }
  // 重新生成数据
  generateHistoricalData(endTime, interval);
};

const reset = () => {
  // 清空现有数据
  chartData.xData = [];
  chartData.seriesData = [];
  lastTimePoint = null;
  // 恢复实时设备状态获取
  showRealtimeDeviceStatus = true;
  // 重新生成当前时间往前300秒的数据

  const now = new Date();

  generateHistoricalData(now, 5);

  // 开启实时更新
  startRealTimeUpdate();
};

// 开启实时更新（重置用）
const startRealTimeUpdate = () => {
  // 确保之前的定时器已清除
  if (updateTimer) {
    clearInterval(updateTimer);
    updateTimer = null;
  }
  // 启动定时更新
  updateTimer = setInterval(() => {
    updateFunction();
  }, 1000);
};

// 生成历史数据
const generateHistoricalData = (endTime, intervalMinutes) => {
  if (!dusterNo.value || !selectedDevice.value) return;

  // 清空现有数据
  chartData.xData = [];
  chartData.seriesData = [];
  const startTime = new Date(endTime.getTime() - intervalMinutes * 60 * 1000);
  const startTimeStr = moment(startTime).format("YYYY-MM-DD HH:mm:ss");
  const endTimeStr = moment(endTime).format("YYYY-MM-DD HH:mm:ss");

  // 从API获取历史数据
  getMonitorToday({
    dusterNo: dusterNo.value,
    deviceNo: selectedDevice.value,
    startTime: startTimeStr,
    endTime: endTimeStr,
  })
    .then((res) => {
      if (res.data && res.data.length > 0) {
        res.data.forEach((item) => {
          chartData.xData.push(item.date);
          chartData.seriesData.push(item.realData);
        });
        // 更新图表
        updateChart();
      }
    })
    .catch((err) => {
      console.error("获取历史数据失败:", err);
    });
};

// 监听窗口大小变化，调整图表大小
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

const getDeviceList = () => {
  if (!dusterNo.value) return;

  getMonitorList({
    dusterNo: dusterNo.value,
  }).then((res) => {
    if (res.data) {
      deviceList.value = res.data.devices || [];
      if (deviceList.value.length > 0) {
        selectedDevice.value = deviceList.value[0].deviceNo;
      }

      tableData.value = Array.from(
        { length: res.data.compartCount },
        (item, index) => ({
          compartName: `${index + 1}仓`,
          peakValueR: 0,
          peakValueH: 0,
          status: 0,
          blowBack: 0,
        })
      );
      initChart();
    }
  });
};

// 监听dusterNo变化
watch(dusterNo, (newVal) => {
  if (newVal) {
    // 重新获取设备列表
    getDeviceList();
  }
});

onMounted(() => {
  if (dusterNo.value) {
    getDeviceList();
  }

  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  // 清除定时器
  if (updateTimer) {
    clearInterval(updateTimer);
    updateTimer = null;
  }
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<style scoped lang="scss">
.bag-monitoring-container {
  width: 100%;
  height: calc(100% - 14px);
  box-sizing: border-box;
  // overflow-x: hidden;
  position: relative;
  background-color: #181d21;
  overflow-y: auto;
  overflow-x: hidden;
  &::-webkit-scrollbar {
    width: 2px;
    background-color: rgba(58, 63, 69, 0.5);
  }

  .header {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 16px;
    
    @media (max-width: 768px) {
      flex-direction: column;
      align-items: flex-start;
      padding-top: 50px; /* Make room for the select container */
    }

    .select-container {
      position: absolute;
      left: 0;
      top: 0;
      width: 400px;
      display: flex;
      align-items: center;
      z-index: 99;
      
      @media (max-width: 768px) {
        width: 100%;
        position: relative;
        margin-bottom: 10px;
      }

      .select-label {
        color: #909399 !important;
        font-size: 14px;
      }
      span {
        display: block;
        width: 80px;
        margin-right: 10px;
      }

      .device-number {
        background: #fcf0c2;
        padding: 2px 8px;
        margin-left: 10px;
        border-radius: 6px;
      }
    }

    .title {
      font-size: 18px;
      font-weight: bold;
      color: var(--success);
    }
  }

  .chart-container {
    width: 100%;
    height: calc(100% - 380px);
    min-height: 200px;
    max-height: calc(50vh - 50px);
    background-color: #000;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    position: relative;

    .chart-wrapper {
      flex: 1;
      width: 100%;
      .no-data-text {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: #999;
        background-color: #000;
        border-radius: 4px;
      }
    }
    .no-data {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 10;
    }
  }

  .data-panel {
    position: absolute;
    top: 0px;
    right: 0px;
    width: 320px;
    z-index: 100;
    transition: transform 0.3s ease-in-out;

    @media (max-width: 768px) {
      width: 280px;
    }

    &.collapsed {
      transform: translateX(345px);
      
      @media (max-width: 768px) {
        transform: translateX(300px);
      }
    }

    .panel-toggle {
      position: absolute;
      width: 25px;
      height: 30px;
      background: #232a31;
      top: 0px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      border-radius: 4px;
      .el-icon {
        color: var(--success) !important;
      }
    }

    .collapsed-icon {
      left: -23px;
    }
    .expanded-icon {
      right: -23px;
    }

    .data-box {
      padding: 10px;
      background-color: #232a31;
      border-radius: 4px;
      border: 1px solid #3a3f45;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-bottom: 10px;

      .data-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
        font-size: 14px;

        @media (max-width: 768px) {
          flex-wrap: wrap;
          font-size: 12px;
        }

        div {
          flex: 1;
          
          @media (max-width: 768px) {
            min-width: 45%;
            margin-bottom: 3px;
          }
        }
      }
    }

    .second-box {
      font-size: 12px;
    }
  }

  .data-table {
    background-color: #181d21;
    border-radius: 4px;
    padding: 10px 0;
    box-sizing: border-box;
    overflow-x: auto;
    overflow-y: hidden;
    max-height: 300px;
    &::-webkit-scrollbar {
      width: 2px;
      background-color: rgba(58, 63, 69, 0.5);
    }

    table {
      width: 100%;
      border-collapse: collapse;
      min-width: 600px;

      th,
      td {
        border: 1px solid #434343;
        text-align: center;
        padding: 8px;
        font-size: 14px;
        font-weight: 400;
      }
      td {
        color: #afafaf;
      }

      th {
        background-color: #181d21;
        color: #bababd;
        font-weight: 600;
      }

      .error {
        color: #f56c6c;
      }

      .highlight {
        background-color: #181d21;
        position: relative;

        &::after {
          content: "";
          position: absolute;
          width: 16px;
          height: 16px;
          background-color: #e6a23c;
          border-radius: 50%;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          z-index: 1;
        }
      }
      .online-style {
        color: var(--accent);
        font-weight: 600;
    background-color: #58595a;
      }
    }

  
  }
    .time-controls {
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      gap: 10px;
      
      @media (max-width: 768px) {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .el-button {
        border-color: var(--accent);
        color: var(--accent);
        background-color: #181d21;
        
        &:hover {
          border-color: var(--accent);
          color: var(--accent);
        }
        .el-icon {
          color: var(--accent) !important;
        }
      }
      :deep(.el-input__wrapper) {
        background-color: #181d21;
        box-shadow: 0 0 0 1px var(--accent) inset;
        color: var(--accent);
        &:hover {
          box-shadow: 0 0 0 1px var(--accent) inset;
          color: var(--accent);
        }
        .el-input__inner {
          color: var(--accent);
        }
      }

      .time-desc {
        font-size: 14px;
        color: #606266;
        display: flex;
        align-items: center;
        .icon {
          display: inline-block;
          width: 12px;
          height: 12px;
          background-color: #05ea09;
          border-radius: 50%;
          margin-right: 5px;
        }
        .time-desc-value {
          color: #fff;
          font-weight: 600;
        }
      }
      .time-label,
      .time-unit {
        font-size: 14px;
        margin: 0 5px;
        margin-right: 10px;
      }
      .time-input {
        width: 60px;
      }
    }
}
</style>
