<template>
  <div class="monitor-container" style="cursor: default">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>监控系统</el-breadcrumb-item>
      <el-breadcrumb-item>监控{{ playType }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="monitor-wrap">
      <div class="video-box">
        <div class="video-container" ref="videoContainerRef">
          <!-- 插件播放 -->
          <div
            class="x"
            v-if="playType == 1"
            v-html="html"
            style="width: 100%; height: 100%"
          ></div>
          <!-- 非插件播放 ，默认非插件播放-->
          <div class="v" style="width: 100%; height: 100%" v-if="playType == 0">
            <div
              :class="{
                videoItem: true,
                a1: divNum == 1,
                a4: divNum == 4,
                a9: divNum == 9,
                selected: count == selected,
              }"
              v-for="count in divNum"
              :key="divNum + count"
              @click.capture="selectVideo(count)"
            >
              <div
                style="width: 100%; height: 100%"
                :id="'my-video' + count"
              ></div>
            </div>
          </div>
        </div>
        <div v-show="playType == 0" class="split-screen">
          <span class="sp sp01" @click="splitView(1)"></span>
          <span class="sp sp02" @click="splitView(4)"></span>
          <span class="sp sp03" @click="splitView(9)"></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 }}
            <span
              @click.stop="viewPhoto(item.device_id)"
              class="viewPhoto"
              v-if="item.photo_num"
              >查看图片</span
            >
          </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('takephoto', '')" class="cameraCtr"></div>
          <div
            @mousedown="configCamera('move', 0)"
            @mouseup="stopConfigCamera()"
            class="upCtr"
          ></div>
          <div
            @mousedown="configCamera('move', 1)"
            @mouseup="stopConfigCamera()"
            class="downCtr"
          ></div>
          <div
            @mousedown="configCamera('move', 2)"
            @mouseup="stopConfigCamera()"
            class="leftCtr"
          ></div>
          <div
            @mousedown="configCamera('move', 3)"
            @mouseup="stopConfigCamera()"
            class="rightCtr"
          ></div>
        </div>
        <div class="btnBox">
          <div class="zoom">
            <!-- 无论插件还是费插件都可以放大缩小 -->
            <span
              class="addCtr"
              @mousedown="configCamera('move', 8)"
              @mouseup="stopConfigCamera()"
            ></span>
            <span
              class="reduceCtr"
              @mousedown="configCamera('move', 9)"
              @mouseup="stopConfigCamera()"
            ></span>
          </div>
          <div
            v-show="jktype == 1"
            class="playBack"
            @click="playBackDialogVisible = true"
            id="playBack"
          ></div>
          <div
            v-show="playType == 0"
            @click="checkPlayType(1)"
            class="playtype1"
          ></div>
          <div
            v-show="playType == 1"
            @click="checkPlayType(0)"
            class="playtype0"
          ></div>
          <div @click="addEquip()" class="addequip"></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="dialogVisible = 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
            style="width: 400px"
            v-model="backForm.aisle"
            placeholder="请选择"
          >
            <el-option
              v-for="item in Number(jktype)"
              :key="item"
              :label="'通道' + item"
              :value="item"
            >
            </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>
