
<template>
  <div id="camera-container">
    <div class="camera-list">
      <div class="devices">
        <div class="input">
          <el-input
            class="custom"
            v-model="deviceNo"
            @input="searchDevice"
            placeholder="设备名称/设备编号"
            suffix-icon="el-icon-search"
          ></el-input>
        </div>
        <div class="list">
          <div
            :class="[
              'area-device',
              activeDeviceId == device.id ? 'active' : '',
            ]"
            v-for="(device, dIndex) in deviceList"
            :key="dIndex"
            @click="getVideoData(device)"
          >
            <div class="device-name">
              <!-- <img
                :src="
                  device.is_online
                    ? './images/icon_jehzx@2x.png'
                    : './images/icon_jehlx@2x.png'
                "
                alt=""
              /> -->
              {{ device.device_name }}
            </div>
            <!-- <div :class="['status', device.is_online ? 'online' : 'offline']">
              {{ device.is_online ? "在线" : "离线" }}
            </div> -->
          </div>
        </div>

        <div class="operate-body">
          <div class="box-title">监控操作</div>
          <div class="operate-box">
            <el-form class="my-form" ref="form" label-position="top">
              <el-form-item label="分屏：">
                <el-select
                  class="w-100"
                  placeholder="所有"
                  v-model="cameraSplitNum"
                  @change="changeSplitNum"
                >
                  <el-option
                    v-for="(item, index) in cameraSplitNumList"
                    :label="item.txt"
                    :value="item.num"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="回放时间：">
                <el-date-picker
                  class="w-100"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  v-model="playBackTime.startTime"
                  placeholder="请选择开始时间"
                  @change="setPalyBackStartTime"
                ></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-date-picker
                  class="w-100"
                  type="datetime"
                  v-model="playBackTime.endTime"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择结束时间"
                  @change="setPalyBackEndTime"
                ></el-date-picker>
              </el-form-item>
              <div class="operte-btn">
                <div class="btn-item">
                  <el-button
                    type="warning"
                    icon="md-arrow-dropright-circle"
                    @click="getPlaybackUrl"
                    >回放</el-button
                  >
                </div>
                <div class="btn-item">
                  <el-button
                    class="blue-light-btn"
                    icon="ios-pause"
                    @click="playbackPause"
                    >暂停</el-button
                  >
                </div>
              </div>
              <div class="operte-btn">
                <div class="btn-item">
                  <el-button
                    class="blue-light-btn"
                    icon="md-skip-backward"
                    @click="playbackSlow"
                    >慢放</el-button
                  >
                </div>
                <div class="btn-item">
                  <el-button
                    class="blue-light-btn"
                    icon="ios-skip-forward"
                    @click="playbackFast"
                    >快进</el-button
                  >
                </div>
                <div class="btn-item">
                  <el-button
                    class="blue-light-btn"
                    icon="md-refresh"
                    @click="playbackResume"
                    >恢复</el-button
                  >
                </div>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <div class="videos" id="player"></div>
    </div>
  </div>
