<template>
  <el-dialog title="历史记录" v-model="visible" width="70%" destroy-on-close :close-on-click-modal="false" @close="visible = false">
    <div class="monitoringMap" id="mapcontainer"></div>
    <div ref="chartRef" class="chart"></div>
    <div :style="{ display: 'none' }">
      <InfoWindow class="infoBox" :value="locationInfo" @close="InfoWin.close()" />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { debounce, format } from "@/utils";
import { MapCustom } from "@/utils/mapCustom";
import { nextTick, onMounted, onUnmounted, PropType, ref, watch } from "vue";
import * as echarts from "echarts";
import { dataRecord, locateRecord } from "@/api";
import { TDevice } from "@/api/index.d";
import ViaMarker from "@/assets/img/via-marker.png";
import endMarker from "@/assets/img/end-marker.png";
import startMarker from "@/assets/img/start-marker.png";
import InfoWindow from "@/components/InfoWindow.vue";

const chartRef = ref(null);
let myChart = null;
let InfoWin = null;
let newMap = null;
const visible = ref(false);
let locationInfo = ref({});
defineExpose({
  visible,
});
const props = defineProps({
  recordInofo: {
    type: Object as PropType<TDevice.IUseRecordRes>,
    default: () => {},
  },
});

const options = {
  tooltip: {
    trigger: "axis",
    formatter: function (params) {
      let unit = { 0: "次/分", 1: "%", 2: "℃" };
      var res = format(Number(params[0].name)) + "<br/>";
      res += params
        .map(function (param, index) {
          return param.marker + param.seriesName + "：" + param.value + unit[index] + "<br/>";
        })
        .join("");
      return res;
    },
  },
  legend: {
    data: ["心率", "体表温度", "血氧"],
  },
  grid: {
    left: "0%",
    right: "4%",
    bottom: "6%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [],
    axisLabel: {
      formatter: function (item) {
        return format(Number(item), "HH:mm:ss");
      },
    },
  },
  yAxis: {
    type: "value",
  },
  dataZoom: [
    {
      type: "slider", //slider表示有滑动块的，inside表示内置的
      start: 90, // 左边在 10% 的位置。
      end: 100, // 右边在 60% 的位置。
      show: true,
      xAxisIndex: [0],
      handleSize: 0, //滑动条的 左右2个滑动条的大小
      height: 12, //组件高度
      bottom: -2, //右边的距离
      borderColor: "#eee",
      fillerColor: "#E7E7E7",
      backgroundColor: "#eee", //两边未选中的滑动条区域的颜色
      showDataShadow: false, //是否显示数据阴影 默认auto
      showDetail: false, //即拖拽时候是否显示详细数值信息 默认true
      realtime: true, //是否实时更新
      filterMode: "filter",
      handleStyle: {
        borderRadius: "20",
      },
    },
  ],
  series: [
    {
      itemStyle: {
        color: "#FF4241",
      },
      name: "心率",
      type: "line",
      showSymbol: false,
      data: [],
      time: [],
    },
    {
      itemStyle: {
        color: "#12CCA2",
      },
      name: "血氧",
      type: "line",
      showSymbol: false,
      data: [],
      time: [],
    },
    {
      itemStyle: {
        color: "#FF7D00",
      },
      showSymbol: false,
      name: "体表温度",
      type: "line",
      data: [],
      time: [],
    },
  ],
};
watch(visible, (val) => {
  if (val) {
    nextTick(() => {
      newMap = new MapCustom({ dom: "mapcontainer" });
      myChart = echarts.init(chartRef.value);
      getLocateRecord();
      dataRecord({ useRecordId: props.recordInofo.id }).then((res) => {
        if (res.healthData && res.healthData.length) {
          res.healthData.forEach((item) => {
            options.xAxis.data.push(item.time);
            options.series[0].data.push(item.hr);
            options.series[1].data.push(item.bo);
            options.series[2].data.push(item.temp);
          });
        }
        myChart.setOption(options);
      });
    });
  } else {
    myChart = null;
    newMap = null;
    window.removeEventListener("resize", handleResize);
  }
});
const getLocateRecord = () => {
  locateRecord({
    deviceId: props.recordInofo.deviceId,
    startDate: props.recordInofo.createTime,
    endDate: props.recordInofo.updateTime,
  }).then((res) => {
    if (res && res.length) {
      let list = res;
      newMap.clearMap();
      newMap.setCenter([list[0].lng, list[0].lat]);
      newMap.polyline(list);
      let startIcon = newMap.newIcon({
        image: startMarker,
        size: [20, 29],
      });
      let endIcon = newMap.newIcon({
        image: endMarker,
        size: [20, 29],
      });
      let ViaIcon = newMap.newIcon({
        image: ViaMarker,
        size: [20, 29],
      });
      let markers = [];
      list.forEach((item, index) => {
        if (list.length < 50) {
          let marker: any = "";
          if (index == 0) {
            marker = newMap.marker({ icon: endIcon, position: [item.lng, item.lat], zIndex: 13 });
          } else if (index == list.length - 1) {
            marker = newMap.marker({ icon: startIcon, position: [item.lng, item.lat], zIndex: 13 });
          } else {
            marker = newMap.marker({ icon: ViaIcon, position: [item.lng, item.lat], zIndex: 12 });
          }
          marker.on("click", () => {
            locationInfo.value = item;
            InfoWin = newMap.infoWindow();
            InfoWin.open(newMap.map, marker.getPosition());
          });
          markers.push(marker);
        } else {
          if (index % 5 == 0) {
            let marker: any = "";
            if (index == 0) {
              marker = newMap.marker({ icon: endIcon, position: [item.lng, item.lat], zIndex: 13 });
            } else if (index == list.length - 1) {
              marker = newMap.marker({ icon: startIcon, position: [item.lng, item.lat], zIndex: 13 });
            } else {
              marker = newMap.marker({ icon: ViaIcon, position: [item.lng, item.lat], zIndex: 12 });
            }
            marker.on("click", () => {
              locationInfo.value = item;
              InfoWin = newMap.infoWindow();
              InfoWin.open(newMap.map, marker.getPosition());
            });

            markers.push(marker);
          }
        }
      });
      newMap.map.add(markers);
    }
  });
};
const handleResize = debounce(() => {
  myChart && myChart.resize();
}, 200);
onMounted(() => {
  window.addEventListener("resize", handleResize);
});
</script>

<style scoped lang="less">
.monitoringMap {
  height: 300px;
}
.chart {
  height: 300px;
  margin-top: 20px;
}
</style>
