<template>
  <div class="leftMiddle-box">
    <el-button @click="toggleDataZoomMove" class="show-bt">
      <el-icon><d-caret /></el-icon>
      {{ isDataZoomMoving ? '关闭轮播' : '开启轮播' }}
    </el-button>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { BoxApi } from '@/utils/boxApi.ts';
import { DCaret } from '@element-plus/icons-vue';

const chartContainer = ref(null);
let myChart = null;
const cameras = ref([]);
const apiInstance = new BoxApi();

const colorList = ['#FF4B01', '#FF7B00', '#FFE823', '#2379FF', '#2379FF', '#2379FF'];
const colorListA = ['#FC7A24', '#FFC000', '#FFEA97', '#49B1FF', '#49B1FF', '#49B1FF'];
let dataZoomMove = { start: 0, end: 8 };
const isDataZoomMoving = ref(false);
let dataZoomMoveTimer = null;

const option = ref({
  backgroundColor: "#001529",
  tooltip: {
    trigger: "axis",
    backgroundColor: "rgba(21, 154, 255, 0.32)",
    textStyle: { color: "#fff" },
    borderColor: "#159AFF",
    axisPointer: { lineStyle: { color: "transparent" } },
    formatter: (params) => {
      const cameraName = params[0] ? params[0].name : '';
      const outerSeries = params.find(item => item.seriesName === '告警数量');

      return outerSeries ? `<div style="font-weight: bold; margin-bottom: 5px;">摄像头: ${cameraName}</div>${outerSeries.marker} ${outerSeries.seriesName}: ${outerSeries.value} 次` : '';
    }

  },
  dataZoom: [
    { show: false, startValue: dataZoomMove.start, endValue: dataZoomMove.end, yAxisIndex: [0, 1] },
    { type: "inside", yAxisIndex: 0, zoomOnMouseWheel: false, moveOnMouseMove: true, moveOnMouseWheel: true }
  ],
  grid: { containLabel: true, bottom: 20, left: 30, top: 20, right: 30 },
  xAxis: { type: "value", axisLabel: { show: false }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } },
  yAxis: [
    {
      type: "category",
      data: [], // 动态填充摄像头名称
      inverse: true,
      axisLabel: {
        inside: true,
        verticalAlign: "bottom",
        lineHeight: 36,
        margin: 2,
        formatter(value) {
          const k = option.value.yAxis[0].data.indexOf(value);
          // return `{b|${k + 1}} {a|${value}}`;
          return `{a|${value}}`;
        },
        rich: {
          b: { color: "#fff", fontSize: 14 },
          a: { fontSize: 14, color: "#D0DEEE", padding: [4, 0, 0, 8] }
        }
      },
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false }
    },
    {
      type: "category",
      data: [], // 动态填充告警数量
      inverse: true,
      axisLabel: {
        inside: true,
        verticalAlign: "bottom",
        lineHeight: 34,
        margin: 2,
        formatter(value, index) {
          return `{a|${value}}`;
        },
        rich: {
          a: { fontSize: 16, color: "#fff", padding: [4, 0, 0, 0], fontFamily: "DOUYU" }
        }
      },
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false }
    }
  ],
  series: [
    {
      name: "条形图",
      data: [], // 动态填充告警数量
      type: "bar",
      barWidth: 10,
      padding:[0],
      showBackground: true,
      barBorderRadius: [30, 0, 0, 30],
      backgroundStyle: { color: 'rgba(9, 68, 131, .2)' },
      itemStyle: {
        barBorderRadius: [3, 0, 0, 3],
        color(params) {
          const i = colorListA.length;
          const f = colorList.length;
          return {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [
              { offset: 0, color: colorListA[params.dataIndex % i] },
              { offset: 1, color: colorList[params.dataIndex % f] }
            ]
          };
        }
      }
    },
    {
      name: "告警数量",
      type: "scatter",
      symbol: "rect",
      symbolSize: [5, 16],
      itemStyle: { color: '#FFF', shadowColor: "rgba(255, 255, 255, 0.5)", shadowBlur: 5, borderWidth: 1, opacity: 1 },
      z: 2,
      data: [], // 动态填充告警数量
      animationDelay: 500
    }
  ]
});

const toggleDataZoomMove = () => {
  // console.log(`Data zoom move is now ${isDataZoomMoving.value}`);
  isDataZoomMoving.value = !isDataZoomMoving.value; // 切换状态
  // console.log(`转换${isDataZoomMoving.value}`);
  if (isDataZoomMoving.value) {
    startMoveDataZoom();// 关闭轮播
  } else {
    // 开启轮播
    stopMoveDataZoom();
  }

};

