<template>
  <div class="dataPushDialog">
    <p style="text-align: right;">
      <label>时间范围：</label>
      <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          @change="checkTimeRange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          :picker-options="pickerOptions"
      ></el-date-picker>
    </p>
    <!-- {{ startDate }}
    <el-time-picker
      v-model="startTime"
      @change="startTimeChange"
      placeholder="开始时间"
    >
    </el-time-picker>
    <span style="margin: 0 5px">至</span>
    {{ endDate }}
    <el-time-picker
      v-model="endTime"
      @change="endTimeChange"
      placeholder="结束时间"
    >
    </el-time-picker> -->
    <p class="table-title">实时数据推送：</p>
    <table-data
        height="188"
        :headers="tableData.header"
        :tableData="tableData.body"
    ></table-data>
    <p class="table-title">周期数据推送：</p>
    <table-data
        ref="table2"
        :hasLoading="hasLoading"
        height="200"
        :headers="tableData2.header"
        :tableData="tableData2.body"
        :key="hasLoading"
    ></table-data>
  </div>
</template>

<script>
import {formatDate} from "@/common/js/utils.js";
import {tableQuery, tableRealTime} from "@/common/api/homepageSignal.js";

export default {
  data() {
    return {
      dirObj: {
        "1": "北",
        "2": "东北",
        "3": "东",
        "4": "东南",
        "5": "南",
        "6": "西南",
        "7": "西",
        "8": "西北",
      },
      dateRange: [], // 初始化为空数组
      // pickerOptions: {
      //   disabledDate: this.disabledDate, // 使用外部定义的 disabledDate 函数
      //   // disabledTime: this.disabledHours,
      // },
      tableInterval: null,
      hasLoading: false,
      startDate: "",
      endDate: "",
      startTime: "",
      endTime: "",
      tableData: {
        name: "实时数据推送",
        key: "curDataPush",
        clickable: true,
        header: [
          {label: "时间", key: "time", align: "center"},
          {label: "方向", key: "dirName", align: "center"},
          {label: "车道", key: "laneSort", align: "center"},
          {label: "排队长度", key: "queueLength", align: "center"},
          {label: "头车位置", key: "firstCarPosition", align: "center"},
          {label: "末车位置", key: "endCarPosition", align: "center"},
        ],
        body: [],
      },

      tableData2: {
        name: "周期数据推送",
        key: "weekDataPush",
        clickable: true,
        header: [
          {label: "时间", key: "time", headWidth: 160, align: "center"},
          {label: "方向", key: "dirName", align: "center"},
          {label: "车道", key: "laneSort", align: "center"},
          {label: "流量", key: "flow", align: "center"},
          {label: "速度", key: "speed", align: "center"},
          {label: "最大排队长度", key: "queueLength", align: "center"},
          {label: "平均延误", key: "delayTime", align: "center"},
          {label: "平均停车次数", key: "stopTimes", align: "center"},
          {label: "平均车头时距", key: "vehheadTime", align: "center"},
          {label: "时间占有率(%)", key: "timeOccupancy", align: "center"},
          {label: "空间占有率(%)", key: "vehicleNumsRatioMean", align: "center"},
        ],
        body: [],
      },
    };
  },
  computed: {
    pickerOptions() {
      const now = new Date(); // 当前日期
      const yesterday = new Date(now); // 昨天
      yesterday.setDate(now.getDate() - 1);

      return {
        disabledDate(time) {
          // 禁用选择日期
          return (
              time > now || time < new Date(yesterday.setHours(0, 0, 0, 0)) // 大于今天 // 小于昨天的凌晨
          );
        },
      };
    },
  },
  props: ["propsData"],
  components: {
    tableData: () =>
        import(/*webpackChunkName:"tableData" */ "../tableData.vue"),
  },
  beforeDestroy() {
    if (this.tableInterval) {
      clearInterval(this.tableInterval);
      this.tableInterval = null;
    }
  },
  mounted() {
    this.initTable(1);
    this.tableInterval = setInterval(() => {
      this.initTable(0);
    }, 5000);
    // this.startDate = formatDate(
    //   new Date(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 1))
    // );
    // this.endDate = formatDate(new Date());
  },
  methods: {
    initTable(val) {
      tableRealTime({
        crossId: this.propsData.id,
        isFirstInvoke: val,
      }).then((res) => {
        if (res && res.data) {
          this.$refs.table2?.loadingFinish();
          this.hasLoading = false;
          const data = res.data.content;
          this.handleTableData(data);
        }
      });
    },
    checkTimeRange() {
      if (this.dateRange.length === 2) {
        const start = new Date(this.dateRange[0]);
        const end = new Date(this.dateRange[1]);
        const now = new Date();
        const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
        const oneHour = 60 * 60 * 1000; // 一小时的毫秒数

        // 计算日期范围的天数差
        const daysDiff = Math.round(Math.abs((start - end) / oneDay));

        if (daysDiff > 1) {
          this.$message.error("只能选择一天内的时间范围");
          this.dateRange = [];
          return;
        }
        // 检查开始时间和结束时间是否大于当前时间
        if (start > now || end > now) {
          this.$message.error("开始时间和结束时间不能大于当前时间");
          this.dateRange = [];
          return;
        }
        // 计算时间范围的毫秒数差
        const timeDiff = Math.abs(start - end);

        if (timeDiff > oneHour) {
          this.$message.error("开始时间和结束时间应在1小时内");
          this.dateRange = [];
          return;
        }
        this.getTableData();
      }
    },
    // disabledDate(time) {
    //   const currentDate = new Date();
    //   const previousDay = new Date(currentDate);
    //   previousDay.setDate(currentDate.getDate() - 1);

    //   return (
    //     time.getTime() < previousDay.getTime() ||
    //     time.getTime() > currentDate.getTime() ||
    //     (this.dateRange.length > 0 &&
    //       time.getTime() - this.dateRange[0] > 3600000)
    //   );
    // },
    startTimeChange() {
      this.getTableData();
    },
    endTimeChange() {
      this.getTableData();
    },
    getTableData() {
      if (this.tableInterval) {
        clearInterval(this.tableInterval);
        this.tableInterval = null;
      }
      this.hasLoading = true;
      tableQuery({
        crossId: this.propsData.id,
        // endTime: "2023-10-14 11:00:00",
        // startTime: "2023-10-14 10:00:00",
        endTime: this.dateRange[1],
        startTime: this.dateRange[0],
      }).then((res) => {
        if (res && res.data) {
          this.$refs.table2?.loadingFinish();
          this.hasLoading = false;
          const data = res.data.content;
          this.handleTableData(data);
        }
      });
    },
    handleTableData(data) {
      // 先按时间倒序排序 时间相同则按方向排序 方向相同则按车道排序
      if (data.realTimeData) {
        this.tableData.body = (data.realTimeData.map((item) => {
          item.dirName = this.dirObj[item.dir];
          return item;
        })).sort((a, b) => {
          if (new Date(b.time).getTime() !== new Date(a.time).getTime()) {
            return (new Date(b.time).getTime() - new Date(a.time).getTime())
          } else {
            if (Number(a.dir) !== Number(b.dir)) {
              return (Number(a.dir) - Number(b.dir))
            } else {
              return (Number(a.laneSort) - Number(b.laneSort))
            }
          }
        });
      }
      if (data.cycleData) {
        this.tableData2.body = data.cycleData.map((item) => {
          item.dirName = this.dirObj[item.dir];
          return item;
        }).sort((a, b) => {
          if (new Date(b.time).getTime() !== new Date(a.time).getTime()) {
            return (new Date(b.time).getTime() - new Date(a.time).getTime())
          } else {
            if (Number(a.dir) !== Number(b.dir)) {
              return (Number(a.dir) - Number(b.dir))
            } else {
              return (Number(a.laneSort) - Number(b.laneSort))
            }
          }
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.dataPushDialog {
  background: #fff;
  padding: 20px;

  .table-title {
    margin: 10px 0;
    font-size: 16px;
  }

  /deep/ .el-input__inner {
    height: 30px;
  }

  /deep/ .el-input__icon,
  /deep/ .el-range-separator {
    line-height: 20px;
  }
}
</style>
