<template>
  <div class="sliding-chart-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 initChart = () => {
  if (!chartRef.value) return;

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

// 数据转换函数
const transformData = (rawData) => {
  return rawData.map((item) => {
    // 处理工序名称列表
    const operationNames = item.operationNameList.filter(
      (name) => name !== "成品率"
    );

    // 处理工序数值列表 - 每3个一组：[目标值, 实际值, 差值]
    const operationNumbers = item.operationNumberList;
    const targetValues = [];
    const actualValues = [];

    for (let i = 0; i < operationNumbers.length; i += 3) {
      // 跳过成品率数据（通常是最后3个）
      if (i / 3 >= operationNames.length) break;

      targetValues.push(parseFloat(operationNumbers[i]));
      actualValues.push(parseFloat(operationNumbers[i + 1]));
    }

    // 获取成品率数据（最后3个值）
    const yieldIndex = operationNumbers.length - 3;
    const productTarget = parseFloat(operationNumbers[yieldIndex]);
    const productActual = parseFloat(operationNumbers[yieldIndex + 1]);

    return {
      title:
        `${item.materialModel}工序成品率对比` +
        (item.materialCategory ? `(${item.materialCategory})` : ""),
      xAxis: operationNames,
      productTarget: productTarget,
      productActual: productActual,
      series: [
        {
          name: "工序目标值",
          data: targetValues,
          color: "#5470C6",
          type: "line",
          symbol: "diamond",
          symbolSize: 10,
        },
        {
          name: "工序实际值",
          data: actualValues,
          color: "#91CC75",
          type: "line",
          symbol: "circle",
          symbolSize: 8,
        },
      ],
    };
  });
};

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

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

  // 计算工序差值
  const processDiff = currentData.series[0].data.map((target, index) => {
    const diff = currentData.series[1].data[index] - target;
    return parseFloat(diff.toFixed(1));
  });

  const option = {
    backgroundColor: "transparent",
    title: {
      text: currentData.title,
      left: "center",
      textStyle: {
        fontSize: 14,
        color: "#fff",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      textStyle: {
        color: "#fff",
      },
      formatter: (params) => {
        const processIndex = params[0].dataIndex;
        const diffValue = processDiff[processIndex];
        const diffColor = diffValue >= 0 ? "#91CC75" : "#EE6666";
        const diffSymbol = diffValue >= 0 ? "+" : "";

        let result = `<div style="font-weight:bold;margin-bottom:5px">${params[0].axisValue}</div>`;

        // 工序数据
        result += `
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#5470C6;margin-right:5px"></span>
            <span style="flex:1">工序目标值:</span>
            <span style="font-weight:bold">${params[0].value}%</span>
          </div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:#91CC75;margin-right:5px"></span>
            <span style="flex:1">工序实际值:</span>
            <span style="font-weight:bold">${params[1].value}%</span>
          </div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:10px;background:#EE6666;margin-right:5px"></span>
            <span style="flex:1">工序差值:</span>
            <span style="font-weight:bold;color:${diffColor}">${diffSymbol}${diffValue}%</span>
          </div>`;

        // 产品数据
        result += `
          <div style="border-top:1px solid rgba(255,255,255,0.2);margin:5px 0"></div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:2px;background:#5470C6;margin-right:5px"></span>
            <span style="flex:1">产品目标值:</span>
            <span style="font-weight:bold">${currentData.productTarget}%</span>
          </div>
          <div style="display:flex;align-items:center;margin:3px 0">
            <span style="display:inline-block;width:10px;height:2px;background:#91CC75;margin-right:5px"></span>
            <span style="flex:1">产品实际值:</span>
            <span style="font-weight:bold">${currentData.productActual}%</span>
          </div>`;

        return result;
      },
    },
    legend: {
      data: [
        ...currentData.series.map((item) => item.name),
        "产品目标值",
        "产品实际值",
      ],
      bottom: 10,
      textStyle: {
        color: "#fff",
      },
    },
    grid: {
      top: "10%",
      right: "12%",
      bottom: "15%", // 增加底部空间
      left: "8%",
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: currentData.xAxis,
      axisLine: {
        lineStyle: {
          color: "#fff",
        },
      },
      axisLabel: {
        color: "#fff",
        interval: 0,
        rotate: currentData.xAxis.some((name) => name.length > 4) ? 30 : 0,
      },
    },
    yAxis: {
      type: "value",
      name: "成品率(%)",
      nameTextStyle: {
        color: "#fff",
        padding: [0, 50, 20, 0],
      },
      min: 70, // 固定最小值，确保产品线可见
      max: 100,
      axisLine: {
        lineStyle: {
          color: "#fff",
        },
      },
      axisLabel: {
        color: "#fff",
        formatter: "{value}%",
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255,255,255,0.1)",
        },
      },
    },
    series: [
      // 工序目标值(实线)
      {
        ...currentData.series[0],
        lineStyle: {
          color: "#5470C6",
          width: 3,
        },
        itemStyle: {
          color: "#5470C6",
          borderColor: "#fff",
          borderWidth: 1,
        },
        label: {
          show: true,
          position: "top",
          formatter: (params) => {
            const diff = processDiff[params.dataIndex];
            const diffColor = diff >= 0 ? "#91CC75" : "#EE6666";
            const diffSymbol = diff >= 0 ? "+" : "";
            return `${params.value}% (${diffSymbol}${diff}%)`;
          },
          color: "#fff",
          rich: {
            diff: {
              color: "#EE6666",
              padding: [0, 0, 0, 5],
            },
          },
        },
      },
      // 工序实际值(实线)
      {
        ...currentData.series[1],
        lineStyle: {
          color: "#91CC75",
          width: 3,
        },
        itemStyle: {
          color: "#91CC75",
          borderColor: "#fff",
          borderWidth: 1,
        },
        label: {
          show: false, // 只在目标值上显示标签
        },
      },
      // 产品目标值横线(虚线)
      {
        name: "产品目标值",
        type: "line",
        data: currentData.xAxis.map(() => currentData.productTarget),
        symbol: "none",
        lineStyle: {
          color: "#5470C6",
          width: 2,
          type: "dashed",
        },
        markLine: {
          silent: true,
          symbol: "none",
          lineStyle: {
            color: "#5470C6",
            width: 2,
            type: "dashed",
          },
          label: {
            show: true,
            position: "end",
            formatter: "产品目标: {c}%",
            color: "#5470C6",
          },
          data: [
            {
              yAxis: currentData.productTarget,
            },
          ],
        },
      },
      // 产品实际值横线(虚线)
      {
        name: "产品实际值",
        type: "line",
        data: currentData.xAxis.map(() => currentData.productActual),
        symbol: "none",
        lineStyle: {
          color: "#91CC75",
          width: 2,
          type: "dashed",
        },
        markLine: {
          silent: true,
          symbol: "none",
          lineStyle: {
            color: "#91CC75",
            width: 2,
            type: "dashed",
          },
          label: {
            show: true,
            position: "end",
            formatter: "产品实际: {c}%",
            color: "#91CC75",
          },
          data: [
            {
              yAxis: currentData.productActual,
            },
          ],
        },
      },
    ],
    animationDuration: 500,
  };

  chartInstance.setOption(option, true);
};

const nextChart = () => {
  currentIndex.value = (currentIndex.value + 1) % chartData.value.length;
  updateChart();
  resetTimer();
};

const resetTimer = () => {
  if (timer) clearInterval(timer);
  startTimer();
};

const startTimer = () => {
  timer = setInterval(nextChart, 5000);
};

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

const chartData = ref([]);

const loadData = async () => {
  const rowData = await qualityReport();
  chartData.value = transformData(rowData.data);
};

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

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

<style scoped>
/* 样式保持不变 */
.sliding-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: transparent;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
}
</style>
