<template>
  <div class="monitorBox" v-loading="loadingBg">
    <div class="monitor-container">
      <!-- 左侧数据列表树 -->
      <div class="sideBar">
        <el-tree
          :data="lineTreeData"
          :props="defaultProps"
          ref="tree"
          node-key="id"
          highlight-current
          :default-expand-all="true"
          @node-click="handleNodeClick"
          :current-node-key="currentNodekey"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <div v-if="node.level === 1">
              <span class="iconfont icon-dianli"></span>
              <span>{{ node.label }} </span>
            </div>
            <div v-else-if="data.list && node.level !== 1">
              <span class="iconfont icon-dianlihangye"> </span>
              <span>{{ node.label }} </span>
            </div>
            <div v-else>
              <span
                class="iconfont icon-video-camera"
                :class="data.onlinestatus == 0 ? 'disconnect' : ''"
                style="margin-right: 6px"
              ></span>
              <span :class="data.onlinestatus == 0 ? 'disconnect' : ''">{{
                node.label
              }}</span>
            </div>
          </span>
          <!-- <span
              v-else
              class="iconfont icon-video-camera"
              style="margin-right: 6px"
            ></span>
            <span :class="data.onlinestatus == 0 ? 'disconnect' : ''"
              >{{ node.label }} -- {{ data.cmdid }}</span
            >
          </span> -->
        </el-tree>
      </div>
      <!-- 带参数的中心内容右侧参数区 -->
      <div class="picSetBox">
        <div class="swiperBox" v-loading="loading">
          <carouselChart
            ref="carouselpic"
            :terminalPhoto="terminalPhoto"
            v-if="terminalPhoto.length > 0"
          ></carouselChart>
          <!-- <div class="totalPic" v-if="totalPic !== 0">
            图片总数：{{ totalPic }}张
          </div> -->
        </div>
        <div class="parameterArea">
          <div class="zzbox">
            <!-- <h3>装置名称</h3> -->
            <p class="zzidname">{{ cmdid }}</p>
          </div>
          <div class="paramsDate">
            <h3>日历快速查询</h3>
            <el-date-picker
              v-model="dateValue"
              type="date"
              placeholder="选择日期"
              value-format="timestamp"
              @change="changedate"
            >
            </el-date-picker>
          </div>
          <div class="monitorItemBox">
            <h3>选择通道监拍点</h3>

            <el-select
              v-model="channelListValue"
              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
                }}
                <!-- {{ item.label }}{{ item.alias }} -->
              </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"
                  :disabled="zzstatus == 0"
                >
                  主动拍照<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"
                  :disabled="zzstatus == 0"
                >
                  主动录像<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"
                :disabled="zzstatus == 0"
              >
                装置信息</el-button
              >
              <el-button
                type="primary"
                @click.native.stop="handleSetSchedule()"
                :disabled="zzstatus == 0"
                >拍照时间表</el-button
              >
              <!-- <el-dropdown
                class="dropgps"
                trigger="click"
                @command="handleCommand"
              >
                <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-dropdown
                class="dropgps"
                trigger="click"
                @command="handleCommandWarn"
              >
                <el-button type="primary" :disabled="zzstatus == 0">
                  声光报警<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>

              <!-- <el-button type="primary" @click="handlehistoryPic"
                >历史图片</el-button
              > -->
            </div>
          </div>
        </div>
      </div>
      <setschedule ref="setschedule_ref"></setschedule>
      <info-dialog ref="infodialog_ref"></info-dialog>
    </div>
  </div>
</template>

