<template>
  <div class="titleBox">
    各区域终端运行状态
    <!-- <div class="titles">
      <div
        class="react-right"
        :class="time == 4 ? 'titleClick' : ''"
        @click="timeChange(4)"
      >
        <span class="text"> 周</span>
      </div>
      <div
        class="react-right"
        :class="time == 3 ? 'titleClick' : ''"
        @click="timeChange(3)"
      >
        <span class="text"> 月</span>
      </div>
    </div> -->
  </div>
  <div v-loading="loading" element-loading-background="#343849c7">
    <!-- style="width: 450px; height: 285px" -->

    <div
      class="eacharts1"
      ref="eacharts1"
      style="width: 100%; height: 330px"
    ></div>
  </div>
  <!-- 详情弹框 -->
  <terminalPopUpBox ref="terminalPopUpBoxRef" />
</template>

<script lang="ts" setup>
import { onMounted, ref, getCurrentInstance, onUnmounted, markRaw } from "vue";
const { proxy }: any = getCurrentInstance();
import * as echarts from "echarts";
import terminalPopUpBox from "@/views/VoltageSag_BJ/components/popUpFrame/terminalPopUpBox.vue";
import { regionDevCount } from "@/api/statistics/index";
import { isEqual } from "lodash";
import { useStore } from "vuex";
const terminalPopUpBoxRef = ref();
const store = useStore();
const eacharts1 = ref(null);
const time = ref(4); //
const dataSource = ref([]);
const loading = ref(false);
const myChart = ref(null);
const renderChart = () => {
  // 如果实例存在，则销毁它
  if (myChart.value) {
    myChart.value.dispose();
  }
  myChart.value = markRaw(proxy.$echarts.init(eacharts1.value));

  myChart.value.setOption({
    legend: {
      right: 10,
      top: 5,
      itemGap: 10,
      textStyle: {
        color: "#fff",
      },
      fontSize: 12,
      padding: [2, 0, 0, 0], //[上、右、下、左]
      itemWidth: 15,
      itemHeight: 10,
    },
    grid: {
      containLabel: true,
      left: "4%",
      right: "40",
      bottom: "15",
      top: "45",
    },
    tooltip: {
      trigger: "axis",
      show: true,
    },
    color: ["#28a74590", "#ff250070"],
    xAxis: {
      name: "区域",
      type: "category",
      show: true,
      boundaryGap: [20, 0], // 左侧留出空间
      splitLine: {
        show: false,
        lineStyle: {
          color: "#fff",
          type: "dashed",
        },
      },
      axisLabel: {
        rotate: 45, // 旋转角度，如45度
        interval: 0, // 强制显示所有标签
        textStyle: {
          color: "#fff",
          fontSize: 10,
        },
      },
      axisLine: {
        show: true, //不显示x轴
        onZero: false, // 不强制与Y轴0点对齐
        lineStyle: {
          color: "#fff",
        },
      },
      axisTick: {
        show: false, //不显示刻度
      },
      data: dataSource.value.map((item) => item.areaName),
    },

    yAxis: [
      {
        name: "台",
        minInterval: 5,
        axisLabel: {
          color: "#fff",
          fontWeight: 400,
          fontSize: 10,
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: "#fff",
            type: "dashed",
          },
        },
        axisLine: {
          show: true, //不显示x轴
          lineStyle: {
            color: "#fff",
          },
        },
        axisTick: {
          show: false, //不显示刻度
        },
      },
    ],
    series: [
      {
        name: "在线终端",
        type: "bar",
        stack: "total",
        data: dataSource.value.map((item) => item.onLine),
        barMaxWidth: 20,
        label: {
          normal: {
            show: true,
            // 使用函数形式的formatter进行判断
            formatter: function (params) {
              // 如果值为0则返回空字符串（不显示），否则显示数值
              return params.value === 0 ? "" : params.value;
            },
            textStyle: {
              color: "#fff",
              fontSize: 10,
            },
          },
        },
      },
      {
        name: "离线终端",
        type: "bar",
        stack: "total",
        data: dataSource.value.map((item) => item.offLine),
        barMaxWidth: 20,
        label: {
          normal: {
            show: true,
            // 使用函数形式的formatter进行判断
            formatter: function (params) {
              // 如果值为0则返回空字符串（不显示），否则显示数值
              return params.value === 0 ? "" : params.value;
            },
            textStyle: {
              color: "#fff",
              fontSize: 10,
            },
          },
        },
      },
    ],
  });
  // 添加点击事件
  myChart.value.off("click"); // 先移除之前的点击事件
  // 添加点击事件（修改后）
  myChart.value.on("click", function (params) {
    // 1. 只处理系列数据（柱状图）的点击，忽略图例等其他元素
    if (params.componentType !== "series") {
      return; // 非系列点击直接返回，避免执行后续逻辑
    }

    // 2. 安全获取匹配的数据源（使用find替代filter，更高效）
    const matchedItem = dataSource.value.find(
      (item) => item.areaName === params.name
    );

    // 3. 确保数据存在后再执行操作，避免undefined错误
    if (matchedItem && matchedItem.deptsIndex !== undefined) {
      terminalPopUpBoxRef.value.open(matchedItem.deptsIndex);
    }
  });
};
const init = () => {
  regionDevCount({
    deptId: store.state.deptId,
    type: store.state.timeType,
    startTime: store.state.timeValue[0],
    endTime: store.state.timeValue[1],
  }).then((res: any) => {
    let isSame = isEqual(dataSource.value, res.data);
    dataSource.value = res.data;

    if (!isSame) {
      loading.value = true;
      renderChart();
      loading.value = false;
    }
  });
};
// 保存定时器ID
const timer = ref(null);
onMounted(() => {
  // 保存定时器引用
  timer.value = setInterval(() => {
    init();
  }, 60000);
});
// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});
defineExpose({
  init,
});
</script>
<style lang="scss" scoped>
@use "@/assets/scss/index.scss";
.titles {
  margin-right: 10px;
  .react-right {
    width: 50px !important;
    line-height: 20px !important;
    font-size: 14px !important;
  }
}
</style>
