<template>
  <div class="app-container">
    <el-row :gutter="15" type="flex">
      <el-col :span="18">
        <el-row :gutter="15" type="flex">
          <el-col :span="6">
            <div class="status-container">
              <h3 class="status-title">定位状态</h3>
              <div class="status-group">
                <div class="status-item">
                  <span class="count online">{{ CameraOnlineData.on }}</span>
                  <div class="label">
                    <svg-icon icon-class="camera" />在线数量
                  </div>
                </div>
                <div class="status-item">
                  <span class="count offline">{{ CameraOnlineData.off }}</span>
                  <div class="label">
                    <svg-icon icon-class="camera" />离线数量
                  </div>
                </div>
              </div>
            </div>
            <div class="status-container">
              <h3 class="status-title">视频分析任务启动状态</h3>
              <div class="status-group">
                <div class="status-item" style="height: 300px">
                  <pie-chart
                    :option="VideoAnalysisOnlineData"
                    v-if="isDataLoaded"
                  />
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="18">
            <div class="status-container">
              <h3 class="status-title both-end">
                <span>
                  <template v-if="selectVidoe.length === 2">
                    <span>{{ cameraName }}的{{ algorithmName }}</span>
                  </template>
                  <template v-else>
                    <span>请选择摄像头和算法</span>
                  </template></span
                >
                <el-cascader
                  v-model="selectVidoe"
                  @change="handleCascaderChange"
                  :options="videoList"
                  :props="{
                    value: 'value',
                    label: 'label',
                    children: 'children',
                  }"
                  clearable
                ></el-cascader>
              </h3>
              <div class="video-box" ref="videoContainer">
                <div class="video-container">
                  <video
                    id="videoPlayer"
                    ref="videoPlayer"
                    class=""
                    style="width: 100%; height: 100%"
                    autoplay
                    muted
                    controls
                    preload="auto"
                  ></video>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="15" type="flex">
          <el-col :span="24">
            <div class="status-container">
              <h3 class="status-title both-end">
                <span>统计分析(条/天)</span>
                <el-date-picker
                  v-model="pickerDate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="getData"
                >
                </el-date-picker>
              </h3>
              <line-chart :chartData="StatisticsData" v-if="isDataLoaded" />
            </div>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="6">
        <div class="status-container h100">
          <h3 class="status-title both-end">
            <span>实时报警</span>
          </h3>
          <div
            class="card-box"
            v-for="item of alarmList"
            :key="item.logId"
            @click="lookAlarm(item)"
          >
            <el-row>
              <el-col :span="12">
                <dict-tag
                  :options="dict.type.algorithm_level"
                  :value="item.alarmLevel"
                />
                <p>{{ item.algorithmName }}</p>
                <p>{{ item.cameraName }}</p>
                <p>{{ item.alarmTime }}</p>
              </el-col>
              <el-col :span="12">
                <image-preview
                  :src="item.alarmImageUrl"
                  :width="170"
                  :height="145"
                />
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="dialogVisible" width="60%">
      <div slot="title" class="dialog-title">
        <span>
          <dict-tag
            style="display: inline-block; margin-right: 10px"
            :options="dict.type.algorithm_level"
            :value="currentAlarm.alarmLevel"
          />
          <span style="margin-right: 20px">{{
            (currentAlarm && currentAlarm.alarmMessage) || "报警详情"
          }}</span>

          <span style="margin-right: 20px">
            {{ currentAlarm && currentAlarm.cameraPosition }}</span
          >
          <span style="margin-right: 20px">{{
            currentAlarm && currentAlarm.alarmTime
          }}</span>
        </span>
        <el-button
          @click="playBack"
          :disabled="currentAlarm.videoStatus === 0"
          type="text"
          class="right-btn"
        >
          <i
            v-if="lookBackVideo === 0"
            :class="
              currentAlarm.videoStatus === 1
                ? 'el-icon-video-play'
                : 'el-icon-loading'
            "
          ></i>
          {{
            lookBackVideo === 1
              ? "查看图片"
              : currentAlarm.videoStatus === 1
              ? "查看回放"
              : "视频加载中"
          }}
        </el-button>
      </div>
      <div v-if="currentAlarm">
        <img
          v-if="lookBackVideo === 0"
          :src="currentAlarm.alarmImageUrl"
          style="width: 100%; height: 400px"
        />
        <video
          v-if="lookBackVideo === 1"
          :src="currentAlarm.videoBackUrl"
          style="width: 100%; height: 400px"
          controls
          autoplay
        ></video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PieChart from "./dashboard/PieChart.vue";