export default {
  data() {
    return {
      currPage: 1, //当前分页
      totalPage: 0, //总分页
      id: "", //右侧菜单选中的设备ID
      activeIndex: 0, //控制设备列表选中状态
      jktype: "", //为1有回放，否则无回放
      divNum: 1, //默认分屏数量
      hlsHdSrc: "",
      rtmpHdSrc: "",
      takePhotoDialogVisible: false, //拍照弹框
      Idlist: [], //右侧设备列表
      divMainHeight: "", //视频盒子高度
      selected: 1, //默认选中第一个视频窗口
      playType: 0, //0:直播 ; 1：插件
      html: "", //插件播放内容
      picUrl: "", //视频拍照地址
      playBackDialogVisible: false,
      mapTojkId: this.$route.query.id, //四情基地监控设备id
      mapTojktype: this.$route.query.jktype, //四情基地监控设备jktype
      myVideo: {},
      backForm: {
        time: "",
        start: "",
        end: "",
        aisle: 1,
      },
      backFormRules: {
        time: [
          { required: true, message: "请选择时间范围", trigger: "change" },
        ],
        aisle: [{ required: true, message: "请选择通道", trigger: "change" }],
      },
      accessToken:'',
    };
  },
  filters: {
    formatName: function (value) {
      //设备名字
      if (value.equip_name) {
        return value.equip_name;
      } else {
        return "设备" + value.device_id;
      }
    },
  },
  mounted() {
    this.getJkList();
    // this.windowResize()
    // window.onresize = () => {
    // 	this.windowResize()
    // }
  },
  //注销window.onresize事件
  destroyed() {
    window.onresize = null;
    // this.player.dispose()
  },
  methods: {
    viewPhoto(id) {
      this.$router.push("/index/photoView/" + id);
    },
    //获取视频列表
    getJkList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=camera.camera_manage.list_camera",
        data: this.qs.stringify({ page: this.currPage }),
      }).then((res) => {
        if (res.data.message == "") {
          this.Idlist = res.data.data.data;
          this.accessToken=res.data.data.accessToken;
          this.totalPage = Math.ceil(res.data.data.counts / 10);
          if (this.mapTojkId && this.mapTojktype) {
            //基地展示跳转过来
            this.selectEquip(this.mapTojkId, this.mapTojktype, 99999);
          } else {
            this.selectEquip(
              this.Idlist[0].device_id,
              this.Idlist[0].jktype,
              0
            );
          }
        }
      });
    },
    //视频分页
    splitPage(str) {
      if (str == "jian") {
        if (this.currPage > 1) {
          this.currPage--;
          this.getJkList();
        }
      } else {
        if (this.currPage < this.totalPage) {
          this.currPage++;
          this.getJkList();
        }
      }
    },
    //关闭方向
    stopConfigCamera() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=camera.camera_manage.ctrl_camera",
        data: this.qs.stringify({
          device_id: this.id,
          ctrl: "stop",
        }),
      });
    },
    //上下左右和拍照
    configCamera(ctrl, movenum) {
      if (ctrl == "takephoto") {
        this.$axios({
          method: "POST",
          url: "/api/api_gateway?method=camera.camera_manage.camera_takephoto",
          data: this.qs.stringify({
            device_id: this.id,
          }),
        }).then((res) => {
          let data = JSON.parse(res.data.data);
          if (data.code == 200) {
            this.picUrl = data.data.picUrl;
            this.takePhotoDialogVisible = true;
          } else {
            this.$message.error(data.msg);
          }
        });
      } else {
        //上下左右、放大、缩小
        this.$axios({
          method: "POST",
          url: "/api/api_gateway?method=camera.camera_manage.ctrl_camera",
          data: this.qs.stringify({
            device_id: this.id,
            ctrl: ctrl,
            movenum: movenum,
          }),
        }).then((res) => {
          // if (res.data.message == '') {
          // 	this.$message.success('指令下发成功')
          // 	// this.stopConfigCamera() //关闭方向
          // }
        });
      }
    },
    //选中右侧菜单设备
    selectEquip(device_id, jktype, index) {
      this.jktype = jktype;
      this.activeIndex = index; //菜单选中状态
      this.id = device_id; //保存选中的设备id
      this.$axios({
        url: "/api/api_gateway?method=camera.camera_manage.addr_camera",
        method: "POST",
        data: this.qs.stringify({ device_id: device_id }),
      }).then((res) => {
        if (res.data.message == "") {
          var data = eval("(" + res.data.data + ")");
          let hlsHdSrc = data.hlsHd;
          let rtmpHdSrc = data.rtmpHd;
          if (this.playType == 1) {
            console.log("插件");
            //插件
            this.html = `<video id="player" autoplay muted poster='' controls playsInline webkit-playsinline src="${rtmpHdSrc}" style="width:100%; height:100%;"></video>`;
            setTimeout(() => {
              this.myVideo["xPlayer"] = new EZUIKit.EZUIPlayer(player);
              this.myVideo["xPlayer"].play();
            }, 1000);
          } else if (this.playType == 0) {
            console.log("非插件");
            let playHtml = `<video id="myPlayer${this.selected}"  muted autoplay  poster='' controls playsInline  webkit-playsinline src="${hlsHdSrc}"  style="width:100%; height:100%;"></video>`;
            document.getElementById(
              "my-video" + this.selected
            ).innerHTML = playHtml;
            //非插件
            this.$nextTick(() => {
              this.myVideo[`myPlayer${this.selected}`] = new EZUIKit.EZUIPlayer(
                `myPlayer${this.selected}`
              );
              setTimeout(() => {
                this.myVideo[`myPlayer${this.selected}`].play();
              }, 150);
              console.log(this.myVideo[`myPlayer${this.selected}`]);
              // this.player = videojs('my-video' + this.selected)
              // this.player.reset()
              // this.player.src({
              // 	src: this.hlsHdSrc,
              // 	type: 'application/x-mpegURL'
              // })
              // this.player.play()
              // this.player.load()
            });
          }
        }
      });
    },
    //函数：获取尺寸
    // windowResize() {
    // 	// console.log(this.$refs.videoContainerRef.offsetWidth);
    // 	// calc(100% - 47)
    // 	this.divMainHeight =
    // 		(this.$refs.videoContainerRef.offsetWidth * 9) / 16 + 'px'
    // },
    //点击分屏
    splitView(num) {
      for (let item in this.myVideo) {
        this.myVideo[item].stop();
      }
      this.divNum = num;
      this.selected = 1;
      this.selectEquip(this.id, this.jktype, this.activeIndex);
    },
    //点击视频
    selectVideo(i) {
      console.log(i);
      this.selected = i;
    },
    //播放模式切换，插件/视频直播
    checkPlayType(i) {
      this.playType = i;
      for (let item in this.myVideo) {
        this.myVideo[item].stop();
      }
      console.log(this.myVideo);
      this.selectEquip(this.id, this.jktype, this.activeIndex);
    },
    //复制拍照地址
    copyPicUrl() {
      document.getElementById("picUrl").select();
      this.$message({
        showClose: true,
        message: "手动复制，在浏览器打开，另存为",
      });
    },
    //添加设备
    addEquip() {
      this.$prompt("添加设备id", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=camera.camera_manage.add_camera",
            data: this.qs.stringify({ device_id: value }),
          }).then((res) => {
            if (res.data.message == "") {
              console.log(456);
              this.getJkList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消添加",
          });
        });
    },
    //回放
    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());
    
          if (!document.getElementById("playWind")) {
            document.getElementById("videoBack").innerHTML =
              '<div id="playWind"></div>';
          }
          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: this.accessToken,
            decoderPath: "static/js/",
            width: 560,
            height: 460,
          });
      });
    },
    palyBackClose() {
      this.$refs.backFormRef.resetFields();
      this.playback.stop();
      document.getElementById("videoBack").innerHTML = "";
    },
  },
};
</script>

