<template>
  <BasicModal title="历史曲线" width="1000px" :height="600" v-bind="$attrs" @register="register">
    <LineMulti
      class="w-900px"
      height="500px"
      x-axis-prop-type="ttime"
      :prop-type-arr="propTypeMap"
      :chart-data="chartData"
      :option="{ textStyle: { color: '#fff' }, legend: { textStyle: { color: '#fff', top: 10 } } }"
    />
  </BasicModal>
</template>
<script lang="ts" setup>
  /**
   * 预警信息-历史曲线组件
   *
   * 使用方式，从外部使用 useModal 钩子并将 register 传入该组件
   *
   * 然后使用钩子提供的 openModal 并在调用时提供数据，数据参考下面 useModalInner 的回调
   */
  import { ref, defineEmits, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import dayjs from 'dayjs';
  import LineMulti from '/@/components/chart/LineMulti.vue';
  import { getHistoryData, listdays } from '../comment.api';

  const warningRecord = ref<{
    starttime: string;
    endtime: string;
    deviceid: string;
    devicename: string;
    devicetype: string;
    valuecode: string;
    valuename: string;
  }>();

  const chartData = ref<any>();

  defineEmits(['register']);

  const [register] = useModalInner(({ data, device }) => {
    warningRecord.value = data;
    refresh(device);
  });

  const params = computed(() => {
    if (!warningRecord.value) return {};
    const { starttime, endtime = dayjs(), deviceid, devicetype } = warningRecord.value;

    const gapstr = ['1s', '5s', '10s', '30s', '1m', '10m', '30m', '1h'];
    const gaparr = [1000, 5000, 10000, 30000, 60000, 600000, 1800000, 3600000, Infinity];
    // 需要根据预警信息的报警开始-报警结束（报警未解决即为当前时间）差值决定请求历史数据时使用的间隔
    // 例如差值为20s，那么应以1s为间隔，如果为5h，那么应为30min，为10h则应为1h
    // 如此，根据下面的逻辑获取到合适的间隔：
    // 设大小间隔为x、y（例如x=1000ms,y=5000ms），已知时间轴最少应分10份，则时间差z >= 10x且z < 10y时可以取该间隔
    const timediff = dayjs(endtime).diff(dayjs(starttime));
    let interval = '1s';
    for (let index = 0; index < gaparr.length - 1; index++) {
      const x = gaparr[index];
      const y = gaparr[index + 1];

      if (timediff >= 10 * x && timediff < 10 * y) {
        interval = gapstr[index];
      }
    }

    return {
      ttime_begin: starttime,
      ttime_end: endtime,
      gdeviceids: deviceid,
      strtype: devicetype,
      interval,
    };
  });

  const propTypeMap = computed(() => {
    if (!warningRecord.value) return new Map();
    const { valuecode, valuename } = warningRecord.value;
    return new Map([[valuecode, valuename]]);
  });

  async function refresh(device) {
    let result: any = { records: [] };
    if (device.stationtype === 'redis') {
      result = await getHistoryData({
        startTime: params.value.ttime_begin,
        endTime: params.value.ttime_end,
        deviceId: params.value.gdeviceids,
        ...params.value,
      });
    } else {
      result = await listdays(params.value).then((r) => {
        if (r.datalist) return r.datalist;
        return { total: 0, records: [] };
      });
    }
    result.records.forEach((e) => {
      return Object.assign(e, e.readData);
    });
    chartData.value = result.records;
  }
</script>
<style scoped lang="less">
  @import '/@/design/theme.less';
  @import '/@/design/vent/modal.less';
</style>
