<template>
  <div class="multi-product-ring-container">
    <ScreenComHeader :module-id="moduleId" title="质量一致性检验" />
    <div ref="chartRef" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import ScreenComHeader from "@/views/screens/configs/screenComHeader.vue";

const props = defineProps({
  moduleId: {
    type: String,
    required: true,
  },
});
const chartRef = ref(null);
let chartInstance = null;
let timer = null;
const currentProductIndex = ref(0);

// 假数据结构（含ISO时间字符串）
const mockData = [
  {
    productName: "智能控制器",
    inspectionItems: [
      {
        name: "外观检查",
        startTime: "2023-05-10T09:00:00Z",
        endTime: "2023-05-10T09:25:00Z",
        color: "#5470C6",
      },
      {
        name: "功能测试",
        startTime: "2023-05-10T09:25:00Z",
        endTime: "2023-05-10T10:25:00Z",
        color: "#91CC75",
      },
      {
        name: "老化试验",
        startTime: "2023-05-10T10:25:00Z",
        endTime: "2023-05-10T12:25:00Z",
        color: "#EE6666",
      },
    ],
  },
  {
    productName: "温度传感器",
    inspectionItems: [
      {
        name: "外观检查",
        startTime: "2023-05-10T08:00:00Z",
        endTime: "2023-05-10T08:30:00Z",
        color: "#5470C6",
      },
      {
        name: "精度校准",
        startTime: "2023-05-10T08:30:00Z",
        endTime: "2023-05-10T10:30:00Z",
        color: "#73C0DE",
      },
    ],
  },
];

// 计算时间差（分钟）
const getDuration = (start, end) => {
  return (new Date(end) - new Date(start)) / (1000 * 60);
};

// 获取当前检验阶段
const getCurrentPhase = (product) => {
  const now = new Date(); // 真实当前时间
  return product.inspectionItems.findIndex((item) => {
    return now >= new Date(item.startTime) && now < new Date(item.endTime);
  });
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);
  updateChart();
  window.addEventListener("resize", handleResize);

  // 3秒切换产品
  timer = setInterval(() => {
    currentProductIndex.value =
      (currentProductIndex.value + 1) % mockData.length;
    updateChart();
  }, 5000);
};

// 更新图表
const updateChart = () => {
  if (!chartInstance || mockData.length === 0) return;

  const currentProduct = mockData[currentProductIndex.value];
  const currentPhaseIndex = getCurrentPhase(currentProduct);

  // 预处理数据
  const processedData = currentProduct.inspectionItems.map((item) => {
    const duration = getDuration(item.startTime, item.endTime);
    return {
      ...item,
      duration,
      timeLabel: `${formatTime(item.startTime)}~${formatTime(item.endTime)}`,
    };
  });

  const option = {
    backgroundColor: "transparent",
    title: [
      {
        text: `当前产品: ${currentProduct.productName}`,
        left: "center",
        top: 10,
        textStyle: {
          color: "#fff",
          fontSize: 14,
        },
      },
    ],
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        return `
          <div style="font-weight:bold;margin-bottom:5px">${params.name}</div>
          <div style="margin:3px 0">时段: ${params.data.timeLabel}</div>
          <div style="margin:3px 0">耗时: ${params.data.duration}分钟</div>
        `;
      },
      backgroundColor: "rgba(0,0,0,0.8)",
      borderColor: "#333",
      textStyle: {
        color: "#fff",
        fontSize: 12,
      },
    },
    series: [
      {
        name: "检验进度",
        type: "pie",
        radius: ["45%", "35%"],
        center: ["50%", "50%"],
        itemStyle: {
          borderRadius: 6,
          borderColor: "#0f1325",
          borderWidth: 2,
        },
        label: {
          show: true,
          fontSize: 14,
          color: "#fff",
          weight: "bold",
        },
        labelLine: {
          show: true,
          length: 60,
          smooth: 0.1, // 引导线轻微弯曲
        },
        data: processedData.map((item, index) => ({
          name: item.name,
          value: item.duration,
          timeLabel: item.timeLabel,
          duration: item.duration,
          itemStyle: {
            color: item.color,
            shadowBlur: index === currentPhaseIndex ? 10 : 0,
            shadowColor: item.color,
          },
        })),
      },
    ],
  };

  chartInstance.setOption(option, true);
};

// 时间格式化 (HH:mm)
const formatTime = (isoString) => {
  const date = new Date(isoString);
  return date.toTimeString().slice(0, 5);
};

const handleResize = () => {
  chartInstance?.resize();
};

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
  if (chartInstance) {
    chartInstance.dispose();
    window.removeEventListener("resize", handleResize);
  }
});
</script>

<style scoped>
.multi-product-ring-container {
  width: 100%;
  height: 100%;
  min-height: 450px; /* 增加高度适应新元素 */
  position: relative;
  background-color: transparent;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
}
</style>
