<template>
  <div class="deviceStatistics card">
    <div class="card-head">
      <div class="title">内容数据</div>
      <SectionDate @change="getStatisticsContent" />
    </div>
    <div ref="chartRef" style="flex: 1"></div>
  </div>
</template>
<script setup>
import SectionDate from "@/components/sectionDate.vue";
import { statisticsContent } from "@/api/index";
import { onMounted, ref } from "vue";
import { format } from "@/utils";
import * as echarts from "echarts";
import { useResize } from "@/utils/hooks";

const d = new Date();
const chartRef = ref(null);
let myChart = null;

const option = ref({
  tooltip: {
    trigger: "axis",
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [],
    axisLabel: {
      formatter: function (item) {
        return format(item, "MM-DD");
      },
    },
  },
  yAxis: {
    type: "value",
  },
  series: [],
});

const getStatisticsContent = (req) => {
  statisticsContent(req).then((res) => {
    if (res.times && res.times.length) {
      option.value.xAxis.data = res.times.map((item) => (req.type == "hour" ? format(item) : format(item, "YYYY-MM-DD")));
      option.value.series = [
        {
          name: "SOS预警数组",
          data: res?.sosArr,
          type: "line",
        },
        {
          name: "围栏预警数组",
          data: res?.railArr,
          type: "line",
        },
        {
          name: "破坏预警数组",
          data: res?.destroyArr,
          type: "line",
        },
        {
          name: "生理预警数组",
          data: res?.healthArr,
          type: "line",
        },
      ];
      myChart.setOption(option.value);
    }
  });
};
useResize(() => {
  myChart.resize();
});
onMounted(() => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value);
    myChart.setOption(option.value);
  }

  getStatisticsContent({
    startDate: `${format(d, "YYYY-MM-DD")} 00:00:00`,
    endDate: `${format(d, "YYYY-MM-DD")} 23:59:59`,
    type: "hour",
  });
});
</script>
<style scoped lang="less">
.card {
  height: 380px;
  height: 100%;
  background: #ffffff;
  padding: 16px 10px;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  margin-bottom: 20px;
  .card-head {
    color: #061451;
    font-size: 18px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    transform: translateX(-10px);
    .title {
      &::before {
        display: inline-block;
        margin-right: 10px;
        content: "";
        width: 2px;
        height: 14px;
        border-radius: 20px;
        background: #061451;
      }
    }
  }
}
</style>
