<template>
  <div class="monitor-container">
    <div class="monitor-wrap">
      <div class="video-box">
        <div class="fbg" v-if="fScreen"></div>
        <div
          class="fbgBtn"
          @click="fScreenFun()"
          v-if="!oneFScreen && fScreen"
        ></div>
        <div
          :class="{ 'video-container': true, fScreen: fScreen }"
          ref="videoContainerRef"
        >
          <!-- 非插件播放 ，默认非插件播放-->
          <div
            :class="{
              videoItem: true,
              a1: divNum == 1,
              a2: divNum == 2,
              a9: divNum == 9,
              a12: divNum == 12,
              selected: count == selected,
            }"
            v-for="count in divNum"
            :key="String(count) + divNum"
            @click="selectVideo($event, count, 'my-video' + divNum + count)"
          >
            <span style="display: none" class="current">{{
              Idlist[count - 1]
            }}</span>
            <div class="vedio_btn_control">
              <div class="direc">
                <div
                  @click.stop="configCamera(oneId, 'takephoto', '')"
                  class="cameraCtr"
                ></div>
                <div
                  @mousedown.stop="configCamera(oneId, 'move', 0)"
                  @mouseup.stop="stopConfigCamera(oneId)"
                  class="upCtr"
                ></div>
                <div
                  @mousedown.stop="configCamera(oneId, 'move', 1)"
                  @mouseup="stopConfigCamera(oneId)"
                  class="downCtr"
                ></div>
                <div
                  @mousedown.stop="configCamera(oneId, 'move', 2)"
                  @mouseup="stopConfigCamera(oneId)"
                  class="leftCtr"
                ></div>
                <div
                  @mousedown.stop="configCamera(oneId, 'move', 3)"
                  @mouseup="stopConfigCamera(oneId)"
                  class="rightCtr"
                ></div>
              </div>
              <div class="zoom">
                <!-- 无论插件还是费插件都可以放大缩小 -->
                <span
                  class="addCtr"
                  @mousedown.stop="configCamera(oneId, 'move', 8)"
                  @mouseup="stopConfigCamera(oneId)"
                ></span>
                <span
                  class="reduceCtr"
                  @mousedown.stop="configCamera(oneId, 'move', 9)"
                  @mouseup="stopConfigCamera(oneId)"
                ></span>
              </div>
            </div>
            <i
              @click.stop="oneFullFun($event, count)"
              class="iconfont icon-quanping fSBtn"
            ></i>
            <div
              style="width: 100%; height: 100%"
              :id="'my-video' + divNum + count"
            ></div>
          </div>
        </div>
        <div class="split-screen">
          <span
            :class="divNum == 1 ? 'sp0 sp' : 'sp00 sp'"
            @click="splitView(1)"
          ></span>
          <span
            :class="divNum == 2 ? 'sp1 sp' : 'sp01 sp'"
            @click="splitView(2)"
          ></span>
          <span
            :class="divNum == 9 ? 'sp2 sp' : 'sp02 sp'"
            @click="splitView(9)"
          ></span>
          <span
            :class="divNum == 12 ? 'sp3 sp' : 'sp03 sp'"
            @click="splitView(12)"
          ></span>
        </div>
      </div>
      <div class="nav-box">
        <ul class="viewLists">
          <li
            v-for="(item, index) in Idlist"
            :key="index"
            :class="{ active: activeIndex == index }"
            @click="selectEquip(item.device_id, item.jktype, index)"
          >
            <span
              :class="['dot', item.status == 1 ? 'onLine' : 'outLine']"
            ></span>
            {{ item | formatName }}
          </li>
        </ul>
        <div class="splitPage" onselectstart="return false">
          <span
            class="arrow el-icon-caret-top"
            @click="splitPage('jian')"
          ></span>
          <span>{{ currPage }}</span>
          <span>/</span>
          <span>{{ totalPage }}</span>
          <span
            class="arrow el-icon-caret-bottom"
            @click="splitPage('jia')"
          ></span>
        </div>
        <div class="direc">
          <div
            @click="configCamera(id, 'takephoto', '')"
            class="cameraCtr"
          ></div>
          <div
            @mousedown="configCamera(id, 'move', 0)"
            @mouseup="stopConfigCamera(id)"
            class="upCtr"
          ></div>
          <div
            @mousedown="configCamera(id, 'move', 1)"
            @mouseup="stopConfigCamera(id)"
            class="downCtr"
          ></div>
          <div
            @mousedown="configCamera(id, 'move', 2)"
            @mouseup="stopConfigCamera(id)"
            class="leftCtr"
          ></div>
          <div
            @mousedown="configCamera(id, 'move', 3)"
            @mouseup="stopConfigCamera(id)"
            class="rightCtr"
          ></div>
        </div>
        <div class="btnBox">
          <div class="zoom">
            <!-- 无论插件还是费插件都可以放大缩小 -->
            <span
              class="addCtr"
              @mousedown="configCamera(id, 'move', 8)"
              @mouseup="stopConfigCamera(id)"
            ></span>
            <span
              class="reduceCtr"
              @mousedown="configCamera(id, 'move', 9)"
              @mouseup="stopConfigCamera(id)"
            ></span>
          </div>
          <div
            v-show="jktype == 1"
            class="playBack"
            @click="playBackDialogVisible = true"
          ></div>
          <div @click="addEquip()" class="addequip"></div>
          <div @click="fScreenFun()" class="fSBtn1"></div>
        </div>
      </div>
    </div>
    <!-- 拍照 -->
    <el-dialog
      title="手动下载"
      :visible.sync="takePhotoDialogVisible"
      width="30%"
    >
      <el-input type="textarea" id="picUrl" v-model="picUrl"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="takePhotoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="copyPicUrl">复制</el-button>
      </span>
    </el-dialog>
    <!-- 查看回放 -->
    <el-dialog
      title="查看回放"
      :visible.sync="playBackDialogVisible"
      width="600px"
      @close="palyBackClose"
    >
      <el-form
        ref="backFormRef"
        :model="backForm"
        :rules="backFormRules"
        label-width="80px"
      >
        <el-form-item label="时间范围" prop="time">
          <el-date-picker
            v-model="backForm.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="通道" prop="aisle">
          <el-select v-model="backForm.aisle" placeholder="请选择">
            <el-option label="通道一" value="1"> </el-option>
            <el-option label="通道二" value="2"> </el-option>
            <el-option label="通道三" value="3"> </el-option>
            <el-option label="通道四" value="4"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="playBackDialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="playBackSubmit">确定</el-button>
        </el-form-item>
      </el-form>
      <div id="videoBack">
        <div id="playWind"></div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import "@/plugin/ezuikit.js";
