<template>
  <el-card class="box-card">
    <el-empty v-if="noData" description="暂无数据"></el-empty>
    <div id="realtimeContainer"></div>
  </el-card>
</template>

<script setup>
import { defineExpose, onMounted, ref } from 'vue';
import { Line } from '@antv/g2plot';
import { formatChartTime } from 'utils/time';

const show = ref(false);
const noData = ref(true);
let bar = null;

// 设置图表
onMounted(() => {
  show.value = true;
});

// 设置图表
const setDate = data => {
  if (bar) {
    bar.destroy();
  }
  bar = new Line('realtimeContainer', {
    data,
    padding: 'auto',
    xField: 'time',
    yField: 'value',
    seriesField: 'category',
    slider: {
      start: 0.5,
      end: 1,
    },
    height: 700,
    // smooth: true,
    point: {
      size: 2,
      shape: 'circular',
      style: {
        fill: 'white',
        lineWidth: 2,
      },
    },
  });

  bar.render();
};

// 处理数据
const changeDate = value => {
  if (!value || !value.length) {
    noData.value = true;
    return;
  }
  noData.value = false;

  const arr = [];
  value.forEach(element => {
    const item = { ...element };

    const so2Item = { category: 'SO2(ppb)' };
    const saltItem = { category: '盐分阻抗(Ω)' };
    const environmentTemperatureItem = { category: '环温(℃)' };
    const environmentHumidityItem = { category: '环湿(RH%)' };
    const corrosion1Item = { category: '锌腐蚀电流(nA)' };
    const corrosion2Item = { category: '铜腐蚀电流(nA)' };
    const corrosion3Item = { category: '铝腐蚀电流(nA)' };
    const corrosion4Item = { category: '钢腐蚀电流(nA)' };

    so2Item.time = formatChartTime(item.time);
    so2Item.value = item.so2;
    arr.push(so2Item);

    saltItem.time = formatChartTime(item.time);
    saltItem.value = item.salt;
    arr.push(saltItem);

    environmentTemperatureItem.time = formatChartTime(item.time);
    environmentTemperatureItem.value = item.environmentTemperature;
    arr.push(environmentTemperatureItem);

    environmentHumidityItem.time = formatChartTime(item.time);
    environmentHumidityItem.value = item.environmentHumidity;
    arr.push(environmentHumidityItem);

    corrosion1Item.time = formatChartTime(item.time);
    corrosion1Item.value = item.corrosion1;
    arr.push(corrosion1Item);

    corrosion2Item.time = formatChartTime(item.time);
    corrosion2Item.value = item.corrosion2;
    arr.push(corrosion2Item);

    corrosion3Item.time = formatChartTime(item.time);
    corrosion3Item.value = item.corrosion3;
    arr.push(corrosion3Item);

    corrosion4Item.time = formatChartTime(item.time);
    corrosion4Item.value = item.corrosion4;
    arr.push(corrosion4Item);
  });
  setDate(arr);
};

defineExpose({ changeDate });
</script>