</template>
<script>
import {
  getDeviceListByProjectId,
  getDevicePlayAddress,
  getPlayBackUrl,
} from "@/api/video-supervisory.js";
import $ from "jquery";
export default {
  name: "",
  props: {
    projectId: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    return {
      deviceNo: "",
      deviceList: [],
      cameraSplitNum: 2,
      cameraSplitNumList: [
        {
          num: 1,
          txt: "1x1",
        },
        {
          num: 2,
          txt: "2x2",
        },
        {
          num: 3,
          txt: "3x3",
        },
        {
          num: 4,
          txt: "4x4",
        },
      ],
      playBackTime: {
        startTime: "",
        endTime: "",
      },
      selectedItem: {},
      player: null,
      activeCameraIndex: 0,
    };
  },
  mounted() {
    console.log(this.projectId);
    this.showWindow();
  },
  methods: {
    renderVideos() {
      this.player = new window.JSPlugin({
        szId: "player",
        szBasePath: "/js/",
        iMaxSplit: 4,
        iCurrentSplit: this.cameraSplitNum,
        openDebug: true,
        oStyle: {
          borderSelect: "#FFCC00",
        },
      });

      let _that = this;
      // 事件回调绑定
      this.player.JS_SetWindowControlCallback({
        windowEventSelect: function (iWndIndex) {
          //插件选中窗口回调
          console.log(iWndIndex);
          _that.activeCameraIndex = iWndIndex;
        },
        pluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
          //插件错误回调
          console.log("pluginError callback: ", iWndIndex, iErrorCode, oError);
        },
        windowEventOver: function (iWndIndex) {
          //鼠标移过回调
          //console.log(iWndIndex);
        },
        windowEventOut: function (iWndIndex) {
          //鼠标移出回调
          //console.log(iWndIndex);
        },
        windowEventUp: function (iWndIndex) {
          //鼠标mouseup事件回调
          //console.log(iWndIndex);
        },
        windowFullScreenChange: function (bFull) {
          //全屏切换回调
          if (bFull) {
            _that.isFullScreen = 1;
          } else {
            _that.isFullScreen = 0;
          }
        },
        firstFrameDisplay: function (iWndIndex, iWidth, iHeight) {
          //首帧显示回调

          _that.removeLoading("player-container-" + iWndIndex);
          console.log(
            "firstFrame loaded callback: ",
            iWndIndex,
            iWidth,
            iHeight
          );
        },
        performanceLack: function () {
          //性能不足回调
          console.log("performanceLack callback: ");
        },
      });

      this.deviceList.map((item, index) => {
        this.startPlay(index, item.playUrl);
      });
    },
    getVideoData(device) {
      this.selectedItem = { ...device };
      this.activeDeviceId = device.id;
      this.addLoading("player-container-" + this.activeCameraIndex);
      this.startPlay(this.activeCameraIndex, device.playUrl);
    },
    addLoading(elementId) {
      if ($("#" + elementId + " .loading-overlay").length > 0) {
        return false;
      }
      var str =
        '<div class="loading-overlay"><i class="el-icon-loading"></i></div>';
      $("#" + elementId).append(str);
    },
    removeLoading(elementId) {
      $("#" + elementId + " .loading-overlay").remove();
    },
    startPlay(index, playURL) {
      this.player.JS_Play(playURL, { playURL: playURL, mode: 0 }, index).then(
        () => {
          console.log("realplay success");
        },
        (e) => {
          console.error(e);
        }
      );
    },

    playbackStart(playURL, startTime, endTime) {
      //$('#player-container-'+this.activeCameraIndex).addClass('playback');
      this.player
        .JS_Play(
          playURL,
          { playURL: playURL, mode: 0 },
          this.activeCameraIndex,
          startTime,
          endTime
        )
        .then(
          () => {
            //this.playback.rate = 1
          },
          (e) => {
            console.error(e);
          }
        );
    },
    playbackFast() {
      this.player.JS_Fast().then(
        (rate) => {
          //this.playback.rate = rate
        },
        (e) => {
          console.error(e);
        }
      );
    },
    playbackSlow() {
      this.player.JS_Slow().then(
        (rate) => {
          //this.playback.rate = rate
        },
        (e) => {
          console.error(e);
        }
      );
    },
    /**
     * 暂停
     */
    playbackPause() {
      this.player.JS_Pause().then(
        () => {},
        (e) => {}
      );
    },
    /**
     * 恢复
     */
    playbackResume() {
      //$('#player-container-'+this.activeCameraIndex).removeClass('playback');
      //$('#player-container-'+this.activeCameraIndex).addClass('sub-wnd-'+this.cameraSplitNum);
      this.player.JS_Resume().then(
        () => {},
        (e) => {}
      );
    },

    setPalyBackStartTime(e) {
      this.playBackTime.startTime = this.formatDateTime(e);
    },
    setPalyBackEndTime(e) {
      this.playBackTime.endTime = this.formatDateTime(e);
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hour = date.getHours();
      const minute = date.getMinutes();
      const second = date.getSeconds();
      return `${year}-${this.pad(month)}-${this.pad(day)} ${this.pad(
        hour
      )}:${this.pad(minute)}:${this.pad(second)}`;
    },
    pad(num) {
      return num.toString().padStart(2, "0");
    },

    initCarmerPlay() {
      let len = this.deviceList.length;
      let maxLen = this.cameraSplitNum * this.cameraSplitNum;
      if (len > maxLen) {
        len = maxLen;
      }
      this.player.JS_StopRealPlayAll().then(
        () => {},
        (err) => {}
      );

      $(".sub-wnd").removeClass("sub-wnd-2");
      $(".sub-wnd").removeClass("sub-wnd-3");
      $(".sub-wnd").removeClass("sub-wnd-4");
      $(".sub-wnd").addClass("sub-wnd-" + this.cameraSplitNum);
      for (let i = 0; i < maxLen; i++) {
        if (this.deviceList.hasOwnProperty(i)) {
          this.getLiveAddress(this.deviceList[i], i);
        }
      }
    },
    getLiveAddress(item, index) {
      this.$forceUpdate();
      this.addLoading("player-container-" + index);

      getDevicePlayAddress(item.id).then((res) => {
        this.$forceUpdate();
        this.startPlay(index, res.data.url);
      });
    },

    changeSplitNum() {
      this.arrangeWindow();
    },
    arrangeWindow() {
      this.player.JS_ArrangeWindow(this.cameraSplitNum).then(
        () => {
          this.initCarmerPlay();
        },
        (e) => {
          console.error(e);
        }
      );
    },
    searchDevice: _.debounce(() => {
      this.showWindow();
    }, 1000),
    showWindow() {
      this.selectedItem = {};
      this.activeDeviceId = "";

      getDeviceListByProjectId(this.projectId, {
        keywords: this.deviceNo,
      }).then((res) => {
        this.deviceList = res.data;

        this.renderVideos();
      });
    },
    getPlaybackUrl() {
      if (!this.playBackTime.startTime) {
        this.$message({
          message: "请选择回放开始时间",
          type: "warning",
        });
        return false;
        // return this.$Message.error('请选择回放开始时间');
      }
      if (!this.playBackTime.endTime) {
        this.$message({
          message: "请选择回放结束时间",
          type: "warning",
        });
        return false;
        // return this.$Message.error('请选择回放结束时间');
      }
      this.addLoading("player-container-" + this.activeCameraIndex);

      let data = {
        begin_time: this.playBackTime.startTime,
        end_time: this.playBackTime.endTime,
      };
      getPlayBackUrl(
        this.selectedItem.id
          ? this.selectedItem.id
          : this.deviceList[this.activeCameraIndex].id,
        data
      ).then((res) => {
        this.playbackStart(
          res.data.url,
          res.data.start_time,
          res.data.end_time
        );
      });
    },
  },
};
</script>
<style lang="less" scoped>
#camera-container {
  padding-top: 10px;
  width: 100%;
  height: 100%;

  .title {
    position: relative;
    font-size: 0.18rem;
    color: #00ffff;
    background: linear-gradient(
      0deg,
      rgba(59, 99, 247, 0.8) 0%,
      rgba(59, 99, 247, 0.2) 100%
    );
    padding: 0.14rem 0.1rem;
    line-height: 0.22rem;

    img {
      width: 0.22rem;
      vertical-align: top;
    }

    i {
      float: right;
      cursor: pointer;
    }
  }

  .camera-list {
    height: 100%;
    display: flex;
    justify-content: space-between;

    .devices {
      width: 2.5rem;

      .list {
        height: calc(100% - 0.5rem - 3.6rem);
        background: rgba(41, 63, 151, 0.61);
        overflow-y: auto;

        .area-device {
          font-size: 0.14rem;
          color: #a4bce0;
          white-space: nowrap;
          line-height: 0.15rem;
          padding: 0.125rem 0.12rem;

          cursor: pointer;
          border-bottom: 0.01rem solid #2f46a3;
          display: flex;
          justify-content: space-between;

          .device-name {
            overflow: hidden;
            text-overflow: ellipsis;
          }

          &:hover {
            background: rgba(0, 255, 255, 0.4);
          }

          &.active {
            background: rgba(0, 255, 255, 0.4);
          }

          img {
            width: 0.15rem;
            vertical-align: top;
          }
        }

        .online {
          color: #00ffff;
        }

        .offline {
          color: #a4bce0;
        }
      }
    }

    .videos {
      width: calc(100% - 2.6rem) !important;
      height: 100% !important;
      padding: 0.1rem;
    }
  }
}