<script>
import {
  getdyTreeListJoggle,
  getChannelByTermidJoggle,
  getTerminalPhotoListJoggle,
  getLatestPhotoJoggle,
  getReturnedPhotoJoggle,
  alarmMarkJoggle,
} from "@/utils/api/index";
import { mapState } from "vuex";
import carouselChart from "../components/carouselChart.vue";
import setschedule from "./components/setschedule.vue";
import deviceUpgrade from "./components/deviceUpgrade.vue";
import infoDialog from "./components/infoDialog.vue";
export default {
  components: {
    carouselChart,
    setschedule,
    deviceUpgrade,
    infoDialog,
  },
  data() {
    return {
      btnpicloading: false,
      btnvideoloading: false,
      flag: true,
      onlinestatus: "", //设备状态啊
      showBigPic: true,
      defaultKey: "",
      lineTreeData: [],
      treeStatus: [],
      statusTimer: null,
      defaultProps: {
        //指定参数格式回显数据
        children: "list",
        label: "name",
      },
      currentNodekey: "", //默认选中的节点树,
      cmdid: "", //装置id,
      channelId: "", //通道装置id
      channelList: "", //通道数据
      channelOption: [], //通道分类
      channelListOption: [], //通道内容
      channelListValue: "",
      channelValue: [], //选中的通道
      terminalPhoto: [], //获取拍照装置当前数据
      totalPic: "",
      dateValue: "", //日期
      nopicPath: require("@/assets/img/nopic.jpg"),
      loadingBg: true,
      loading: true,
      newPicData: "",
      timer: null,
      treetimer: null,
      treenum: 0,
      i: 0,
      newTermId: "",
      zzstatus: "",
    };
  },
  // watch: {
  //   lineTreeData: {
  //     handler() {
  //       console.log("count改变");
  //     },
  //     immediate: true, // 加此属性
  //   },
  // },
  computed: {
    ...mapState(["channelid", "termid"]),
    channelid() {
      let storechannelid = localStorage.getItem("channelid");
      return storechannelid;
      // return this.$store.state.channelid;
    },
    termid() {
      let storetermid = localStorage.getItem("termid");
      return storetermid;
    },
  },
  mounted() {},
  created() {
    this.getLineTreeList();
    this.getDateTime();
    console.log(this.dateValue);
    this.treetimer = window.setInterval(() => {
      setTimeout(this.getLineTreeStatus(), 0);
    }, 300000);
  },
  methods: {
    //获取当前时间
    getDateTime() {
      this.dateValue = new Date().getTime();
    },
    //选择时间
    changedate() {
      console.log(this.dateValue);
      console.log(this.channelList);
      this.getTerminalPhotoList(
        this.channelValue,
        this.dateValue,
        this.channelList[0].termId
      );
    },
    //获取状态
    getLineTreeStatus() {
      getdyTreeListJoggle()
        .then((res) => {
          console.log(res);
          this.lineTreeData = res.data.list;
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.newTermId); //一定要加这个选中了否则样式没有出来
          });
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //获取左侧树结构
    getLineTreeList() {
      this.loadingBg = true;
      getdyTreeListJoggle()
        .then((res) => {
          console.log(res);
          this.lineTreeData = res.data.list;
          console.log(this.lineTreeData);
          console.log(this.lineTreeData[0].list[0].list);
          if (this.lineTreeData[0].list[0].list.length > 0) {
            this.currentNodekey = this.lineTreeData[0].list[0].list[0].id; //第一个数据
            this.newTermId = this.lineTreeData[0].list[0].list[0].id;

            this.cmdid = this.lineTreeData[0].list[0].list[0].cmdid;
            this.zzstatus = this.lineTreeData[0].list[0].list[0].onlinestatus;
            console.log(this.zzstatus);
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
              this.channelId = this.currentNodekey;
              this.getChannelList(this.channelId); //获取通道id接口
            });
          }
          this.loadingBg = false;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //点击获取当前点击的tree数据
    handleNodeClick(data, node) {
      console.log(data, node);
      if (data.list) {
        this.$refs.tree.setCurrentKey(data.list[0].id);
      }
      this.zzstatus = data.onlinestatus;
      console.log(this.zzstatus);
      this.channelId = data.id; //获取当前点击的id
      this.cmdid = data.cmdid;
      this.newTermId = data.id; //获取当前点击的id
      console.log(data);
      this.channelValue = [];
      this.channelOption = [];
      this.channelListOption = [];
      this.getChannelList(this.channelId); //获取通道id接口
      this.stop();
      this.btnvideoloading = false;
      this.btnpicloading = false;
    },
    //获取通道的接口
    getChannelList(id) {
      getChannelByTermidJoggle({ termid: id })
        .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,
            });
            this.channelValue.push(item.channelid); //默认选中所有通道
          }); // 选择通道一通道二select框
          console.log(this.channelOption);
          console.log(this.channelValue);
          this.channelListOption = [];
          this.channelListOption.push({
            label: "全部",
            value: "",
            termid: "",
            alias: "",
          });
          this.channelList.forEach((item) => {
            this.channelListOption.push({
              label: item.channelname,
              value: item.channelid,
              termid: item.termId,
              alias: item.alias,
            });
          });
          this.channelListValue = this.channelListOption[0].value; //默认选中所有通道
          // console.log(JSON.parse(JSON.stringify(this.channelValue)));
          // this.channelValue = JSON.parse(JSON.stringify(this.channelValue));
          console.log(this.channelOption.length);
          if (this.channelOption.length == 0) {
            console.log("没有绑定通道");
            this.terminalPhoto = [
              {
                path: this.nopicPath,
                termId: id,
              },
            ];
            console.log(this.terminalPhoto);
            return;
          } else {
            this.getTerminalPhotoList(
              this.channelValue,
              this.dateValue,
              this.channelList[0].termId
            ); //获取图片列表是传当前设备的 id 和termid
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log("没有绑定通道");
          this.terminalPhoto = [
            {
              path: this.nopicPath,
              termId: id,
            },
          ];
          console.log(this.terminalPhoto);
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //获取图片
    getTerminalPhotoList(id, date, termId) {
      this.loading = true;
      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,
              },
            ];
            this.totalPic = 0;
          } else {
            this.terminalPhoto = res.data.list;
          }

          console.log(this.terminalPhoto.length);
          this.totalPic = res.data.num;
          //this.$refs.a.getphotodata(this.terminalPhoto);
          this.loading = false;
          console.log(this.terminalPhoto);
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //切换通道
    changeChannelId(val) {
      let selchannel = [];
      if (!val) {
        this.channelList.forEach((item) => {
          selchannel.push(item.channelid); //选中所有通道
        });
      } else {
        selchannel.push(val);
      }
      let channelObj = {};
      channelObj = this.channelOption.find(function (i) {
        return i.value;
      });
      console.log(channelObj);
      this.getTerminalPhotoList(selchannel, this.dateValue, channelObj.termid);
    },

    //设置时间表
    handleSetSchedule() {
      this.$refs.setschedule_ref.display();
      this.$refs.setschedule_ref.getSingleAccess(this.channelId, this.cmdid);
      this.$refs.setschedule_ref.deviceList();
    },
    handleCommandWarn(command) {
      switch (command) {
        case "open": //开启
          this.handleWarn(1);
          break;
        case "close": //关闭
          this.handleWarn(0);
          break;
      }
    },
    //声光报警
    handleWarn(val) {
      console.log("声光报警");
      console.log(this.cmdid);
      alarmMarkJoggle({ cmdId: this.cmdid, ctrl: val })
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            if (val == 1) {
              this.$message({
                showClose: true,
                message: "声光报警开启成功",
                type: "success",
              });
            } else {
              this.$message({
                showClose: true,
                message: "声光报警关闭成功",
                type: "success",
              });
            }
          }
        })
        .catch((err) => {
          this.$message({
            showClose: true,
            message: "声光报警操作失败",
            type: "error",
          });
        });
    },
    //线缆显示
    handleCommandLine(command) {
      switch (command) {
        case "open": //开启
          this.$refs.carouselpic.openline();
          break;
        case "close": //关闭
          this.$refs.carouselpic.handelClear();
          break;
      }
    },

    handleShowErr() {
      this.$message({
        showClose: true,
        message: "该功能暂未开发,敬请期待",
        type: "warning",
      });
    },

    //手动拍照
    handleCommandpic(command) {
      this.btnpicloading = true;
      console.log(command);
      getLatestPhotoJoggle({
        captureType: 0,
        channel: command,
        // cmdid: this.cmdid,
        termId: this.newTermId,
        preset: 255,
      })
        .then((res) => {
          this.$message({
            showClose: true,
            message: "手动拍照请求成功！",
            type: "success",
          });
          console.log(res);
          this.newPicData = res.data;
          console.log(this.newPicData);
          console.log(this.newTermId);

          this.timer = window.setInterval(() => {
            this.newPicApi();
            this.i++;
          }, 5000);
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //手动拍视频
    handleCommandvideo(command) {
      console.log(command);
      this.btnvideoloading = true;
      getLatestPhotoJoggle({
        captureType: 1,
        channel: command,
        //cmdid: this.cmdid,
        termId: this.newTermId,
        preset: 255,
      })
        .then((res) => {
          this.$message({
            showClose: true,
            message: "手动拍视频请求成功！",
            type: "success",
          });
          console.log(res);
          this.newPicData = res.data;
          console.log(this.newPicData);
          console.log(this.newTermId);
          this.timer = window.setInterval(() => {
            this.newPicApi();
            this.i++;
          }, 10000);
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    //手动拍照
    // handleShowPic() {
    //   console.log(this.channelValue[0]);
    //   console.log(this.cmdid);
    //   getLatestPhotoJoggle({
    //     captureType: 0,
    //     channel: this.channelValue[0],
    //     cmdid: this.cmdid,
    //     preset: 255,
    //   })
    //     .then((res) => {
    //       this.$message({
    //         message: "自动拍照请求成功！",
    //         type: "success",
    //       });
    //       console.log(res);
    //       this.newPicData = res.data;
    //       console.log(this.newPicData);
    //       console.log(this.newTermId);

    //       this.timer = window.setInterval(() => {
    //         this.newPicApi();
    //         this.i++;
    //       }, 10000);
    //     })
    //     .catch((err) => {
    //       console.log(err); //代码错误、请求失败捕获
    //     });
    // },
    //获取最新图片
    newPicApi() {
      getReturnedPhotoJoggle({
        photoTime: this.newPicData,
        termId: this.newTermId,
      }).then((res) => {
        console.log(res.data);
        console.log(this.i);
        //console.log(this.newPicData, this.currentNodekey);
        if (res.data == true && this.i < 10) {
          console.log(res.data);
          clearInterval(this.timer);
          this.timer = null;
          this.getTerminalPhotoList(
            this.channelValue,
            this.dateValue,
            this.channelList[0].termId
          );
          this.btnpicloading = false;
          this.btnvideoloading = false;
          console.log("返回最新图片");
          this.i = 0;
        } else if (res.data == false && this.i > 10) {
          this.i = 0;
          clearInterval(this.timer);
          this.timer = null;
          this.$message({
            showClose: true,
            message: "装置暂无响应，请稍后再试！",
            type: "warning",
          });
          this.btnpicloading = false;
          this.btnvideoloading = false;
        }
        console.log("2222222222222222");
      });
    },
    stop() {
      clearInterval(this.timer);
      this.timer = null;
    },

    //装置信息handleShowInfo
    handleShowInfo() {
      this.$refs.infodialog_ref.display();
      this.$refs.infodialog_ref.getListData(this.channelId, this.cmdid);
    },
    //历史图片
    // handlehistoryPic() {
    //   this.$router.push({ path: "/realTimeSearch" });
    //   // sessionStorage.setItem("keyPath", " realTimeSearch");
    // },
  },
  destroyed() {
    clearInterval(this.treetimer);
    this.treetimer = null;
    //离开页面是销毁
    if (this.timer) {
      console.log(this.timer);
      clearInterval(this.timer);
      this.timer = null;
    } //利用vue的生命周期函数
  },
};
</script>

<style lang="less">
.monitorBox {
  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;
      overflow: auto;
      padding: 16px 0px;
      .el-tree {
        .el-tree-node__content {
          height: 40px;
          font-size: 12px;
        }
        .custom-tree-node {
          color: #333;
        }
      }
      .el-tree--highlight-current
        .el-tree-node.is-current
        > .el-tree-node__content {
        // 设置颜色
        color: #fff;
        background: #169e8c;
        .custom-tree-node {
          color: #fff;
        }
      }

      .disconnect {
        color: #d3d3d3;
      }
    }
    .picSetBox {
      display: flex;
      width: 100%;
      height: 100%;
      //background: #fcc;
      flex: 1;
      overflow: hidden;
      .swiperBox {
        -webkit-box-flex: 1;
        -ms-flex: 1;
        flex: 1;
        width: auto;
        overflow: hidden;
        display: flex;
        flex-direction: column;
      }
      .totalPic {
        width: 100%;
        height: 16px;
        margin-bottom: 8px;
        text-align: right;
        font-size: 12px;
        color: #2d8cf0;
        font-weight: bold;
        line-height: 16px;
      }
    }
    .parameterArea {
      width: 220px;
      padding: 16px 16px;
      border-left: 1px solid #dcdfe6;
      position: relative;
      .monitorItemBox,
      .paramsDate,
      .setTimebtn,
      .GPSItemBox,
      .zzbox {
        margin-bottom: 16px;
        h3 {
          font-size: 14px;
          font-weight: normal;
          color: @color-text-primary;
          margin-bottom: 8px;
        }
        .el-date-editor.el-input {
          width: 215px;
        }
        .zzidname {
          font-weight: normal;
        }
      }
      .setTimebtn {
        // position: absolute;
        // bottom: 0px;
        .buttonGroup {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .el-button {
            margin-bottom: 8px;
            width: 104px;
          }
          .el-button + .el-button {
            margin-left: 0px;
          }
        }
      }
    }
  }
}
.messageGps {
  .el-message-box__message {
    p {
      line-height: 32px;
      font-size: 16px;
      label {
        margin-right: 4px;
      }
      span {
        color: #333;
      }
    }
  }
}
.el-loading-mask {
  z-index: 99;
}
.picdropStyle,
.videodropStyle,
.gpsdropStyle {
  width: 104px;
  margin-top: 0px !important;
}
</style>