export default {
  data() {
    return {
      currPage: 1, //当前分页
      totalPage: 0, //总分页
      id: "", //监控选中状态selected，右侧菜单控制的ID
      oneId: "", //单个监控全屏时的监控id
      activeIndex: null, //控制设备列表选中状态
      jktype: "", //为1有回放，否则无回放
      divNum: 1, //默认分屏数量
      hlsHdSrc: "",
      rtmpHdSrc: "",
      player: null, //videojs的对象
      takePhotoDialogVisible: false, //拍照弹框
      Idlist: [], //右侧设备列表
      divMainHeight: "", //视频盒子高度
      selected: "", //默认不选中视频窗口
      divName: "", //选中的监控的id
      html: "", //插件播放内容
      picUrl: "", //视频拍照地址
      playBackDialogVisible: false,
      fScreen: false, //默认多个监控非全屏
      oneFScreen: false, //单个监控全屏状态
      btnFlag: true, //全屏按钮显示控制
      backForm: {
        time: "",
        start: "",
        end: "",
        aisle: "",
      },
      backFormRules: {
        time: [
          { required: true, message: "请选择时间范围", trigger: "change" },
        ],
        aisle: [{ required: true, message: "请选择通道", trigger: "change" }],
      },
      playback: {}, //回放
      videoObj: {},
    };
  },
  filters: {
    formatName: function (value) {
      //设备名字
      if (value.device_name) {
        return value.device_name;
      } else {
        return "设备" + value.device_id;
      }
    },
  },
  created() {
    this.getJkList();
  },
  methods: {
    //获取视频列表
    getJkList() {
      this.$axios({
        method: "POST",
        url: "/api/list_camera",
        data: this.qs.stringify({ page: this.currPage }),
      }).then((res) => {
        this.Idlist = res.data.data;
        this.totalPage = Math.ceil(res.data.counts / 12);
        this.initMonitor(); //进入页面默认1屏都显示视频
      });
    },
    getJkList2() {
      this.$axios({
        method: "POST",
        url: "/api/list_camera",
        data: this.qs.stringify({ page: this.currPage }),
      }).then((res) => {
        this.Idlist = res.data.data;
      });
    },
    //视频分页
    splitPage(str) {
      this.selected = "";
      this.activeIndex = null;
      if (str == "jian") {
        if (this.currPage > 1) {
          this.currPage--;
          this.getJkList2();
        }
      } else {
        if (this.currPage < this.totalPage) {
          this.currPage++;
          this.getJkList2();
        }
      }
    },
    //上下左右和拍照
    configCamera(id, ctrl, movenum) {
      if (id != "") {
        if (ctrl == "takephoto") {
          this.$axios({
            method: "POST",
            url: "/api/camera_takephoto",
            data: this.qs.stringify({
              device_id: id,
              ctrl: ctrl,
            }),
          }).then((res) => {
            if (res.data.code == 200) {
              let data = res.data.data;
              this.picUrl = data.picUrl;
              this.takePhotoDialogVisible = true;
            } else {
              this.$message.error("设备网络异常!");
            }
          });
        } else {
          //上下左右、放大、缩小
          this.$axios({
            method: "POST",
            url: "/api/ctrl_camera",
            data: this.qs.stringify({
              device_id: id,
              ctrl: ctrl,
              movenum: movenum,
            }),
          }).then((res) => {
            if (res.data == 1) {
              this.$message.success("操作成功");
            } else {
              this.$message.error("操作失败");
            }
          });
        }
      } else {
        this.$message.error("请选中监控");
      }
    },
    //关闭方向
    stopConfigCamera(id) {
      if (id != "") {
        this.$axios({
          method: "POST",
          url: "/api/ctrl_camera",
          data: this.qs.stringify({
            device_id: id,
            ctrl: "stop",
          }),
        });
      }
    },
    //分屏默认显示视频
    initMonitor() {
      this.selected = ""; //取消监控选中
      this.activeIndex = null; //取消菜单选中
      for (let item = 0; item < this.divNum; item++) {
        if (this.Idlist[item]) {
          //避免右侧监控数量少于divNum
          this.$axios({
            url: "/api/addr_camera",
            method: "POST",
            data: this.qs.stringify({ device_id: this.Idlist[item].device_id }),
          }).then((res) => {
            var data = eval("(" + res.data + ")");
            var hlsHdSrc = data.hlsHd;
            var rtmpHdSrc = data.rtmp;
            this.$nextTick(() => {
              let playHtml = `<video id="videoitem${this.divNum}${item}"
								 style='width: 100%;height: 100%;' src="${hlsHdSrc}" autoplay  poster='' muted controls playsInline  webkit-playsinline>
								 </video>`;
              document.getElementById(
                "my-video" + this.divNum + (item + 1)
              ).innerHTML = playHtml;
              this.$nextTick(() => {
                this.videoObj[
                  "videoitem" + this.divNum + item
                ] = new EZUIKit.EZUIPlayer("videoitem" + this.divNum + item);
              });
            });
          });
        }
      }
    },
    //选中右侧菜单设备
    selectEquip(device_id, jktype, index) {
      console.log(jktype);
      if (this.selected !== "") {
        //判断是否选中左侧监控
        document
          .getElementsByClassName("selected")[0]
          .getElementsByClassName("current")[0].innerHTML = device_id; //更换current里的设备id值
        console.log(device_id);
        this.jktype = jktype;
        this.activeIndex = index; //菜单选中状态
        this.id = device_id; //保存选中的设备id
        console.log(this.divName);
        this.$axios({
          url: "/api/addr_camera",
          method: "POST",
          data: this.qs.stringify({ device_id: device_id }),
        }).then((res) => {
          var data = eval("(" + res.data + ")");
          let hlsHdSrc = data.hlsHd;
          let playHtml = `<video id="n${this.divName}"
								 style='width: 100%;height: 100%;' src="${hlsHdSrc}" autoplay  poster='' muted controls playsInline  webkit-playsinline>
								 </video>`;
          let target = document.getElementById(this.divName);
          target.removeChild(target.childNodes[0]);
          target.innerHTML = playHtml;
          this.$nextTick(() => {
            new EZUIKit.EZUIPlayer(`n${this.divName}`);
          });
        });
      }
    },
    //点击分屏
    splitView(num) {
      this.divNum = num;
      for (let item in this.videoObj) {
        console.log(item);
        this.videoObj[item].stop();
      }
      this.$nextTick(() => {
        this.initMonitor();
      });
    },
    //点击视频
    selectVideo(e, i, divName) {
      console.log("外");
      let current = e.currentTarget.getElementsByClassName("current")[0]
        .innerHTML;
      if (current.indexOf("device_id") == -1) {
        this.id = current;
      } else {
        this.id = JSON.parse(current).device_id;
      }
      console.log(this.id);
      this.divName = divName; //视频外面div的id
      this.selected = i;
    },
    //复制拍照地址
    copyPicUrl() {
      document.getElementById("picUrl").select();
      this.$message({
        showClose: true,
        message: "手动复制，在浏览器打开，另存为",
      });
    },
    //添加设备
    addEquip() {
      this.$prompt("添加设备id", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.$axios({
            method: "POST",
            url: "/api/add_camera",
            data: this.qs.stringify({ device_id: value }),
          }).then((res) => {
            if (res.data == 1) {
              this.getJkList();
            } else {
              this.$message.error(res.data);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消添加",
          });
        });
    },
    fScreenFun() {
      this.fScreen = !this.fScreen;
    },
    oneFullFun(el, i) {
      this.selected = i;
      let par = el.currentTarget.parentNode;
      let current = par.getElementsByClassName("current")[0].innerHTML;
      if (current == "") {
        return false;
      } else if (current.indexOf("device_id") == -1) {
        this.oneId = current;
      } else {
        this.oneId = JSON.parse(current).device_id;
      }
      this.$nextTick(() => {
        par.classList.toggle("fullScreen");
        this.oneFScreen = !this.oneFScreen; //点击菜单栏全屏按钮后，再点击单个监控全屏时，隐藏恢复按钮
      });
    },
    playBackSubmit() {
      this.$refs.backFormRef.validate((valid) => {
        if (!valid) {
          return false;
        }
      });
      let start = new Date(this.backForm.time[0]);
      let end = new Date(this.backForm.time[1]);
      let beginVal = "";
      let endVal = "";
      function checked(num) {
        if (num < 10) {
          num = "0" + num;
        }
        return num;
      }
      beginVal =
        beginVal +
        start.getFullYear() +
        checked(start.getMonth() + 1) +
        checked(start.getDate()) +
        checked(start.getHours()) +
        checked(start.getMinutes()) +
        checked(start.getSeconds());
      endVal =
        endVal +
        end.getFullYear() +
        checked(end.getMonth() + 1) +
        checked(end.getDate()) +
        checked(end.getHours()) +
        checked(end.getMinutes()) +
        checked(end.getSeconds());
      this.$axios({
        method: "POST",
        url: "/api/nvr_view",
        data: this.qs.stringify({
          e_id: this.id,
        }),
      }).then((res) => {
        if (!document.getElementById("playWind")) {
          document.getElementById("videoBack").innerHTML =
            '<div id="playWind"></div>';
        }
        let accessToken = res.data.jk_token;
        let url = `ezopen://open.ys7.com/${this.id}/${this.backForm.aisle}.local.rec?begin=${beginVal}&end=${endVal}`;
        this.playback = new EZUIKit.EZUIPlayer({
          id: "playWind",
          autoplay: true,
          url: url,
          accessToken: accessToken,
          decoderPath: "static/js/",
          width: 560,
          height: 460,
        });
      });
    },
    palyBackClose() {
      this.$refs.backFormRef.resetFields();
      this.playback.stop();
      document.getElementById("videoBack").innerHTML = "";
    },
  },
  destroyed() {
    for (let item in this.videoObj) {
      this.videoObj[item].stop();
      console.log(this.videoObj[item]);
    }
  },
};
</script>