.input {
  background: #243889;
  padding: 0.05rem;
  font-size: 0;
}

.el-input.custom {
  font-size: 0.14rem;

  ::v-deep .el-input__inner {
    border-radius: 0.04rem;
    border: none;
    box-sizing: border-box;
    color: #fff;
    display: inline-block;
    height: 0.4rem;
    line-height: 0.4rem;
    outline: 0;
    padding: 0 0.15rem;
    background-color: rgba(0, 0, 0, 0.4);
  }

  ::v-deep .el-input__icon {
    line-height: 0.4rem;
  }
}

.info-body {
  width: 3.5rem;
  background: rgba(41, 63, 151, 0.7);
  border-radius: 0.06rem;
}

.amap-info-content {
  background: transparent;
  padding: 0;
  font-size: 0.14rem;
  color: #00ffff;
}

.info-body {
  display: flex;
  padding: 0.1rem;
  cursor: pointer;

  .project-name {
    padding: 0.1rem;
    border-left: 0.01rem solid rgba(255, 255, 255, 0.3);
  }

  .device-count {
    text-align: center;
    padding: 0 0.16rem;

    .label {
      color: #fff;
    }

    .value {
      color: #ffa200;
      font-size: 0.22rem;
    }
  }
}

::v-deep .loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);

  /* 半透明遮罩 */
  display: flex;
  justify-content: center;
  align-items: center;

  .el-icon-loading {
    color: #ffffff;
    font-size: 0.3rem;
  }
}

