<!--
 * @Author: zhangtq 2452618307@qq.com
 * @Date: 2024-11-15 14:26:52
 * @LastEditors: zhangtq 2452618307@qq.com
 * @LastEditTime: 2025-01-20 18:30:16
 * @FilePath: src/views/screen/components/video/components/VideoPlayBack.vue
 * @Description: 这是默认设置,可以在设置》工具》File Description中进行配置
 -->
<template>
  <div class="container">
    <div class="left">
      <div style="width: 100%;display: flex;flex-direction: row">
        <div class="sift-main">
          <el-date-picker
            v-model="timeRange"
            clearable
            type="datetimerange"
            :append-to-body="false"
            popper-class="sift-data"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>

        <el-button icon="el-icon-search" @click="searchTimeBtn" class="searchButton"></el-button>
      </div>
      <div style="width: 100%;display: flex;flex-direction: row;margin-top: 5px;" v-if="selectItem === 1">
        <el-input placeholder="请输入名称" v-model="keyWord" clearable @clear="resetBtn" v-no-whitespace>
        </el-input>
        <el-button icon="el-icon-search" @click="searchBtn" class="searchButton"></el-button>
      </div>
      <div class="bk-button-group"
           style="width: 100%;height: 40px;display: flex;flex-direction: row;border: 1px solid #1f3a6f;margin-top: 5px;"
      >
        <div :class="{ active: selectItem === 1 }" @click="changCount(1)"
             style="width: 50%;display: flex;justify-content: center;align-items: center;border-right:1px solid #1f3a6f;cursor:pointer;"
        >设备列表
        </div>
        <div :class="{ active: selectItem === 2 }" @click="changCount(2)"
             style="width: 50%;display: flex;justify-content: center;align-items: center;cursor:pointer;"
        >检索结果
        </div>
      </div>
      <div class="list" v-if="selectItem === 1">
        <div class="car-item" v-for="item in videoList" :key="item.puid" style="display: flex;flex-direction: row">
          <input class="checkbox" type="checkbox" :value="item" @change="selectListChange($event,item)"
                 v-model="selectList" :disabled="selectList.length >= 1 && !selectList.includes(item)"
          />
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
      <div class="list" v-if="selectItem === 2 ">
        <div class="car-item" v-for="item in searchList" :key="item.name" style="display: flex;flex-direction: row">
          <input class="checkbox" type="checkbox" :value="item" @change="selectSearchListChange($event,item)"
                 v-model="searchSelectList" :disabled="searchSelectList.length >= 1 && !searchSelectList.includes(item)"
          />
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="main-body">
        <div class="right">
          <div class="cell">
            <div class="cell-player">
              <div :class="cellClass(i)" v-for="i in cellCount" :key="i">
                <player
                  :title="i"
                  :id="`player${activePlayer}`"
                  @playerClick="handlePlayerClick"
                  @dblclick="toggleFullScreen()"
                  v-if="cellCount != 6"
                  :activePlayer="activePlayer"
                  :ref="`player${i}`"
                  v-on:startVideo="startVideo"
                  v-on:clearTime="clearTime"
                ></player>
                <player
                  :title="i"
                  :id="`player${activePlayer}`"
                  @playerClick="handlePlayerClick"
                  @dblclick="toggleFullScreen()"
                  v-if="cellCount == 6 && i != 2 && i != 3"
                  :activePlayer="activePlayer"
                  :ref="`player${i}`"
                ></player>
                <template v-if="cellCount == 6 && i == 2">
                  <div class="cell-player-6-2-cell">
                    <player
                      :title="i"
                      :id="`player${activePlayer}`"
                      @playerClick="handlePlayerClick"
                      @dblclick="toggleFullScreen()"
                      :activePlayer="activePlayer"
                      :ref="`player${i}`"
                    ></player>
                    <player
                      :title="i + 1"
                      :id="`player${activePlayer}`"
                      @playerClick="handlePlayerClick"
                      @dblclick="toggleFullScreen()"
                      :activePlayer="activePlayer"
                      :ref="`player${i + 1}`"
                    ></player>
                  </div>
                </template>
              </div>
            </div>
            <canvas id="canvas_video" style="display: none"></canvas>
            <canvas id="huaImg" style="display: none"></canvas>
          </div>
          <div class="right-lower"></div>
        </div>
      </div>
      <div style="width: 68%;height: 6vh;position: absolute;top: 91%;left: 30.5%;border: 1px solid #365998;border-radius: 5px">
        <VideoProgress ref="VideoProgress" v-on:seek="seek" style="margin-top: 0.6%;"/>
      </div>
    </div>

  </div>