// 关闭轮播
const stopMoveDataZoom = () => {
  if (dataZoomMoveTimer) {
    // console.log('Stopping data zoom move...');
    clearInterval(dataZoomMoveTimer);
    dataZoomMoveTimer = null;

  }
};


// 启动数据轮播
const startMoveDataZoom = () => {
  // if (isDataZoomMoving.value) return;
  // console.log('Starting ...');
  if (dataZoomMoveTimer !== null) {
    clearInterval(dataZoomMoveTimer);
  }
  if (isDataZoomMoving.value) {
    // console.log('Starting data zoom move...');
    dataZoomMoveTimer = setInterval(() => {
      dataZoomMove.start += 1;
      dataZoomMove.end += 1;
      if (dataZoomMove.end > option.value.yAxis[0].data.length - 1) {
        dataZoomMove.start = 0;
        dataZoomMove.end = 8;
      }
      myChart.setOption({
        dataZoom: [{ type: "slider", startValue: dataZoomMove.start, endValue: dataZoomMove.end }]
      });
    }, 2500);
  }
};





// 获取摄像头信息并获取对应的告警数量
const fetchCameras = async () => {
  try {
    // 获取摄像头数据
    const token = localStorage.getItem('alertToken');
    const limit = 20;
    let offset = 0;
    let allCameras = [];

    // 获取所有摄像头信息
    const firstResponse = await apiInstance.getCameras(limit, offset, token);
    const cameraCount = firstResponse.count;
    allCameras = firstResponse.results;

    while (offset + limit < cameraCount) {
      offset += limit;
      const response = await apiInstance.getCameras(limit, offset, token);
      allCameras = allCameras.concat(response.results);
    }

    // 提取摄像头名称和对应的告警数量并存储在对象数组中
    const cameraData = [];

    for (const camera of allCameras) {
      // 获取该摄像头的告警数量
      const eventsResponse = await apiInstance.getEventsByParams(token, 20, 1, null, null, null, camera.id);
      const count = eventsResponse.count || 0; // 确保即使没有事件也返回 0
      cameraData.push({ name: camera.name, count }); // 将数据存储为对象以便排序
    }

    // 按照告警数量降序排序
    cameraData.sort((a, b) => b.count - a.count);

    // 提取排序后的名称和数量
    const cameraNames = cameraData.map(item => item.name);
    const cameraCounts = cameraData.map(item => item.count);

    // 更新图表的 Y 轴标签和系列数据
    option.value.yAxis[0].data = cameraNames;
    option.value.yAxis[1].data = cameraCounts.map(count => `${count}`);
    option.value.series[0].data = cameraCounts;
    option.value.series[1].data = cameraCounts;

    // 设置图表选项并启动轮播
    myChart.setOption(option.value);
    startMoveDataZoom(); // 重新启动轮播效果
  } catch (error) {
    console.error("Error fetching cameras or events:", error);
  }
};

// 清理轮播和事件监听
onBeforeUnmount(() => {
  if (dataZoomMoveTimer) {
    clearInterval(dataZoomMoveTimer);
    dataZoomMoveTimer = null; // 确保计时器被清空
  }
  if (myChart) {
    window.removeEventListener('resize', resizeChart); // 确保事件监听器被移除
    myChart.dispose();
    myChart = null;
  }
});



// 初始化图表
onMounted(async () => {
  myChart = echarts.init(chartContainer.value);
  await fetchCameras();
  myChart.setOption(option.value);

  // 监听窗口变化事件，调整图表大小
  window.addEventListener('resize', resizeChart);
});


const resizeChart = () => {
  if (myChart && !myChart.isDisposed()) {
    myChart.resize();
  } else {
    console.warn('Attempted to resize a disposed ECharts instance.');
  }
};


// const resizeChart = () => {
//   if (myChart && !myChart.isDisposed()) {
//     myChart.resize();
//     if (dataZoomMoveTimer) {
//       clearInterval(dataZoomMoveTimer);
//       startMoveDataZoom();
//     }
//   }
// };
</script>

<style scoped>
.leftMiddle-box{
  display: flex;
  flex-direction: column;
  height: 41vh;
  margin: 20px;
}
.show-bt{
  background-color: #001529;
  border: #001529;
  width: 6vw;
  height: 4vh;
  border-radius: 6px;
  color: white;
  font-weight: bolder;
  font-size: 15px;
  padding: 0;
}
.chart-container {
  /* margin: 0 1vw 0 1vw; */
  padding-top: 0;
  width: 100%;
  height: 35vh;
  box-sizing: border-box;
}
</style>