.operate-body {
  /* position: absolute; */
  font-size: 0.2rem;
  width: 100%;
  left: 0;
  bottom: 0;
  background: rgba(13, 100, 174, 0.15);
  padding: 0 0.1rem;
  border-width: 0 1px 1px 0;

  ::v-deep .el-form-item__label {
    color: #fff;
  }

  ::v-deep .el-form-item__label {
    padding: 0;
  }

  ::v-deep .el-date-editor.el-input,
  ::v-deep .el-date-editor.el-input__inner {
    width: 100%;
  }

  ::v-deep .el-form {
    ::v-deep .el-form-item__label {
      color: #fff;
    }
  }

  ::v-deep .el-date-editor {
    margin-bottom: 0.1rem;
  }

  ::v-deep .el-form-item {
    margin-bottom: 0;
  }

  ::v-deep .el-input__inner {
    background: rgba(50, 78, 134, 1);
    border: none;
    color: #fff;
    height: 0.28rem;
    line-height: 0.28rem;
  }
}

.box-title {
  height: 0.4rem;

  padding-left: 0.2rem;
  line-height: 0.4rem;
  font-weight: 500;
  font-size: 0.14rem;
  color: #ffffff;
  position: relative;

  &::before {
    width: 0.05rem;
    background: #f6b44d;
    content: "";
    position: absolute;
    left: 0.05rem;
    top: 0.05rem;
    bottom: 0.05rem;
  }
}

.operte-btn {
  display: flex;
  margin-bottom: 0.05rem;
}

.operte-btn .btn-item {
  flex: 1;
  margin: 0 0.02rem;
}

.operte-btn .btn-item button {
  padding: 0.1rem;
  width: 100%;
}

::v-deep .el-form {
  font-size: 0;
}

::v-deep .el-form-item__content {
  line-height: 0.4rem;
  margin-bottom: 0.04rem;
}

::v-deep .el-input__suffix {
  line-height: 0.4rem;
}

.operate-box {
  ::v-deep .el-input__icon {
    line-height: 0.28rem;
  }

  ::v-deep .el-button {
    line-height: 0.16rem;
  }
}

::v-deep .el-form-item__label {
  line-height: 0.4rem;
  font-size: 0.14rem;
}

.parent-wnd .sub-wnd.sub-wnd-2 {
  width: 50% !important;
}

.parent-wnd .sub-wnd.sub-wnd-3 {
  width: 33.33% !important;
}

.parent-wnd .sub-wnd.sub-wnd-4 {
  width: 25% !important;
}
</style>