<style lang='less' scoped>
.monitor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  .monitor-wrap {
    display: flex;
    justify-content: space-between;
    background: #323a47;
    flex: 1;
    .video-box {
      flex: 1;
      padding: 10px;
      .video-container {
        width: 100%;
        height: calc(100% - 47px);
        background: rgb(97, 93, 93);
        & > div {
          display: flex;
          flex-wrap: wrap;
          .videoItem {
            border: 1px solid #000;
            box-sizing: border-box;
          }
          .videoItem:hover {
            border-color: aquamarine;
          }
          .selected {
            border: 1px solid aquamarine;
          }
          .a1 {
            width: 100%;
            height: 100%;
          }
          .a4 {
            width: 50%;
            height: 50%;
          }
          .a9 {
            width: 33.3%;
            height: 33.3%;
          }
        }
      }
      .split-screen {
        display: flex;
        justify-content: flex-start;
        padding: 15px 0;
        .sp {
          width: 17px;
          height: 17px;
          display: inline-block;
          margin-right: 10px;
          cursor: pointer;
        }
        .sp01 {
          background: url(../../../assets/images/forecasting/monitor/sp1.png);
        }
        .sp02 {
          background: url(../../../assets/images/forecasting/monitor/sp2.png);
        }
        .sp03 {
          background: url(../../../assets/images/forecasting/monitor/sp3.png);
        }
        .sp01:hover {
          background: url(../../../assets/images/forecasting/monitor/sp1-active.png);
        }
        .sp02:hover {
          background: url(../../../assets/images/forecasting/monitor/sp2-active.png);
        }
        .sp03:hover {
          background: url(../../../assets/images/forecasting/monitor/sp3-active.png);
        }
      }
    }
    .nav-box {
      width: 240px;
      background: #474e60;
      color: #fff;
      font-size: 14px;
      .viewLists {
        height: 50%;
        overflow: auto;
        li {
          padding-left: 25px;
          padding-right: 25px;
          line-height: 40px;
          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 {
        text-align: center;
        width: 100%;
        height: 20%;
        margin: 5% 0 5% 0;
        position: relative;
        background: url(../../../assets/images/forecasting/monitor/direction-btn.png)
          no-repeat center;
        background-size: contain;
        & > div {
          position: absolute;
          width: 50px;
          height: 50px;
          cursor: pointer;
        }
        .upCtr {
          top: 10px;
          left: 50%;
          margin-left: -25px;
        }
        .downCtr {
          bottom: 10px;
          left: 50%;
          margin-left: -25px;
        }
        .leftCtr {
          top: 50%;
          left: 28px;
          margin-top: -25px;
        }
        .rightCtr {
          top: 50%;
          right: 28px;
          margin-top: -25px;
        }
        .cameraCtr {
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          margin: auto;
        }
      }
      .btnBox {
        height: 15%;
        .zoom,
        .playBack,
        .playtype0,
        .playtype1,
        .addequip {
          width: 140px;
          height: 32px;
          margin: auto;
          margin-bottom: 10px;
          cursor: pointer;
        }
        .zoom {
          background: no-repeat center / 100%
            url(../../../assets/images/forecasting/monitor/zoom-btn.png);
          display: flex;
          & > span {
            flex: 1;
            height: 32px;
          }
        }
        .playBack {
          background: url(../../../assets/images/forecasting/monitor/playback-btn.png)
            no-repeat center;
        }
        .playtype0 {
          background: url(../../../assets/images/forecasting/monitor/playtype0.png)
            no-repeat center;
          margin-bottom: 10px;
        }
        .playtype1 {
          background: url(../../../assets/images/forecasting/monitor/playtype1.png)
            no-repeat center;
          margin-bottom: 10px;
        }
        .addequip {
          background: url(../../../assets/images/forecasting/monitor/addequip.png)
            no-repeat center;
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>