<template>
  <div class="quality-target-bar-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 { qualityReport } from "@/api/screens";

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

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

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

  // 启动轮播定时器
  startAutoPlay();
};

// 启动自动轮播
const startAutoPlay = () => {
  if (timer) clearInterval(timer);
  timer = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % chartData.value.length;
    updateChart();
  }, 3000); // 3秒切换一次
};

// 数据转换函数 - 只提取成品率数据
const transformData = (rawData) => {
  return rawData.map((item) => {
    const operationNumbers = item.operationNumberList;
    const yieldIndex = operationNumbers.length - 3;

    return {
      name:
        item.materialModel +
        (item.materialCategory ? `(${item.materialCategory})` : ""),
      target: parseFloat(operationNumbers[yieldIndex]),
      actual: parseFloat(operationNumbers[yieldIndex + 1]),
      diff: parseFloat(operationNumbers[yieldIndex + 2]),
    };
  });
};

// 更新图表数据 - 只显示当前索引的产品
const updateChart = () => {
  if (!chartInstance || !chartData.value.length) return;

  const currentData = chartData.value[currentIndex.value];

  const option = {
    backgroundColor: "transparent",
    title: {
      text: currentData.name,
      left: "center",
      textStyle: {
        fontSize: 14,
        color: "#fff",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      textStyle: {
        color: "#fff",
      },
      formatter: () => {
        const diffColor = currentData.diff >= 0 ? "#91CC75" : "#EE6666";
        const diffSymbol = currentData.diff >= 0 ? "+" : "";

        return `
          <div style="font-weight:bold;margin-bottom:5px">${currentData.name}</div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;background:#5470C6;margin-right:5px"></span>
            <span style="flex:1">目标成品率:</span>
            <span style="font-weight:bold">${currentData.target}%</span>
          </div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;background:#91CC75;margin-right:5px"></span>
            <span style="flex:1">实际成品率:</span>
            <span style="font-weight:bold">${currentData.actual}%</span>
          </div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;background:${diffColor};margin-right:5px"></span>
            <span style="flex:1">差值:</span>
            <span style="font-weight:bold;color:${diffColor}">${diffSymbol}${currentData.diff}%</span>
          </div>
        `;
      },
    },
    legend: {
      data: ["目标成品率", "实际成品率"],
      bottom: 35,
      textStyle: {
        color: "#fff",
      },
      itemWidth: 20,
      itemHeight: 10,
    },
    grid: {
      top: "10%",
      right: "10%",
      bottom: "15%",
      left: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: ["产品成品率对比"],
      axisLine: {
        lineStyle: {
          color: "#fff",
        },
      },
      axisLabel: {
        color: "#fff",
      },
    },
    yAxis: {
      type: "value",
      name: "成品率(%)",
      nameTextStyle: {
        color: "#fff",
        padding: [0, 0, 0, 40],
      },
      min: 0,
      max: 100,
      axisLine: {
        lineStyle: {
          color: "#fff",
        },
      },
      axisLabel: {
        color: "#fff",
        formatter: "{value}%",
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255,255,255,0.1)",
        },
      },
    },
    series: [
      {
        name: "目标成品率",
        type: "bar",
        barWidth: 40,
        data: [
          {
            value: currentData.target,
            itemStyle: {
              color: "#5470C6",
            },
          },
        ],
        label: {
          show: true,
          position: "top",
          formatter: "{c}%",
          color: "#fff",
        },
      },
      {
        name: "实际成品率",
        type: "bar",
        barWidth: 40,
        data: [
          {
            value: currentData.actual,
            itemStyle: {
              color:
                currentData.actual >= currentData.target
                  ? "#91CC75"
                  : "#EE6666",
            },
          },
        ],
        label: {
          show: true,
          position: "top",
          formatter: (params) => {
            const diff = currentData.diff;
            const diffColor = diff >= 0 ? "#91CC75" : "#EE6666";
            const diffSymbol = diff >= 0 ? "+" : "";
            return `${params.value}% {diff|${diffSymbol}${diff}%}`;
          },
          color: "#fff",
          rich: {
            diff: {
              color: "#EE6666",
              padding: [0, 0, 0, 5],
            },
          },
        },
      },
    ],
    animationDuration: 500,
  };

  chartInstance.setOption(option, true);
};

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

const loadData = async () => {
  try {
    const rowData = await qualityReport();
    chartData.value = transformData(rowData.data);
    if (chartData.value.length > 0) {
      initChart();
    }
  } catch (error) {
    console.error("加载数据失败:", error);
  }
};

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

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

<style scoped>
.quality-target-bar-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;
  background-color: transparent;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
}
</style>