</template>
<script>

import { parseTime } from '@/utils/bonus'
import { getBallVideoWeb, selectVideoList } from '@/api/screen/screen'
import player from '@/views/screen/components/video/components/Player.vue'
import screenfull from 'screenfull'
import { red } from 'chalk'
import AudioPlay from '@/views/screen/components/video/components/VideoProgress.vue'
import VideoProgress from '@/views/screen/components/video/components/VideoProgress.vue'

export default {
  name: 'VideoPlayBack',
  components: { VideoProgress, AudioPlay, player },
  props: {},
  data() {
    return {
      player: null,
      timeRange: [parseTime(new Date(), '{y}-{m}-{d} 00:00:00'), parseTime(new Date(), '{y}-{m}-{d} 23:59:59')],
      keyWord: '',
      videoList: [],
      searchList: [],
      searchSelectList: [],
      selectList: [],
      queryParams: {
        startTime: '',
        endTime: '',
        puid: ''
      },
      cellCount: 1,
      activeArray: [],
      activePlayer: 1,
      fullscreen: false,
      selectItem: 1,
      date: '2024-11-14',
      dateRange: ['2024-11-14 10:00:00', '2024-11-14 10:30:00'],
      qxToken: '',
      indexMap: {
        1: {},
        2: {},
        3: {},
        4: {}
      }
    }
  },
  mounted() {
    this.fetchDate()
  },
  methods: {
    red,
    changCount(count) {
      this.selectItem = count
      if (count === 1) {
        for (let i = 0; i < this.activeArray.length; i++) {
          const playerRef = `player${i + 1}`
          const playerInstance = this.$refs[playerRef]
          if (playerInstance && playerInstance[0]) {
            setTimeout(() => {
              playerInstance[0].closeVideo()
            }, 500)
          } else {
            console.error(`Player instance for ${playerRef} is not available.`)
          }
        }
        this.activeArray = []
        this.searchSelectList = []
        this.searchList = []
        this.selectList = []
        this.getVideoList()
      }
    },
    fetchDate() {
      this.getVideoList()
    },
    searchBtn() {
      const params = {
        name: this.keyWord
      }
      this.getVideoList(params)
    },
    resetBtn() {
      this.keyWord = ''
      this.searchBtn()
    },
    getVideoList(params) {
      selectVideoList(params).then(res => {
        this.videoList = res.rows
      })
    },
    searchTimeBtn() {
      if (!this.timeRange) {
        this.$message.error('请选择时间范围')
        return
      }
      let puid = this.selectList.map(item => item.puid).join(',')
      if (puid === '') {
        this.$message.error('请先选择需要查询的设备')
        return
      }
      this.queryParams.startTime = parseTime(this.timeRange[0], '{y}-{m}-{d} {h}:{i}:{s}')
      this.queryParams.endTime = parseTime(this.timeRange[1], '{y}-{m}-{d} {h}:{i}:{s}')
      this.queryParams.puid = puid
      this.getSearchList()
      this.selectItem = 2
    },
    getSearchList() {
      this.searchList = []
      getBallVideoWeb(this.queryParams).then(res => {
        this.searchList = res.rows
        console.log(this.searchList)
      })
    },
    QXPlayVideo(item) {
      for (let i = 1; i <= this.cellCount; i++) {
        if (!this.activeArray.includes(i)) {
          this.activePlayer = i
          this.indexMap[i] = item
          break
        }
      }
      console.log(this.indexMap)
      const playerRef = `player${this.activePlayer}`
      const playerInstance = this.$refs[playerRef]
      if (playerInstance && playerInstance[0]) {
        console.log("====================")
        this.activeArray.push(Number(this.activePlayer))
        playerInstance[0].openHistoryVideo(item)
      } else {
        console.error(`Player instance for ${playerRef} is not available.`)
      }
    },
    selectListChange(e, item) {
      if (!e.target.checked) {
        this.selectList = this.selectList.filter(i => i.puid !== item.puid)
        //去重
        this.selectList = Array.from(new Set(this.selectList))
      } else {
        this.selectList.push(item)
        this.selectList = Array.from(new Set(this.selectList))
      }

      console.log(this.selectList)
    },
    selectSearchListChange(e, item) {
      if (!e.target.checked) {
        this.searchSelectList = this.searchSelectList.filter(i => i.name !== item.name)
        //去重
        this.searchSelectList = Array.from(new Set(this.searchSelectList))
        //去除indeMap中item想同的数据
        for (let i = 1; i <= this.cellCount; i++) {
          if (this.indexMap[i] && this.indexMap[i].name === item.name) {
            console.log('删除', i)
            this.indexMap[i] = {}
            this.activeArray = this.activeArray.filter(a => a !== i)
            console.log(this.activeArray)
            const playerRef = `player${i}`
            console.log(playerRef)
            const playerInstance = this.$refs[playerRef]
            if (playerInstance && playerInstance[0]) {
              setTimeout(() => {
                playerInstance[0].closeVideo()
              }, 500)
            } else {
              console.error(`Player instance for ${playerRef} is not available.`)
            }
          }
        }
      } else {
        if (this.searchSelectList.length > this.cellCount) {
          this.$message.error('最多只能打开' + this.cellCount + '个视频！')
          return
        } else {
          this.searchSelectList.push(item)
          this.searchSelectList = Array.from(new Set(this.searchSelectList))
          item.currentTime = 0
          this.QXPlayVideo(item)
        }
      }
      console.log(this.searchSelectList)
    },
    handlePlayerClick(e) {
      this.activePlayer = e.title
    },
    //双击全屏
    toggleFullScreen() {
      const playerRef = `player${this.activePlayer}`
      const playerInstance = this.$refs[playerRef]
      if (playerInstance && playerInstance[0]) {
        if (screenfull.isEnabled) {
          if (screenfull.isFullscreen) {
            screenfull.exit()
          } else {
            screenfull.request(playerInstance[0].$el)
          }
        } else {
          this.$message.error('当前不支持全屏模式！！！')
        }
      } else {
        console.error(`Player instance for ${playerRef} is not available.`)
      }
    },
    closeAllVideo() {
      for (let i = 0; i < this.activeArray.length; i++) {
        const playerRef = `player${i + 1}`
        const playerInstance = this.$refs[playerRef]
        if (playerInstance && playerInstance[0]) {
          setTimeout(() => {
            playerInstance[0].closeVideo()
          }, 500)
        } else {
          console.error(`Player instance for ${playerRef} is not available.`)
        }
      }
      this.activeArray = []
      this.searchSelectList = []
      this.searchList = []
      this.selectList = []
      this.activePlayer = 1
      this.getVideoList()
    },
    startVideo(time) {
      this.$refs.VideoProgress.datas.playSecond = time
      this.$refs.VideoProgress.startVideo()
    },
    clearTime(title) {
      this.$refs.VideoProgress.datas.playSecond = 0
      this.$refs.VideoProgress.sliderTime = 0
      this.$refs.VideoProgress.stopVideo()
    },
    seek(time) {
      if (this.searchSelectList.length === 0) {
        this.$refs.VideoProgress.datas.playSecond = 0
        this.$refs.VideoProgress.sliderTime = 0
        this.$message.error('请先选择需要播放的视频')
        return
      }
      let item = this.searchSelectList[0]
      const playerRef = `player${this.activePlayer}`
      const playerInstance = this.$refs[playerRef]
      if (playerInstance && playerInstance[0]) {
        playerInstance[0].closeVideo()
        setTimeout(() => {
          item.currentTime = time
          this.QXPlayVideo(item)
        }, 500)
      } else {
        console.error(`Player instance for ${playerRef} is not available.`)
      }
    }
  },
  beforeDestroy() {

  },
  computed: {
    cellClass() {
      return function(index) {
        switch (this.cellCount) {
          case 1:
            return ['cell-player-1']
          case 4:
            return ['cell-player-4']
          case 6:
            if (index == 1) return ['cell-player-6-1']
            if (index == 2) return ['cell-player-6-2']
            if (index == 3) return ['cell-player-6-none']
            return ['cell-player-6']
          case 9:
            return ['cell-player-9']
          case 16:
            return ['cell-player-16']
          default:
            break
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  height: 100%;

  .left {
    width: 30%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 5px;

    .list {
      width: 100%;
      height: 65vh;
      overflow: auto;
      padding: 0 10px;
      margin-top: 5px;
      border: 1px solid #1f3a6f;
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* Internet Explorer 10+ */

      .car-item {
        width: 100%;
        height: 40px;
        display: flex;
        flex-direction: row;
        align-items: center;

        .checkbox {
          margin-right: 10px;
          width: 20px;
          height: 20px;
        }

        .name {
          color: white;
          font-size: 18px;
        }
      }
    }
  }

  .list::-webkit-scrollbar {
    display: none; /* Safari and Chrome */
  }

  .right {
    width: 70%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 2px;

    .video-playback {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;

      video {
        width: 100%;
        height: 100%;
      }
    }
  }
}

/**
  * 日历样式
 */
.sift-main {
  width: 100%;
  ::v-deep.el-range-input {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border: none;
    outline: none;
    display: inline-block;
    height: 100%;
    margin: 0;
    padding: 0;
    width: 39%;
    text-align: center;
    font-size: 14px;
    color: whitesmoke;
    background: rgb(5, 32, 75, 0.9) !important;
  }

  //年、月、日的日历面板样式
  ::v-deep.sift-data {
    background: rgb(5, 32, 75, 0.9);

    .available {
      color: #adadad !important;
    }

    //日历面板头部区域的样式
    .el-date-picker__header {
      background: unset;
    }

    .el-picker-panel__footer {
      background: unset;
    }

    .el-button--text {
      border-color: transparent;
      color: whitesmoke !important;
      background: transparent;
      padding-left: 0;
      padding-right: 0;
    }

    .el-button--default {
      background: unset;
    }

    .is-plain {
      border: none;
    }

    .el-button--mini {
      color: whitesmoke !important;
    }

    // 头部lanble的样式,如(2024年3月)
    .el-date-picker__header-label {
      color: #fff;
    }

    // 切换日历的按钮样式
    .el-picker-panel__icon-btn {
      color: #fff;
    }

    // 周一二三四五的样式
    .el-date-table th {
      color: #fff;
    }

    /* 切换到年时 */
    //除头部的日历模块区域样式  当type=date点击label的年或者月时的样式
    .el-year-table,
    .el-month-table {
      background: unset;
      //头部显示范围内的年的模块的样式
      .available {
        background: unset;
        // 里面的文字的样式
        a {
          color: #1890ff;
        }
      }

      //今年
      .today {
        a {
          color: #fff;
        }
      }

      //选中的年
      .current {
        background: unset;
        border-radius: unset;

        a {
          color: yellow;
        }
      }
    }

    /* 当type=date点击label 日 的样式 */
    // 非本月的区域样式
    .prev-month,
    .next-month {
      background: unset;
      color: #8c8c8c;
    }

    //当月的显示区域样式
    .available {
      // background: blue;
      color: whitesmoke;
    }

    .current {
      // color: green;
      // background: yellow;
      div {
        span {
          background: yellow;
          color: #000;
        }
      }
    }

    .today {
      div {
        span {
          background: #1890ff;
          color: #fff;
        }
      }
    }
  }
}


.main-body {
  width: 100%;
  height: 90%;
  display: flex;

  .right {
    width: 100%;
    height: 100%;

    .cell {
      margin-top: 0.5%;
      display: flex;
      flex-direction: column;
      height: 100%;
    }
  }
}

.bk-button-group .active {
  color: skyblue;
}

.cell-tool {
  height: 40px;
  line-height: 40px;
  margin-top: -1px;
  color: whitesmoke;
  margin-left: 18.5%;
}

.cell-player {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}

.cell-player-4 {
  width: 50%;
  height: 50% !important;
  box-sizing: border-box;
}

.cell-player-1 {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.cell-player-6-1 {
  width: 66.66%;
  height: 66.66% !important;
  box-sizing: border-box;
}

.cell-player-6-2 {
  width: 33.33%;
  height: 66.66% !important;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.cell-player-6-none {
  display: none;
}

.cell-player-6-2-cell {
  width: 100%;
  height: 50% !important;
  box-sizing: border-box;
}

.cell-player-6 {
  width: 33.33%;
  height: 33.33% !important;
  box-sizing: border-box;
}

.cell-player-9 {
  width: 33.33%;
  height: 33.33% !important;
  box-sizing: border-box;
}

.cell-player-16 {
  width: 25%;
  height: 25% !important;
  box-sizing: border-box;
}

.ant-select {
  width: 180px;
}

.bk-button-group .active {
  background: #2959a1;
  color: whitesmoke;
}
</style>
