<!-- 实时数据图表 -->
<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import Container from "./Base/Container.vue";
import { useWsStore } from "../store";
const cargoChart = ref(null);
const chart = ref(null);
const options = {
  color: ["#99D66C", "#5B9BFF"],
  grid: {
    top: 72,
    bottom: 72,
    left: 112,
    right: 88,
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  xAxis: {
    type: "value",
    position: "top",
    splitLine: {
      lineStyle: {
        type: "dashed",
        color: "#ccc8",
      },
    },
    axisLabel: {
      fontSize: 24,
      color: "#fff",
    },
    minInterval: 1,
  },
  yAxis: {
    type: "category",
    axisLine: { show: false },
    axisLabel: { show: false },
    axisTick: { show: false },
    splitLine: { show: false },
    data: ["废片", "阶段成品"],
    axisLabel: {
      fontSize: 24,
      color: "#fff",
    },
  },
  title: [
    {
      text: 0 + "片",
      left: "50%",
      textAlign: "center",
      top: "82%",
      textStyle: {
        fontSize: 32,
        color: "#fff",
      },
    },
    {
      text: 0 + "片",
      left: "50%",
      textAlign: "center",
      top: "44%",
      textStyle: {
        fontSize: 32,
        color: "#fff",
      },
    },
  ],
  series: [
    {
      name: "数量",
      type: "bar",
      stack: "Total",
      showBackground: true,
      barWidth: "32",
      colorBy: "data",
      data: [
        { value: 0, label: { fontSize: 28 } },
        { value: 0, label: { fontSize: 28 } },
      ],
    },
  ],
};

function updateChartOption(product, scrap) {
  if (!chart.value) chart.value = echarts.init(cargoChart.value);
  else {
    chart.value.dispose();
    chart.value = echarts.init(cargoChart.value);
  }
  options.title[0].text = product + "片";
  options.title[1].text = scrap + "片";
  options.series[0].data[0].value = product;
  options.series[0].data[1].value = scrap;
  chart.value.setOption(options);
}

const store = useWsStore();
const productAmount = ref(store.data1.realTimeData?.product || 0);
const scrapAmount = ref(store.data1.realTimeData?.scrap || 0);
store.$subscribe((mutation, state) => {
  productAmount.value = state.data1.realTimeData?.product || 0;
  scrapAmount.value = state.data1.realTimeData?.scrap || 0;
  updateChartOption(productAmount.value, scrapAmount.value);
});

onMounted(() => {
  cargoChart.value.classList.add("h-full");
  updateChartOption(productAmount.value, scrapAmount.value);
});
</script>

<template>
  <Container class="cargo" title="实时数据" icon="cube">
    <div ref="cargoChart" class="cargo-chart"></div>
  </Container>
</template>

<style scoped>
.cargo {
  height: 640px;
  width: 80%;
  align-self: self-end;
}

.cargo-chart {
  height: 100%;
}
</style>
