<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, getPhotoStatApi } 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 photoTime = new Date(photo.photoTime);

        // 计算半小时段索引（0-47）
        const hour = photoTime.getHours();
        const minute = photoTime.getMinutes();
        const halfHourIndex = hour * 2 + (minute >= 30 ? 1 : 0);

        const key = `${channel}-${presetId}`;

        if (!channelPresetMap[key]) {
          channelPresetMap[key] = {
            channel: channel,
            presetId: presetId,
            totalCount: 0,
            hourlyData: new Array(48).fill(0), // 改为48个半小时段
          };
        }

        channelPresetMap[key].totalCount++;
        channelPresetMap[key].hourlyData[halfHourIndex]++; // 更新对应半小时段
      });

      // 将数据按通道分组
      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(", "),
            anomalies: anomalies.length > 0 ? 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 方法
    detectAnomalies(hourlyData) {
      const anomalies = [];
      const startTime = new Date(this.paramsData.starttime);
      const endTime = new Date(this.paramsData.endtime);

      // 生成时间范围内的所有半小时时间点（如 10:00, 10:30, 11:00）
      const halfHourlyPoints = this.getHalfHourlyPoints(startTime, endTime);

      halfHourlyPoints.forEach((timeStr) => {
        // 将时间字符串（如 "10:00"）转换为对应的半小时段索引（0-47）
        const index = this.timeToHalfHourIndex(timeStr);
        const count = hourlyData[index] || 0;

        // 每半小时期望1张，检测多/少
        if (count > 1) {
          anomalies.push(`${timeStr} - 多${count - 1}张`);
        } else if (count < 1) {
          anomalies.push(`${timeStr} - 少${1 - count}张`);
        }
      });

      return anomalies;
    },
    // 获取时间范围内的小时列表
    getHoursInRange(startTime, endTime) {
      const startHour = startTime.getHours();
      const endHour = endTime.getHours();
      const hours = [];

      if (startTime <= endTime) {
        // 同一天或结束时间大于等于开始时间
        for (let h = startHour; h <= endHour; h++) {
          hours.push(h);
        }
      } else {
        // 跨天情况，添加从startHour到23，再到0到endHour
        for (let h = startHour; h < 24; h++) {
          hours.push(h);
        }
        for (let h = 0; h <= endHour; h++) {
          hours.push(h);
        }
      }
      return hours;
    },
    // 获取时间范围内的所有半小时时间点（格式：HH:mm）
    getHalfHourlyPoints(startTime, endTime) {
      const points = [];
      let current = new Date(startTime);

      // 对齐到最近的半小时（如 10:15 → 10:00）
      current.setMinutes(current.getMinutes() >= 30 ? 30 : 0, 0, 0);

      while (current <= endTime) {
        const hours = current.getHours().toString().padStart(2, "0");
        const minutes = current.getMinutes().toString().padStart(2, "0");
        points.push(`${hours}:${minutes}`);
        current = new Date(current.getTime() + 30 * 60 * 1000); // 增加30分钟
      }

      return points;
    },
    // 时间字符串（HH:mm） → 半小时段索引（0-47）
    timeToHalfHourIndex(timeStr) {
      const [hours, minutes] = timeStr.split(":").map(Number);
      return hours * 2 + (minutes >= 30 ? 1 : 0);
    },
    // // 检测异常时间点
    // 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>