import LineChart from "./dashboard/LineChart.vue";
import {
  getCameraOnlineData,
  getVideoAnalysisOnlineData,
  getStatisticsData,
  getVideoPlayUrlWithAlgorithm,
} from "@/api/business/home.js";
import { getAlarmLogList } from "@/api/business/alarmlog.js";
// 播放FLV视频流
import flvjs from "flv.js";

export default {
  dicts: ["algorithm_level"],
  name: "Index",
  components: { PieChart, LineChart },
  data() {
    return {
      selectVidoe: [], // 选择视频
      videoList: [],
      webRtcServer: null, //webRtcServer上下文
      videoShow: false, //视频是否显示
      isDataLoaded: false, // 新增加载状态
      CameraOnlineData: {
        on: 0,
        off: 0,
      },
      VideoAnalysisOnlineData: [],
      StatisticsData: {},
      pickerDate: [],
      alarmList: [],
      // 新增弹窗相关数据
      dialogVisible: false,
      currentAlarm: {},
      lookBackVideo: 0, // 0-图片 1-视频
      iframeSrc: "", // 根据实际路径修改
      width: 0,
      height: 0,
      resizeObserver: null,
      iframeUrl: process.env.VUE_APP_SRS_URL,
      srsUrl: process.env.VUE_APP_SRS_URL,
      player: null,
      // 加载完成状态
      isLoaded: false,
    };
  },
  created() {
    // 设置最近7天为默认值
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 14);

    // 添加日期格式化
    const formatDate = (date) => {
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    };

    this.pickerDate = [formatDate(start), formatDate(end)];
    this.init();
    this.getAlarmLog();
  },
  mounted() {},
  methods: {
    async init() {
      // 使用Promise.all等待所有请求完成
      await Promise.all([
        getVideoPlayUrlWithAlgorithm().then((res) => {
          if (res.code !== 200) return;

          // 在数据转换时保留原始字段
          this.videoList = res.rows.map((camera) => ({
            value: camera.cameraId,
            label: camera.cameraName, // 这里保持摄像头名称
            children: [
              // 原有算法列表
              ...camera.algorithmVo.map((algorithm) => ({
                value: algorithm.algorithmId,
                label: algorithm.algorithmName,
              })),
            ],
          }));
          // 设置默认选中第一个摄像头的第一个算法
          if (
            this.videoList.length > 0 &&
            this.videoList[0].children?.length > 0
          ) {
            this.selectVidoe = [
              this.videoList[0].value,
              this.videoList[0].children[0].value,
            ];
            this.cameraName = this.videoList[0].label; // 摄像头名称
            this.algorithmName = this.videoList[0].children[0].label; // 算法名称
            var url = `${this.srsUrl}/view/${this.videoList[0].value}_${this.videoList[0].children[0].value}.flv`;
            this.videoPlayer(url);
          }
          this.videoShow = true;
        }),

        getCameraOnlineData().then((res) => {
          if (res.code !== 200) return;
          this.CameraOnlineData = { off: res.data.off, on: res.data.on };
        }),

        getVideoAnalysisOnlineData().then((res) => {
          if (res.code !== 200) return;
          this.VideoAnalysisOnlineData = [
            { value: res.data.off, name: "未启动" },
            { value: res.data.on, name: "已启动" },
          ];
        }),

        getStatisticsData({
          startTime: this.pickerDate[0],
          endTime: this.pickerDate[this.pickerDate.length - 1],
        }).then((res) => {
          if (res.code !== 200) return;
          this.StatisticsData = res.data;
          this.pickerDate = [
            res.data.xdata[0],
            res.data.xdata[res.data.xdata.length - 1],
          ];
        }),
      ]);

      // 所有请求完成后设置加载完成状态
      this.$nextTick(() => {
        this.isDataLoaded = true;
      });
    },
    getData() {
      getStatisticsData({
        startTime: this.pickerDate[0],
        endTime: this.pickerDate[this.pickerDate.length - 1],
      }).then((res) => {
        if (res.code !== 200) return;
        this.StatisticsData = res.data;
      });
    },
    getAlarmLog() {
      getAlarmLogList({}).then((res) => {
        if (res.code !== 200) return;
        this.alarmList = res.rows;
      });
    },
    lookAlarm(item) {
      this.currentAlarm = item;
      this.lookBackVideo = 0; // 默认显示图片
      this.dialogVisible = true;
    },

    playBack() {
      this.lookBackVideo = this.lookBackVideo === 0 ? 1 : 0;
    },
    handleCascaderChange(value) {
      console.log(value);
      if (value.length === 2) {
        this.cameraName = this.videoList.find(
          (item) => item.value === value[0]
        ).label; // 摄像头名称
        this.videoList.forEach((alg) => {
          if (alg.value === value[0]) {
            alg.children.forEach((item) => {
              if (item.value === value[1]) {
                this.algorithmName = item.label; // 摄像头名称
              }
            });
          }
        });
        this.iframeSrc = `${this.iframeUrl}/view/${value[0]}/${value[1]}`;
        var url = `${this.srsUrl}/live/${value[0]}_${value[1]}.flv`;
        this.videoPlayer(url);
      }
    },
    videoPlayer(url = "") {
      if (flvjs.isSupported()) {
        var videoElement = document.getElementById("videoPlayer");
        var flvPlayer = flvjs.createPlayer({
          type: "flv",
          url: url, //你的url地址
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
      }
    },
  },
  beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.app-container {
  padding-right: 0;
  .fs30 {
    font-size: 38px;
  }
  .ac {
    text-align: center;
  }
  .status-container {
    padding: 20px;
    background: #f8f9fa;
    border-radius: 5px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    &.h100 {
      height: 100vh;
    }
    .status-title {
      margin: 0 0 20px 0;
      font-size: 16px;
      color: #333;
      .title-icon {
        margin-right: 8px;
        font-size: 20px;
        color: #409eff;
      }
    }
    .both-end {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .card-box {
      border-radius: 5px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      width: 100%;
      padding: 15px;
      margin-top: 10px;
      cursor: pointer;
    }
    .status-group {
      display: flex;
      gap: 20px;
      .status-item {
        flex: 1;
        text-align: center;
        .count {
          font-size: 32px;
          font-weight: bold;
          display: block;
          margin-bottom: 8px;

          &.online {
            color: #67c23a;
          }
          &.offline {
            color: #f56c6c;
          }
        }
        .label {
          font-size: 14px;
          color: #666;
          .svg-icon {
            vertical-align: middle;
            margin-right: 5px;
            font-size: 18px;
          }
        }
      }
    }
    .video-box {
      height: 440px;
      width: 100%;
      position: relative;
      flex-shrink: 0; // 禁止弹性收缩
      overflow: hidden; // 添加溢出隐藏
      .video-container {
        width: 100%;
        height: 100%;
      }
      iframe {
        width: 100%;
        height: 100%;
      }
      .loading-overlay,
      .error-overlay {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        text-align: center;
        i {
          font-size: 40px;
        }
        &-text {
          font-size: 14px;
        }
      }
      .error-overlay {
        color: #f56c6c;
      }
    }
  }
  .dialog-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .right-btn {
      margin-right: 40px;
    }
  }
}
</style>
