<template>
  <div class="realMonitor">
    <div class="monitor-container">
      <!-- 左侧数据列表树 -->
      <div class="sideBar">
        <div class="searchBar">
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterText"
            prefix-icon="el-icon-search"
          >
          </el-input>
        </div>
        <div class="deviceNum">
          <el-statistic title="装置在线 / 总数">
            <template slot="formatter">
              （<span>{{ onlineNum ? onlineNum : 0 }}</span> /
              <span>{{ totalNum ? totalNum : 0 }}</span
              >）
            </template>
          </el-statistic>
        </div>
        <div class="radioFilter">
          <el-radio-group v-model="zzradio" @input="getRadio">
            <el-radio :label="-1">全部</el-radio>
            <el-radio :label="1">在线</el-radio>
            <el-radio :label="0">离线</el-radio>
          </el-radio-group>
          <el-button
            class="refresh"
            @click="getLineTreeStatus"
            type="text"
            icon="el-icon-refresh-right"
            >刷新</el-button
          >
        </div>
        <el-tree
          ref="tree"
          :data="lineTreeData"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :current-node-key="currentNodekey"
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span v-if="node.level === 1">
              <span
                v-if="data.type == 1"
                class="el-icon-folder"
                style="margin-right: 6px"
              ></span>
              <span
                v-else
                class="iconfont icon-dianli"
                style="margin-right: 6px"
              ></span>
              <span>{{ node.label }} </span>
            </span>
            <span v-else-if="node.level === 2">
              <span
                class="iconfont icon-dianlihangye"
                style="margin-right: 6px"
              >
              </span>
              <span>{{ node.label }} </span>
            </span>
            <span v-else>
              <span
                class="iconfont icon-shexiangtoulixian"
                v-if="data.onlinestatus == 0"
                :class="data.onlinestatus == 0 ? 'disconnect' : ''"
                style="margin-right: 6px"
              ></span>
              <span
                class="iconfont icon-shexiangtou-lixian"
                v-else
                :class="data.onlinestatus == 0 ? 'disconnect' : ''"
                style="margin-right: 6px"
              ></span>
              <span
                :id="data.id"
                :class="data.onlinestatus == 0 ? 'disconnect' : ''"
                >{{ node.label }}</span
              >
            </span>
            <!-- <span :class="data.onlinestatus == 0 ? 'disconnect' : ''"
              >{{ node.level }}---{{ node.label }}</span
            > -->
          </span>
        </el-tree>
      </div>
      <div class="resize" title="收缩侧边栏"></div>

      <div class="picSetBox previewBox" v-show="LineFlag">
        <!-- 预览图页面 -->
        <previewContain
          ref="previewRef"
          :previewData="previewData"
        ></previewContain>
      </div>
      <!-- 带参数的中心内容右侧参数区 -->
      <div class="picSetBox" v-show="towerFlag">
        <div class="swiperBox" v-loading="swiperLoading">
          <div class="title">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item> {{ towertitle }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <!-- <carouselChart
            ref="carouselpic"
            :key="carouselKey"
            :terminalPhoto="terminalPhoto"
          ></carouselChart> -->
          <carouselChart
            ref="carouselpic"
            :key="carouselKey"
            :terminalPhoto="terminalPhoto"
            :photoNum="photoNum"
          ></carouselChart>
        </div>
        <div class="parameterArea">
          <div class="zzbox">
            <b>{{ zzCmdid }}</b>
            <!-- <b>{{ collectFlag }}</b> -->
            <el-button
              type="text"
              :icon="collectFlag ? 'el-icon-star-on' : 'el-icon-star-off'"
              @click="addCollectClick"
              >{{ collectFlag ? "取消收藏" : "添加收藏" }}</el-button
            >
          </div>
          <div class="paramsDate">
            <h3>日历快速查询</h3>
            <el-date-picker
              v-model="dateValue"
              type="date"
              placeholder="选择日期"
              format="yyyy 年 MM 月 dd 日"
              :picker-options="pickerOptions"
              @change="changedate"
              :clearable="false"
            >
            </el-date-picker>
          </div>
          <div class="monitorItemBox">
            <h3>选择通道监拍点</h3>
            <el-select
              v-model="selectChannelValue"
              placeholder="请选择通道"
              @change="changeChannelId"
              ref="multiSelect"
            >
              <el-option
                v-for="item in channelListOption"
                :key="item.value"
                :label="
                  item.alias !== null && item.alias !== ''
                    ? item.alias
                    : item.label
                "
                :value="item.value"
              >
                {{
                  item.alias !== null && item.alias !== ""
                    ? item.alias
                    : item.label
                }}
              </el-option>
            </el-select>
          </div>
          <div class="setTimebtn">
            <h3>操作项</h3>
            <div class="buttonGroup">
              <el-dropdown trigger="click" @command="handleCommandpic">
                <el-button type="primary" :loading="btnpicloading">
                  主动拍照<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="picdropStyle">
                  <el-dropdown-item
                    :command="item.value"
                    v-for="(item, index) in channelOption"
                    :key="index"
                    >{{
                      item.alias !== null && item.alias !== ""
                        ? item.alias
                        : item.label
                    }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
              <el-dropdown trigger="click" @command="handleCommandvideo">
                <el-button type="primary" :loading="btnvideoloading">
                  主动录像<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="videodropStyle">
                  <el-dropdown-item
                    :command="item.value"
                    v-for="(item, index) in channelOption"
                    :key="index"
                    >{{
                      item.alias !== null && item.alias !== ""
                        ? item.alias
                        : item.label
                    }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>

              <el-button type="primary" @click="handleShowInfo">
                装置信息</el-button
              >
              <el-button type="primary" @click.native.stop="handleSetSchedule()"
                >拍照时间表</el-button
              >

              <el-dropdown
                class="dropgps"
                trigger="click"
                @command="handleCommandWarn"
              >
                <el-button type="primary">
                  声光报警<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="gpsdropStyle">
                  <el-dropdown-item command="open">开启</el-dropdown-item>
                  <el-dropdown-item command="close">关闭</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 线缆显示 -->
              <el-dropdown
                class="dropgps"
                trigger="click"
                @command="handleCommandLine"
              >
                <el-button type="primary">
                  线缆显示<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="gpsdropStyle">
                  <el-dropdown-item command="open">开启</el-dropdown-item>
                  <el-dropdown-item command="close">关闭</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 获取gps位置 -->
              <el-button type="primary" @click.native.stop="handleShowGPS()"
                >获取GPS位置</el-button
              >
              <!-- gps开关 -->
              <el-dropdown
                class="dropgps"
                trigger="click"
                @command="handleCommandGps"
              >
                <el-button type="primary">
                  GPS开关<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="gpsdropStyle">
                  <el-dropdown-item command="open">开启GPS</el-dropdown-item>
                  <el-dropdown-item command="close">关闭GPS</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button type="primary" @click="handlehistoryPic">
                历史图片</el-button
              >
            </div>
          </div>
          <div class="setfocalLength" v-if="zzprotocol == '65286'">
            <h3>焦距调节</h3>
            <div class="selectChannel">
              <span class="labelname">选择通道</span>
              <el-select
                v-model="channelarrValue"
                placeholder="请选择通道"
                @change="changeChannelarrValue"
                ref="multiSelect"
              >
                <el-option
                  v-for="item in channelOption"
                  :key="item.value"
                  :label="
                    item.alias !== null && item.alias !== ''
                      ? item.alias
                      : item.label
                  "
                  :value="item.value"
                >
                  {{
                    item.alias !== null && item.alias !== ""
                      ? item.alias
                      : item.label
                  }}
                </el-option>
              </el-select>
            </div>
            <div class="buttonGroup">
              <el-button
                type="primary"
                icon="el-icon-zoom-in"
                @click="amplify()"
                >放大</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-zoom-out"
                @click="reduce()"
                >缩小</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <setschedule ref="setschedule_ref"></setschedule>
    <info-dialog ref="infodialog_ref"></info-dialog>
    <gps-position ref="gpsdialog_ref"></gps-position>
    <morePicPreveiw ref="morePicPreveiw_ref"></morePicPreveiw>
    <!-- 收藏弹窗 -->
    <el-dialog title="选择收藏夹" :visible.sync="favorListDialog" width="368px">
      <el-form :model="favorform" @change="changeFavAl">
        <el-form-item label="收藏夹列表">
          <el-select
            style="width: 244px"
            v-model="favorform.favorVal"
            placeholder="请选择收藏夹"
          >
            <el-option
              v-for="item in favorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="favorListDialog = false">取 消</el-button>
        <el-button type="primary" @click="confimFavorBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getdyTreeListJoggle,
  getChannelByTermidJoggle,
  getTerminalPhotoListJoggle,
  getTermStatus,
  alarmMarkJoggle,
  takePicJoggle,
  getTakePicPhotoStatusJoggle,
  getTakePicStatusJoggle,
  setTermGPSJoggle,
  updateTermCamera,
  addFavorList,
  listFavorApi,
} from "@/utils/api/index";
import previewContain from "./previewContain.vue";
import carouselChart from "../components/carouselChart.vue";
import setschedule from "./components/setschedule.vue";
import infoDialog from "./components/infoDialog.vue";
import gpsPosition from "./components/gpsPosition.vue";
import morePicPreveiw from "./components/morePicPreveiw.vue";

import { number } from "echarts";
export default {
  components: {
    previewContain,
    carouselChart,
    setschedule,
    infoDialog,
    gpsPosition,
    morePicPreveiw,
  },
  data() {
    return {
      btnpicloading: false,
      btnvideoloading: false,
      onlinestatus: "", //设备状态啊
      onlineNum: "", //在线数
      totalNum: "", //装置总数
      selectData: "", //点击选中的数据
      type: "", //选中的类型
      lineTreeData: [],
      filterText: "",
      searchName: "",
      photoNum: 5,
      defaultProps: {
        //指定参数格式回显数据
        children: "list",
        label: "name",
      },
      currentNodekey: "", //默认选中的节点树,
      previewData: [], //预览图数据
      page: 1, // 当前页数
      treetimer: null, //轮询状态timer
      LineFlag: true,
      towerFlag: false, //判断是否是图片list
      towertitle: "", //装置杆塔信息
      terminalPhoto: [], //获取装置当前图片数据
      nopicPath: require("@/assets/img/nopic.jpg"),
      swiperLoading: false,
      zzCmdid: "",
      zztermId: "",
      zzprotocol: "", //装置规约
      dateValue: "", //选择日期
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() > Date.now(); // 禁用大于今天的日期
        },
      },
      channelListOption: [], //通道内容
      channelOption: [], //主动拍照通道
      channelarr: [],
      channelarrValue: null,
      selectChannelValue: 1, //选中的通道
      channelId: "", //选中的通道id
      btnpicloading: false, //主动拍照按钮loading
      requestId: "", //请求拍照返回的requestid
      picTime: "", //请求拍照返回的时间
      timer: null, //获取最新图片
      i: 0, //获取最新图片
      CurrentData: "", //历史图片当前选中数据

      statusNum: 0, //查询下发状态
      statusTimer: null, //查询下发状态
      selectDyId: "", //获取当前选中的电压线路等信息
      selectLineId: "",
      selectTowerId: "",
      currentData: "", //保存选中的数据
      zzradio: -1,
      collectFlag: false, //收藏

      favorListDialog: false, //收藏弹窗
      favorform: {
        favorVal: "",
      }, //收藏夹参数
      favorOptions: [], //收藏夹列表
      carouselKey: 0, // 初始key
      picnotiy: [],
      pollingTimer: null, // 轮询定时器（使用setTimeout，因此命名为pollingTimer更合适）
      polling: false, // 控制是否正在轮询的标志位
      isPollingStopped: false, // 新增：标记轮询是否已停止
      maxPollingAttempts: 5, // 新增：最大轮询次数
    };
  },
  watch: {
    filterText(val) {
      console.log(val);
      this.$refs.tree.filter(val);
      console.log(this.$refs.tree);
    },
    zztermId: {
      handler(newVal, oldVal) {
        console.log("我改变了");
        clearInterval(this.statusTimer);
        this.statusTimer = null;
        this.statusNum = 0;
        this.btnpicloading = false;
        this.btnvideoloading = false;
      },
      deep: true,
      immediate: true,
    },
    picnotiy: {
      handler(newVal, oldVal) {
        console.log(newVal);
        console.log(oldVal);
        console.log("我是通知信息，我改变了");
      },
      deep: true,
      immediate: true,
    },
  },

  computed: {},
  mounted() {
    this.dragControllerDiv();
    this.getDateTime();

    window.addEventListener("onmessageWS", this.getSocketData);
  },
  created() {
    //获取日期
    this.zzradio =
      JSON.parse(localStorage.getItem("radio")) !== null
        ? JSON.parse(localStorage.getItem("radio"))
        : -1;
    this.getRadio();
    this.getLineTreeList();
    this.treetimer = window.setInterval(() => {
      setTimeout(this.getLineTreeStatus(), 0);
    }, 1800000);
  },
  methods: {
    //获取当前选中的radio
    getRadio() {
      console.log(this.zzradio);
      localStorage.setItem("radio", JSON.stringify(this.zzradio));
      this.getLineTreeStatus();
    },
    //获取当前时间
    getDateTime() {
      console.log(new Date());
      this.dateValue = new Date().getTime();
      console.log(this.dateValue);
    },
    // //选择时间
    // changedate() {
    //   console.log(this.dateValue);
    // },
    //点击当前选中的treenode
    handleNodeClick(data, node) {
      this.clearfun();
      console.log(data, node);
      if (node) {
        if (
          node.level == 1 &&
          data.dyValue == null &&
          data.hasOwnProperty("list")
        ) {
          this.$refs.tree.setCurrentKey(this.selectData.id);
          return;
        }
        if (
          node.level == 2 &&
          data.bsManufacturer == null &&
          data.hasOwnProperty("list")
        ) {
          this.$refs.tree.setCurrentKey(this.selectData.id);
          return;
        }
        if (node.level == 1 && data.type == 1 && data.hasOwnProperty("list")) {
          this.$refs.tree.setCurrentKey(this.selectData.id);
          return;
        }
      }

      this.selectData = data;
      this.zztermId = data.id;
      this.zzprotocol = data.protocol;
      this.CurrentData = data;
      if (data.isfavor == 0 || data.isfavor == null) {
        this.collectFlag = false;
      } else {
        this.collectFlag = true;
      }
      //this.previewData = data;
      if (data.dyValue) {
        this.LineFlag = true;
        this.towerFlag = false;
        console.log("电压");
        this.type = 1;
        //this.getPicList(data.id, this.type);

        this.$refs.previewRef.getPicList(data.id, this.type, this.page);
      } else if (data.bsManufacturer && data.bsManufacturer !== "收藏夹") {
        this.LineFlag = true;
        this.towerFlag = false;
        console.log("线路");
        this.type = 2;
        this.$refs.previewRef.getPicList(data.id, this.type, this.page);
        //this.getPicList(data.id, this.type);
      } else {
        console.log("杆塔");
        this.LineFlag = false;
        this.towerFlag = true;
        this.towertitle = data.name;
        this.zzCmdid = data.cmdid;
        this.getChannelList(data.id);

        // this.getTerminalPhotoList(id, date, data.id);
      }
      localStorage.setItem("currentData", JSON.stringify(this.selectData));
    },
    //轮询获取装置状态
    getLineTreeStatus() {
      console.log("11111111");
      console.log(this.filterText);
      if (this.filterText !== "") {
        this.$refs.tree.filter(this.filterText);
      } else {
        getdyTreeListJoggle({ type: this.zzradio })
          .then((res) => {
            console.log(res);
            this.lineTreeData = res.data.list;

            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.selectData.id); //一定要加这个选中了否则样式没有出来
            });
          })
          .catch((err) => {
            console.log(err); //代码错误、请求失败捕获
          });
      }
    },
    //树状图搜索
    filterNode(value, data, node) {
      //console.log(value, data, node);
      this.filterText = value;
      console.log(this.filterText);
      // 如果什么都没填全部匹配全部返回
      if (!value) return true;
      this.searchName = data.name + data.cmdid;
      //console.log(this.searchName);
      // 如果传入的value和data中的label相同，匹配成功
      if (this.searchName.indexOf(value) !== -1) {
        return true;
      }
    },
    //获取左侧树结构
    getLineTreeList() {
      console.log(this.zzradio);
      getdyTreeListJoggle({ type: this.zzradio })
        .then((res) => {
          console.log(res);
          this.lineTreeData = res.data.list;
          console.log(this.lineTreeData);

          this.onlineNum = res.data.onlineNum;
          this.totalNum = res.data.totalNum;
          this.currentData = JSON.parse(localStorage.getItem("currentData"));
          console.log(this.currentData);
          // if (this.lineTreeData[0].list[0].list.length > 0) {
          console.log("diyici");
          if (
            this.currentData !== null &&
            Object.keys(this.currentData).length !== 0
          ) {
            console.log("aaa");
            this.currentNodekey = this.currentData.id;
            this.handleNodeClick(this.currentData);
          } else {
            console.log("diyici");
            this.selectData = this.lineTreeData[0]; //第一个选中的数据
            this.currentNodekey = this.lineTreeData[0].id; //第一个数据
            this.type = 1;
            this.newCurrentId = this.lineTreeData[0].id;
            this.previewData = this.lineTreeData[0]; //预览图数据
            this.channelId = this.currentNodekey;
            this.$refs.previewRef.getPicList(
              this.currentNodekey,
              this.type,
              this.page
            );
          }

          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
          });
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },

    //获取通道的接口
    getChannelList(id) {
      getChannelByTermidJoggle({ termid: id })
        .then((res) => {
          console.log(res);
          this.channelList = res.data.list;
          this.channelarr = res.data.list;
          if (this.channelList.length == 0) {
            console.log("没有通道");
            this.getTerminalPhotoList(-1, this.dateValue, this.zztermId); //获取图片列表是传当前设备的 id 和termid
          } else {
            console.log(this.channelList);
            this.channelOption = [];

            this.channelList.forEach((item) => {
              this.channelOption.push({
                label: item.channelname,
                value: item.channelid,
                termid: item.termId,
                alias: item.alias,
              });
            }); // 选择通道一通道二select框
            console.log(this.channelOption);
            this.channelListOption = [];
            this.channelListOption.push({
              label: "全部",
              value: -1,
              termid: "",
              alias: "",
            });
            this.channelList.forEach((item) => {
              this.channelListOption.push({
                label: item.channelname,
                value: item.channelid,
                termid: item.termId,
                alias: item.alias,
              });
            });
            this.selectChannelValue = this.channelListOption[1].value; //默认选中所有通道
            this.channelarrValue = this.channelOption[1].value;
            this.getTerminalPhotoList(
              this.selectChannelValue,
              this.dateValue,
              this.channelList[0].termId
            ); //获取图片列表是传当前设备的 id 和termid
            this.selectDyId = res.data.dyId;
            this.selectLineId = res.data.lineId;
            this.selectTowerId = res.data.towerId;
          }
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //切换通道
    changeChannelId(val) {
      console.log(val);
      this.getTerminalPhotoList(val, this.dateValue, this.zztermId);
    },
    //焦距切换通道
    changeChannelarrValue(val) {
      console.log(val);
    },
    //选择时间
    changedate() {
      console.log(this.dateValue.getTime());
      console.log(this.zztermId);
      this.getTerminalPhotoList(
        this.selectChannelValue,
        this.dateValue,
        this.zztermId
      );
    },
    //获取图片
    // getTerminalPhotoList(id, date, termId) {
    //   this.swiperLoading = true;
    //   this.clearfun();
    //   //this.terminalPhoto = [];
    //   console.log("我是原来的图片", this.terminalPhoto);
    //   console.log(id, date, termId);

    //   getTerminalPhotoListJoggle({
    //     channelid: id,
    //     time: date,
    //     terminalid: termId,
    //   })
    //     .then((res) => {
    //       console.log(res);

    //       if (res.data.list.length == 0) {
    //         this.terminalPhoto = [
    //           {
    //             path: this.nopicPath,
    //             termId: termId,
    //             mediatype: 0,
    //           },
    //         ];
    //       } else {
    //         this.terminalPhoto = res.data.list;
    //       }
    //       this.carouselKey++; // 更新key以强制重新渲染
    //       this.$nextTick(() => {
    //         this.$refs.carouselpic.handleBigpic(this.terminalPhoto[0], 0);
    //       });
    //       this.swiperLoading = false;
    //     })
    //     .catch((err) => {
    //       console.log(err); //代码错误、请求失败捕获
    //     });
    // },

    //获取图片
    getTerminalPhotoList(channelId, date, termId) {
      console.log(channelId, date, termId);
      this.swiperLoading = true;
      console.log("zhanshi asdadadadadadsddadadadadad", this.terminalPhoto);
      //this.terminalPhoto = [];
      getTerminalPhotoListJoggle({
        channelid: channelId,
        time: date,
        terminalid: termId,
      })
        .then((res) => {
          console.log(res);
          if (res.data.list.length == 0) {
            this.terminalPhoto = [
              {
                path: this.nopicPath,
                termId: termId,
                mediaType: 0,
              },
            ];
          } else {
            this.terminalPhoto = res.data.list;
          }
          this.carouselKey++; // 更新key以强制重新渲染

          this.$nextTick(() => {
            this.$refs.carouselpic.changeBigPic(this.terminalPhoto[0], 0);
          });

          this.swiperLoading = false;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    addCollectClick() {
      if (!this.collectFlag) {
        listFavorApi()
          .then((res) => {
            if (res.code == 200) {
              this.favorOptions = res.data;
              this.favorform.favorVal = res.data[0].id;
              if (this.favorOptions.length !== 0) {
                this.favorListDialog = true;
              } else {
                this.$message({
                  duration: 1500,
                  showClose: true,
                  message: "请到收藏夹管理页面添加收藏夹",
                  type: "warning",
                });
              }
            }
          })
          .catch((err) => {});
      } else {
        this.$confirm("此操作将取消收藏, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.collectFlag = false;
          addFavorList({
            termid: this.zztermId,
            id: 0,
          }).then((res) => {
            this.getLineTreeStatus();
          });

          this.$message({
            type: "success",
            message: "取消收藏!",
          });
        });
      }
    },
    //切换收藏夹
    changeFavAl(val) {
      console.log(val);
    },
    //选中收藏夹
    confimFavorBtn() {
      this.collectFlag = true;
      console.log(this.favorform.favorVal);
      addFavorList({
        termid: this.zztermId,
        id: this.favorform.favorVal,
      }).then((res) => {
        if (res.code == 200) {
          this.favorListDialog = false;
          this.getLineTreeStatus();
          this.$message({
            type: "success",
            message: "添加成功!",
          });
        }
      });
    },
    //点击图片列表执行函数
    jumpTowerPic(data) {
      console.log("我是从子组件过来的数据");
      console.log(data);
      this.$refs.morePicPreveiw_ref.display(data);
      // this.LineFlag = false;
      // this.towerFlag = true;
      // this.zzCmdid = data.cmdid;
      // this.towertitle = data.towername;
      // this.zztermId = data.termid;
      // this.selectChannelValue = data.channnelname;
      // this.$refs.tree.setCurrentKey(this.zztermId); //一定要加这个选中了否则样式没有出来
      // this.selectedRegion(this.zztermId);
      // if (data.photoTime == "" || data.photoTime == null) {
      //   this.getDateTime();
      // } else {
      //   this.dateValue = data.photoTime;
      // }
      // console.log(this.selectChannelValue);
      // getChannelByTermidJoggle({ termid: this.zztermId })
      //   .then((res) => {
      //     console.log(res);
      //     this.channelList = res.data.list;
      //     console.log(this.channelList);
      //     this.channelOption = [];
      //     this.channelList.forEach((item) => {
      //       this.channelOption.push({
      //         label: item.channelname,
      //         value: item.channelid,
      //         termid: item.termId,
      //         alias: item.alias,
      //       });
      //     }); // 选择通道一通道二select框
      //     console.log(this.channelOption);
      //     this.channelListOption = [];
      //     this.channelListOption.push({
      //       label: "全部",
      //       value: -1,
      //       termid: "",
      //       alias: "",
      //     });
      //     this.channelList.forEach((item) => {
      //       this.channelListOption.push({
      //         label: item.channelname,
      //         value: item.channelid,
      //         termid: item.termId,
      //         alias: item.alias,
      //       });
      //     });
      //     this.selectChannelValue = data.channnelname;
      //     this.getTerminalPhotoList(
      //       data.channelid,
      //       this.dateValue,
      //       this.zztermId
      //     ); //获取图片列表是传当前设备的 id 和termid
      //   })
      //   .catch((err) => {
      //     console.log(err); //代码错误、请求失败捕获
      //   });
    },
    selectedRegion(id) {
      console.log("滚动到选中定位的位置");
      // 通过Id获取到对应的dom元素
      const node = document.getElementById(id);
      setTimeout(() => {
        if (node) {
          this.$nextTick(() => {
            // 通过scrollIntoView方法将对应的dom元素定位到可见区域 【block: 'center'】这个属性是在垂直方向居中显示
            console.log(node);
            node.scrollIntoView({ block: "center" });
          });
        }
      }, 100);
    },
    //主动拍照
    handleCommandpic(command) {
      console.log(command);
      // localStorage.setItem("picNotify", "");
      getTermStatus({ termId: this.zztermId }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          takePicJoggle({
            captureType: 0,
            channel: command,
            termId: this.zztermId,
            preset: 255,
          })
            .then((res) => {
              console.log(res);
              this.requestId = res.data.requestId; //获取requestid 判断装置是否下发
              this.picTime = res.data.taketime; //获取时间 判断获取最新图片
              console.log(this.requestId);
              console.log(this.picTime);
              this.btnpicloading = true;
              // this.getTakePicStatus(res.data);
              // this.cancleFn = true;

              this.isPollingStopped = false; // 重置轮询停止标记
              this.startPolling(res.data); // 开始轮询
              // this.statusTimer = window.setInterval(() => {
              //   this.getTakePicStatus(res.data);
              //   this.statusNum++;
              // }, 3000);
            })
            .catch((err) => {
              console.log(err); //代码错误、请求失败捕获
            });
        } else {
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
    },
    startPolling(data) {
      if (!this.polling) {
        this.polling = true;
        this.statusNum = 0;
        this.poll(data); // 调用新的poll函数开始第一次轮询
      }
    },
    poll(data) {
      if (this.isPollingStopped) {
        console.log("轮询已停止，不再调用 getTakePicStatus");
        return;
      }
      this.getTakePicStatus(data)
        .then((shouldContinue) => {
          if (shouldContinue) {
            this.statusNum++;
            if (this.statusNum < this.maxPollingAttempts) {
              // 如果需要继续轮询，则设置下一个定时器
              this.pollingTimer = setTimeout(() => {
                this.poll(data); // 递归调用poll进行下一次轮询
              }, 3000);
            } else {
              // 达到最大轮询次数，停止轮询
              this.stopPolling();
              this.$message({
                duration: 1500,
                showClose: true,
                message: "下发指令超时，请重试！",
                type: "warning",
              });
            }
          } else {
            // 根据getTakePicStatus的返回结果，可能在这里就需要停止轮询
            this.stopPolling();
          }
        })
        .catch((err) => {
          console.error("轮询出错:", err);
          this.stopPolling();
        });
    },
    stopPolling() {
      console.log(this.pollingTimer, "清除轮询不");
      if (this.pollingTimer !== null) {
        clearTimeout(this.pollingTimer);
        this.pollingTimer = null;
      }
      this.statusNum = 0;
      this.polling = false;
      this.btnpicloading = false;
      this.btnvideoloading = false;
      this.isPollingStopped = true; // 标记轮询已停止
    },
    //主动拍视频
    handleCommandvideo(command) {
      console.log(command);
      this.clearfun();
      getTermStatus({ termId: this.zztermId }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          takePicJoggle({
            captureType: 1,
            channel: command,
            termId: this.zztermId,
            preset: 255,
          })
            .then((res) => {
              console.log(res);
              this.requestId = res.data.requestId; //获取requestid 判断装置是否下发
              this.picTime = res.data.taketime; //获取时间 判断获取最新视频
              console.log(this.requestId);
              this.btnvideoloading = true;
              this.getTakePicStatus(res.data);
              this.statusTimer = window.setInterval(() => {
                this.getTakePicStatus(res.data);
                this.statusNum++;
              }, 2000);
            })
            .catch((err) => {
              console.log(err); //代码错误、请求失败捕获
            });
        } else {
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
    },

    //获取装置是否下发状态
    getTakePicStatus(data) {
      console.log(data);
      return getTakePicStatusJoggle({
        requestid: data.requestId,
        termId: this.zztermId,
        photoTime: new Date(data.taketime).getTime(),
      })
        .then((res) => {
          console.log(res);
          // res.data  0 状态未知  1 成功 2失败
          if (res.data.cmaStatus === 1 || res.data.picStatus === true) {
            this.stopPolling();
            this.$message({
              duration: 1500,
              showClose: true,
              message: "下发指令成功！",
              type: "success",
            });
            this.timer = window.setInterval(() => {
              this.newPicApi();
              this.i++;
            }, 8000);
            return false; // 停止轮询
          } else if (res.data.cmaStatus === 2) {
            this.stopPolling();
            this.$message({
              duration: 1500,
              showClose: true,
              message: "下发指令失败！",
              type: "error",
            });
            return false; // 停止轮询
          } else {
            return true; // 继续轮询
          }
        })
        .catch((err) => {
          console.error("获取拍照状态失败:", err);
          this.stopPolling();
          return false; // 停止轮询
        });
    },

    getSocketData(res) {
      console.log(res);
      console.log(JSON.parse(res.detail.data));
      let a = JSON.parse(res.detail.data);
      console.log(a.type);
      console.log(a.action);
      if (a.action == "photo") {
        this.$notify({
          title: "通知",
          message: a.content,
          position: "bottom-right",
          type: "warning",
          duration: 60000,
        });
        //this.newPicApi();
      }
    },
    //获取最新图片
    newPicApi() {
      getTakePicPhotoStatusJoggle({
        photoTime: new Date(this.picTime).getTime(),
        termId: this.zztermId,
        requestid: this.requestId,
      }).then((res) => {
        console.log(res.data);
        // // console.log(this.i);
        if (res.data == true && this.i < 10) {
          console.log(res.data);

          clearInterval(this.timer);
          this.i = 0;
          this.timer = null;
          this.btnpicloading = false;
          this.btnvideoloading = false;
          this.getTerminalPhotoList(
            this.selectChannelValue,
            this.dateValue,
            this.zztermId
          ); //获取图片列表是传当前设备的 id 和termid
          this.$message({
            duration: 1500,
            showClose: true,
            message: "已返回最新图片！",
            type: "success",
          });
          console.log("返回最新图片");
        } else if (res.data == false && this.i > 10) {
          clearInterval(this.timer);
          this.timer = null;
          this.i = 0;
        }
      });
    },
    //声光报警开启关闭
    handleCommandWarn(command) {
      switch (command) {
        case "open": //开启
          this.handleWarn(1);
          break;
        case "close": //关闭
          this.handleWarn(0);
          break;
      }
    },
    //声光报警
    handleWarn(val) {
      console.log("声光报警");
      console.log(this.zztermId);
      this.clearfun();
      getTermStatus({ termId: this.zztermId }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          alarmMarkJoggle({
            cmdId: this.zzCmdid,
            ctrl: val,
            termId: this.zztermId,
          })
            .then((res) => {
              console.log(res);
              if (res.code == 200) {
                if (val == 1) {
                  this.$message({
                    duration: 1500,
                    showClose: true,
                    message: "声光报警开启成功",
                    type: "success",
                  });
                } else {
                  this.$message({
                    duration: 1500,
                    showClose: true,
                    message: "声光报警关闭成功",
                    type: "success",
                  });
                }
              }
            })
            .catch((err) => {
              this.$message({
                duration: 1500,
                showClose: true,
                message: "声光报警操作失败",
                type: "error",
              });
            });
        } else {
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
    },
    //设置时间表
    handleSetSchedule() {
      this.clearfun();
      this.$refs.setschedule_ref.display();
      this.$refs.setschedule_ref.getSingleAccess(
        this.zztermId,
        this.zzCmdid,
        this.zzprotocol
      );
      this.$refs.setschedule_ref.deviceList();
    },
    //线缆显示
    handleCommandLine(command) {
      this.clearfun();
      switch (command) {
        case "open": //开启
          this.$refs.carouselpic.openline();
          break;
        case "close": //关闭
          this.$refs.carouselpic.handelClear();
          break;
      }
    },
    //装置信息handleShowInfo
    handleShowInfo() {
      this.clearfun();
      getTermStatus({ termId: this.zztermId }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          this.$refs.infodialog_ref.display(this.zztermId, this.zzCmdid);
          this.$refs.infodialog_ref.getinfo();
          //this.$refs.infodialog_ref.getListData(this.channelId, this.cmdid);
        } else {
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
    },
    //获取GPS位置
    handleShowGPS() {
      this.clearfun();
      this.$refs.gpsdialog_ref.display(this.zzCmdid, this.zztermId);
      this.$refs.gpsdialog_ref.getgpssql();
    },
    //切换gps开启关闭
    handleCommandGps(command) {
      switch (command) {
        case "open": //开启
          this.changeGPS(1, this.zzCmdid);
          break;
        case "close": //关闭
          this.changeGPS(0, this.zzCmdid);
          break;
      }
    },
    changeGPS(val, cmdid) {
      console.log(val, cmdid);
      this.clearfun();
      setTermGPSJoggle({ gpsstatus: val, cmdId: cmdid })
        .then((res) => {
          console.log(res);
          if (val == 0) {
            this.$message({
              duration: 1500,
              message: "GPS已关闭",
              type: "warning",
              showClose: true,
            });
          } else {
            this.$message({
              duration: 1500,
              message: "成功开启GPS",
              type: "success",
              showClose: true,
            });
          }
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //历史图片跳转
    handlehistoryPic() {
      //console.log(this.CurrentData);

      console.log(this.selectDyId, this.selectLineId, this.selectTowerId);
      console.log(this.zzCmdid, this.selectChannelValue);

      if (typeof this.dateValue == "number") {
        console.log(this.dateValue);
        console.log(new Date(new Date().toLocaleDateString()).getTime());
        // var newDateValue = this.dateValue.toString();
        // this.dateValue = newDateValue.slice(0, -3) + "000";
        this.dateValue = new Date(new Date().toLocaleDateString()).getTime();
        console.log(1689782400000);
      } else {
        this.dateValue = this.dateValue.getTime();
      }

      this.$router.push({
        path: "/realTimeSearch",
        query: {
          dyId: this.selectDyId,
          lineId: this.selectLineId,
          towerId: this.selectTowerId,
          termId: this.zztermId,
          cmdId: this.zzCmdid,
          channelId: this.selectChannelValue,
          date: this.dateValue,
        },
      });
      // sessionStorage.setItem("keyPath", " realTimeSearch");
      this.clearfun();
    },
    //拖拽
    dragControllerDiv() {
      var resize = document.getElementsByClassName("resize");
      var left = document.getElementsByClassName("sideBar");
      var mid = document.getElementsByClassName("picSetBox");
      var box = document.getElementsByClassName("monitor-container");
      for (let i = 0; i < resize.length; i++) {
        // 鼠标按下事件
        resize[i].onmousedown = function (e) {
          //颜色改变提醒
          resize[i].style.background = "#128071";
          var startX = e.clientX;
          resize[i].left = resize[i].offsetLeft;
          // 鼠标拖动事件
          document.onmousemove = function (e) {
            var endX = e.clientX;
            var moveLen = resize[i].left + (endX - startX); // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
            var maxT = box[i].clientWidth - resize[i].offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

            if (moveLen < 290) moveLen = 290; // 左边区域的最小宽度为32px
            if (moveLen > maxT - 600) moveLen = maxT - 600; //右边区域最小宽度为150px

            resize[i].style.left = moveLen; // 设置左侧区域的宽度

            for (let j = 0; j < left.length; j++) {
              left[j].style.width = moveLen + "px";
              mid[j].style.width = box[i].clientWidth - moveLen - 3 + "px";
            }
          };
          // 鼠标松开事件
          document.onmouseup = function (evt) {
            //颜色恢复
            resize[i].style.background = "#dcdfe6";
            document.onmousemove = null;
            document.onmouseup = null;
            resize[i].releaseCapture && resize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          };
          resize[i].setCapture && resize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false;
        };
      }
    },
    clearfun() {
      console.log("清除轮询");
      this.stopPolling();
      if (this.pollingTimer !== null) {
        clearTimeout(this.pollingTimer);
        this.pollingTimer = null;
      }
      this.cancleFn = false;
      this.statusNum = 0;
      this.i = 0;
      //销毁主动拍照
      clearInterval(this.statusTimer);
      this.statusTimer = null;
      if (this.timer) {
        console.log(this.timer);
        clearInterval(this.timer);
        this.timer = null;
      } //利用vue的生命周期函数
    },
    //焦距放大缩小
    amplify() {
      getTermStatus({ termId: this.zztermId }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          updateTermCamera({
            termId: this.zztermId,
            channelId: this.channelarrValue,
            type: 6,
          })
            .then((res) => {})
            .catch();
          //this.$refs.infodialog_ref.getListData(this.channelId, this.cmdid);
        } else {
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
      console.log(this.channelarrValue, this.zztermId);
    },
    //焦距缩小
    reduce() {
      getTermStatus({ termId: this.zztermId }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          updateTermCamera({
            termId: this.zztermId,
            channelId: this.channelarrValue,
            type: 7,
          })
            .then((res) => {})
            .catch();
          //this.$refs.infodialog_ref.getListData(this.channelId, this.cmdid);
        } else {
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
    },
  },

  destroyed() {
    if (this.pollingTimer !== null) {
      clearTimeout(this.pollingTimer);
      this.pollingTimer = null;
    }
    this.cancleFn = false;
    //销毁左侧树状图
    clearInterval(this.treetimer);
    this.treetimer = null;
    this.statusNum = 6;
    //销毁主动拍照
    clearInterval(this.statusTimer);
    this.statusTimer = null;
    if (this.timer) {
      console.log(this.timer);
      clearInterval(this.timer);
      this.timer = null;
    } //利用vue的生命周期函数
  },
};
</script>

<style lang="less">
.realMonitor {
  width: calc(100% - 0px);
  height: calc(100% - 12px);
  padding: 12px 0px 0px 0px;
  background: #ffffff;
  .monitor-container {
    display: flex;
    height: 100%;
    box-sizing: border-box;
    background: @color-white;
    border: 1px solid #dddddd;
    border-radius: 4px;
    .sideBar {
      width: 300px;
      //border-right: 1px solid @border-color-base;
      display: flex;
      flex-direction: column;
      padding: 16px 0px;
      .searchBar {
        width: 94%;
        margin: 0 auto;
        margin-bottom: 8px;
      }
      .deviceNum {
        width: 94%;
        margin: 0 auto;
        margin-bottom: 8px;
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        .el-statistic {
          display: flex;
          justify-content: center;
          align-items: center;
          .head {
          }
          .con {
            color: #169e8c;
          }
        }
      }
      .radioFilter {
        width: 94%;
        margin: 0 auto;
        margin-bottom: 8px;
        font-size: 12px;
        display: flex;
        justify-content: space-around;
        .refresh {
        }
        .el-radio-group {
          display: flex;
          align-items: center;
          justify-content: center;
          .el-radio {
            margin-right: 16px;
          }
        }
      }
      .el-tree {
        overflow-y: auto;
        overflow-x: hidden;
        .el-tree-node__content {
          height: 32px;
          font-size: 12px;
        }
        .custom-tree-node {
          color: #333;
          overflow: hidden;
          span {
            display: flex;
            display: inline-table;
            overflow: hidden;
          }
        }
      }

      .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content {
        // 设置颜色
        color: #fff;
        background: #169e8c;
        .custom-tree-node {
          color: #fff;
          //overflow: hidden;
          span {
            display: flex;
            //overflow: hidden;
            .iconfont {
              //width: 30px;
              display: inline-table;
            }
          }
        }
      }

      .disconnect {
        color: #d3d3d3;
      }
    }
    /*拖拽区div样式*/
    .resize {
      cursor: col-resize;
      float: left;
      position: relative;
      background-color: #dcdfe6;
      width: 3px;
      height: 100%;
      /*拖拽区鼠标悬停样式*/
      &:hover {
        background-color: #169e8c;
      }
    }

    .picSetBox {
      display: flex;
      width: 100%;
      height: 100%;
      //background: #fcc;
      flex: 1;
      overflow: hidden;
      border-left: 1px solid @border-color-base;
      .swiperBox {
        -webkit-box-flex: 1;
        -ms-flex: 1;
        flex: 1;
        width: auto;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        position: relative;

        .title {
          height: 32px;
          padding-left: 12px;
          line-height: 32px;
          color: #fff;
          font-size: 12px;
          //background-color: #169e8cb0;
          background: linear-gradient(180deg, #4cdbc8 10%, #128071 100%);
          .el-breadcrumb {
            line-height: 32px;
            color: #fff !important;
            font-size: 14px;
            height: 32px;
            .el-breadcrumb__inner,
            .el-breadcrumb__separator {
              color: #fff !important;
            }
          }
        }
        .el-loading-mask {
          background-color: rgba(0, 0, 0, 0.3);
        }
      }
      .parameterArea {
        width: 220px;
        padding: 0px 8px;
        border-left: 1px solid #dcdfe6;
        position: relative;
        .zzbox {
          height: 32px;
          line-height: 32px;
          display: flex;
          //margin-bottom: 16px;
          //background-color: #169e8cb0;
          b {
            color: #169e8c;
            font-size: 14px;
            font-weight: normal;
          }
          .el-button--text {
            color: #f08200;
          }
        }
        .paramsDate,
        .monitorItemBox,
        .setTimebtn,
        .setfocalLength {
          margin-bottom: 16px;
          position: relative;
          h3 {
            font-size: 14px;
            font-weight: normal;
            color: @color-text-primary;
            margin-bottom: 8px;
          }
        }
        .setTimebtn {
          .buttonGroup {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            .el-button {
              margin-bottom: 8px;
              width: 104px;
            }
            .el-button + .el-button {
              margin-left: 0px;
            }
          }
        }
        .setfocalLength {
          .selectChannel {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            .labelname {
              font-size: 14px;
              margin-right: 4px;
              width: 80px;
              color: #666;
            }
          }
          .buttonGroup {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            .el-button {
              margin-bottom: 8px;
              width: 104px;
            }
            .el-button + .el-button {
              margin-left: 0px;
            }
          }
        }
      }
    }
  }
}
.picdropStyle,
.videodropStyle,
.gpsdropStyle {
  width: 104px;
  margin-top: 0px !important;
}
</style>