<style lang='less' scoped>
ul,
li {
  list-style-type: none;
  margin: 0;
}
.monitor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  .monitor-wrap {
    height: 100%;
    display: flex;
    justify-content: space-between;
    background: #000;
    flex: 1;
    .video-box {
      flex: 1;
      padding: 10px;
      .fScreen {
        position: absolute;
        z-index: 8;
        top: 0;
        left: 0;
        width: 100%;
        height: 100% !important;
      }
      .fbg {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: #000;
        z-index: 5;
      }
      .fbgBtn {
        position: fixed;
        z-index: 9;
        right: 20px;
        bottom: 20px;
        width: 100px;
        height: 100px;
        background: url(../assets/images/monitor/fS2.png);
      }
      .video-container {
        width: 100%;
        height: calc(100% - 45px);
        background: #000;
        display: flex;
        flex-wrap: wrap;
        .fullScreen {
          position: fixed !important;
          width: 100% !important;
          height: 100% !important;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          z-index: 10;
          background: #000;
          .vedio_btn_control {
            display: block;
          }
        }
        .videoItem {
          position: relative;
          border: 1px solid #000;
          box-sizing: border-box;
          .fSBtn {
            position: absolute;
            z-index: 2;
            top: 10px;
            right: 20px;
            color: #fff;
            font-size: 20px;
            cursor: pointer;
          }
          .fSBtn:hover {
            color: red;
          }
        }
        .videoItem:hover {
          border-color: aquamarine;
        }
        .selected {
          border: 1px solid aquamarine;
        }
        .a1 {
          width: 100%;
          height: 100%;
        }
        .a2 {
          width: 50%;
          height: 100%;
        }
        .a9 {
          width: 33.3%;
          height: 33.3%;
        }
        .a12 {
          width: 33.3%;
          height: 25%;
        }
      }
      .split-screen {
        display: flex;
        justify-content: flex-start;
        padding: 15px 0;
        .sp {
          width: 17px;
          height: 17px;
          display: inline-block;
          margin-right: 10px;
          cursor: pointer;
        }
        .sp00 {
          background: url(../assets/images/monitor/1.png);
        }
        .sp01 {
          background: url(../assets/images/monitor/2.png);
        }
        .sp02 {
          background: url(../assets/images/monitor/9.png);
        }
        .sp03 {
          background: url(../assets/images/monitor/12.png);
        }
        .sp0 {
          background: url(../assets/images/monitor/11.png);
        }
        .sp1 {
          background: url(../assets/images/monitor/22.png);
        }
        .sp2 {
          background: url(../assets/images/monitor/99.png);
        }
        .sp3 {
          background: url(../assets/images/monitor/122.png);
        }
      }
    }
    .nav-box {
      width: 240px;
      background: #474e60;
      color: #fff;
      font-size: 14px;
      .viewLists {
        height: 50%;
        overflow: auto;
        padding: 0;
        li {
          padding-left: 25px;
          padding-right: 25px;
          line-height: 34px;
          cursor: pointer;
          .viewPhoto {
            color: #eba219;
            float: right;
            font-size: 12px;
            cursor: pointer;
          }
          .viewPhoto:hover {
            text-decoration: underline;
          }
          .dot {
            display: inline-block;
            width: 7px;
            height: 7px;
            border-radius: 100%;
            margin-right: 15px;
          }
          .onLine {
            background: #15bb88;
          }
          .outLine {
            background: #c1c1c1;
          }
        }
        li.active {
          background: #37414d;
          color: yellow;
        }
        li:hover {
          background: #37414d;
        }
      }
      .splitPage {
        height: 3%;
        margin-top: 2%;
        text-align: center;
        color: #15bb88;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        .arrow {
          font-size: 20px;
          cursor: pointer;
        }
      }
      .direc {
        position: relative;
        z-index: 0;
        text-align: center;
        width: 160px;
        height: 160px;
        margin: 10px auto;
        // position: relative;
        background: url(../assets/images/monitor/direction-btn.png)
					no-repeat center;
        background-size: contain;
        & > div {
          position: absolute;
          width: 53px;
          height: 53px;
          cursor: pointer;
        }
        .upCtr {
          top: 0px;
          transform: translateX(-50%);
          margin-left: 50%;
        }
        .downCtr {
          bottom: 0px;
          transform: translateX(-50%);
          margin-left: 50%;
        }
        .leftCtr {
          transform: translateY(-50%);
          left: 0;
          margin-top: 50%;
        }
        .rightCtr {
          transform: translateY(-50%);
          right: 0;
          margin-top: 50%;
        }
        .cameraCtr {
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          margin: auto;
        }
      }
      .btnBox {
        .zoom,
        .playBack,
        .playtype0,
        .playtype1,
        .addequip,
        .fSBtn1,
        .fSBtn2 {
          width: 140px;
          height: 32px;
          margin: auto;
          margin-bottom: 5px;
          cursor: pointer;
        }
        .zoom {
          background: no-repeat center / 100%
            url(../assets/images/monitor/zoom-btn.png);
          display: flex;
          & > span {
            flex: 1;
            height: 32px;
          }
        }
        .playBack {
          background: url(../assets/images/monitor/playback-btn.png)
						no-repeat center;
        }
        .playtype0 {
          background: url(../assets/images/monitor/playtype0.png)
						no-repeat center;
        }
        .playtype1 {
          background: url(../assets/images/monitor/playtype1.png)
						no-repeat center;
        }
        .addequip {
          background: url(../assets/images/monitor/addequip.png) no-repeat
						center;
        }
        .fSBtn1 {
          background: url(../assets/images/monitor/fS.png) no-repeat
						center;
          position: relative;
        }
      }
    }
  }

  .vedio_btn_control {
    display: none;
    position: absolute;
    right: 10px;
    bottom: 10px;
    z-index: 20;
    width: 140px;
    height: 200px;
    .direc {
      position: relative;
      text-align: center;
      width: 100px;
      height: 100px;
      margin: 10px auto;
      background: url(../assets/images/monitor/direction-btn.png)
				no-repeat center;
      background-size: contain;
      & > div {
        position: absolute;
        width: 33px;
        height: 33px;
        cursor: pointer;
      }
      .upCtr {
        top: 0px;
        transform: translateX(-50%);
        margin-left: 50%;
      }
      .downCtr {
        bottom: 0px;
        transform: translateX(-50%);
        margin-left: 50%;
      }
      .leftCtr {
        transform: translateY(-50%);
        left: 0;
        margin-top: 50%;
      }
      .rightCtr {
        transform: translateY(-50%);
        right: 0;
        margin-top: 50%;
      }
      .cameraCtr {
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
      }
    }
    .zoom {
      width: 140px;
      height: 32px;
      background: no-repeat center / 100%
        url(../assets/images/monitor/zoom-btn.png);
      display: flex;
      & > span {
        flex: 1;
        height: 32px;
      }
    }
  }
}
</style>