<template>
  <el-dialog
    class="phototimeDialog"
    title="当天图片统计"
    :visible.sync="isShowTime"
    :close-on-click-modal="false"
    @close="hide"
    width="100%"
  >
    <h3>{{ rowData.cmdid }}</h3>
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column
        prop="channel"
        label="通道"
        width="120"
      ></el-table-column>

      <el-table-column
        prop="totalCount"
        label="总数"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="presetId"
        label="预置位"
        width="120"
      ></el-table-column>
      <el-table-column prop="anomalies" label="异常时间点"></el-table-column>
    </el-table>
  </el-dialog>
</template>

<script>
import { getphotoApi } from "@/utils/api/reportApi";

export default {
  data() {
    return {
      isShowTime: false,
      rowData: {},
      paramsData: {},
      picListData: [],
      picloading: false,
      radio: "-1",
      page: 1,
      pageSize: 400,
      total: 0,
      tableData: [],
    };
  },
  methods: {
    // 显示弹窗并加载数据
    display(row, params) {
      this.isShowTime = true;
      this.rowData = row;
      this.paramsData = params;
      this.radio = params.channelid;
      this.getPhotoList();
    },
    // 关闭弹窗
    hide() {
      this.isShowTime = false;
    },
    // 获取图片数据
    getPhotoList() {
      this.picloading = true;
      getphotoApi({
        dyid: this.rowData.dyId,
        lineid: this.rowData.lineId,
        towerid: this.rowData.towerId,
        channelid: this.radio,
        termid: this.rowData.id,
        starttime: this.paramsData.starttime,
        endtime: this.paramsData.endtime,
        pageindex: this.page,
        pagesize: this.pageSize,
      })
        .then((res) => {
          this.picListData = res.data.list;
          this.total = res.data.total;
          this.processData();
        })
        .catch((err) => {
          console.error("获取图片数据失败:", err);
        })
        .finally(() => {
          this.picloading = false;
        });
    },
    // 处理数据
    processData() {
      const channelPresetMap = {};

      // 遍历数据，按通道和预置位分组
      this.picListData.forEach((photo) => {
        const channel = photo.channnelname;
        const presetId = photo.presetId;
        const hour = new Date(photo.photoTime).getHours();
        console.log("我是时间", hour);
        const key = `${channel}-${presetId}`;

        if (!channelPresetMap[key]) {
          channelPresetMap[key] = {
            channel: channel,
            presetId: presetId,
            totalCount: 0,
            hourlyData: new Array(24).fill(0),
          };
        }

        channelPresetMap[key].totalCount++;
        channelPresetMap[key].hourlyData[hour]++;
      });

      // 将数据按通道分组
      const groupedData = this.groupByChannel(channelPresetMap);
      console.log(groupedData);
      // 处理每个通道和预置位的数据
      this.tableData = groupedData.flatMap((group) => {
        return group.map((item) => {
          const anomalies = this.detectAnomalies(item.hourlyData);
          return {
            channel: item.channel,
            presetId: `预置位:${item.presetId}`,
            totalCount: item.totalCount,
            anomalies: anomalies.join(", "),
          };
        });
      });
    },
    // 按通道分组
    groupByChannel(channelPresetMap) {
      const grouped = {};

      Object.values(channelPresetMap).forEach((item) => {
        const channel = item.channel;
        if (!grouped[channel]) {
          grouped[channel] = [];
        }
        grouped[channel].push(item);
      });

      return Object.keys(grouped)
        .sort()
        .map((channel) => grouped[channel]);
    },
    // 检测异常时间点
    detectAnomalies(hourlyData) {
      const anomalies = [];
      const now = new Date(); // 获取当前时间
      const currentHour = now.getHours(); // 获取当前小时

      hourlyData.forEach((count, hour) => {
        // 只处理当前时间之前的小时数据
        if (hour <= currentHour) {
          if (count > 2) {
            anomalies.push(`${hour}:00 - 多${count - 2}张`);
          } else if (count < 2) {
            anomalies.push(`${hour}:00 - 少${2 - count}张`);
          }
        }
      });

      return anomalies;
    },
    // 分页逻辑
    handleCurrentChange(val) {
      this.page = val;
      this.getPhotoList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPhotoList();
    },
  },
};
</script>

<style lang="less">
.phototimeDialog {
  h3 {
    margin-bottom: 20px;
  }
  .el-dialog {
    height: 100%;
    margin: 0px;
    .el-dialog__body {
      height: calc(100% - 70px);
      padding: 8px;
    }
  }
}
</style>
