<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";
import { qualityConsistentInspection } from "@/api/screens";

const props = defineProps({
  moduleId: {
    type: String,
    required: true,
  },
});

const chartRef = ref(null);
const chartData = ref([]);
let chartInstance = null;
let timer = null;
const currentProductIndex = ref(0);

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

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

  // 5秒切换产品批次
  timer = setInterval(() => {
    if (chartData.value.length > 0) {
      currentProductIndex.value =
        (currentProductIndex.value + 1) % chartData.value.length;
      updateChart();
    }
  }, 5000);
};

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

  const currentItem = chartData.value[currentProductIndex.value];

  // 计算总时长用于比例
  const totalDuration = currentItem.optionList.reduce(
    (sum, item) => sum + item.duration,
    0
  );

  const option = {
    backgroundColor: "transparent",
    title: [
      {
        text: `产品：${currentItem.productName}     批号：${currentItem.batchCode}`,
        subtext: `检验类型：${currentItem.inspectType}`,
        left: "center",
        top: 10,
        textStyle: {
          color: "#fff",
          fontSize: 16,
          fontWeight: "bold",
        },
        subtextStyle: {
          color: "#aaa",
          fontSize: 12,
          marginTop: 5,
        },
      },
    ],
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const item = currentItem.optionList[params.dataIndex];
        const percentage = ((item.duration / totalDuration) * 100).toFixed(1);
        return `
          <div style="font-weight:bold;margin-bottom:5px">${params.name}</div>
          <div style="margin:3px 0">检验时长: ${item.duration}小时</div>
          <div style="margin:3px 0">占比: ${percentage}%</div>
          <div style="margin:3px 0">状态: ${item.status === 1 ? "通过" : "未通过"}</div>
        `;
      },
      backgroundColor: "rgba(0,0,0,0.8)",
      borderColor: "#333",
      textStyle: {
        color: "#fff",
        fontSize: 12,
      },
    },
    series: [
      {
        name: "检验项目",
        type: "pie",
        radius: ["40%", "60%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        selectedMode: "multiple", // 允许选中单个扇区
        selectedOffset: 20, // 选中扇区的偏移量
        itemStyle: {
          borderRadius: 4,
          borderColor: "#0f1325",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}",
          fontSize: 12,
          color: "#fff",
          fontWeight: "normal",
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 30,
          smooth: 0.2,
        },
        data: currentItem.optionList.map((item, index) => ({
          name: item.optionName,
          value: item.duration,
          // 状态为1的项目默认选中(凸出)
          selected: item.status === 1,
          itemStyle: {
            color: getColorByIndex(index),
            // 状态为1的项目增加发光效果
            shadowBlur: item.status === 1 ? 10 : 0,
            shadowColor:
              item.status === 1 ? getColorByIndex(index) : "transparent",
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 15,
              shadowColor: getColorByIndex(index),
            },
          },
        })),
      },
    ],
  };

  chartInstance.setOption(option, true);
};

// 根据索引获取颜色
const getColorByIndex = (index) => {
  const colors = [
    "#5470C6",
    "#91CC75",
    "#EE6666",
    "#73C0DE",
    "#FAC858",
    "#3BA272",
    "#FC8452",
    "#9A60B4",
  ];
  return colors[index % colors.length];
};

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

// 加载数据
const loadData = async () => {
  try {
    const res = await qualityConsistentInspection(2);
    chartData.value = res.data;
    if (chartData.value.length > 0) {
      updateChart();
    }
  } catch (error) {
    console.error("加载数据失败:", error);
  }
};

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

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>
