<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="left-tree">
        <div class="search-wrapper">
          <el-input
            v-model="searchSite"
            @change="handleSearchSite"
            placeholder="请输入视频巡查监控点名称"
            prefix-icon="el-icon-search"
            clearable
          ></el-input>
          <!-- <el-button
            icon="el-icon-check"
            circle
            type="success"
            title="已巡检"
          ></el-button>
          <el-button icon="el-icon-close" circle title="未巡检"></el-button> -->
        </div>
        <div class="video-site-table" v-if="treeData.length">
          <div
            v-for="(site, index) in treeData"
            :key="site.id"
            class="site-item"
          >
            <img
              v-if="site.status === 1"
              src="@/assets/img/patrolAndRescue/videoInspection/video-site-online.png"
              class="tree-node-icon"
            />
            <img
              v-else
              src="@/assets/img/patrolAndRescue/videoInspection/video-site-offline.png"
              class="tree-node-icon"
            />
            <span class="site-name ellipsis" :title="site.name">
              <span>{{ index + 1 }}、</span>{{ site.name }}</span
            >
            <i v-if="site.checked === 1" class="el-icon-check"></i>
          </div>
        </div>
        <div class="video-site-table" v-else>
          <div class="empty-item">暂无视频巡查监控点</div>
        </div>
      </div>
      <div class="right-table">
        <div class="player-wrapper">
          <el-carousel
            v-if="initVideo"
            :loop="true"
            :autoplay="false"
            height="100%"
            arrow="never"
            ref="carousel"
            indicator-position="none"
            @change="changePlayer"
          >
            <el-carousel-item
              v-for="item in videoWrapper"
              :key="item + videoWrapper"
            >
              <video-player
                @ready="handleReady"
                :split="split"
                :index="item"
                :ref="`videoPlayer${item}`"
              ></video-player>
            </el-carousel-item>
          </el-carousel>
          <!-- <div class="overlay">
            <div
              v-for="splitItem in split * split"
              :key="splitItem"
              class="overlay-item"
              :style="`width: ${split === 3 ? '33.33%' : '50%'};height: ${
                split === 3 ? '33.33%' : '50%'
              };`"
            >
              <div class="overlay-btn-wrapper">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-s-promotion"
                  @click="handleReport(splitItem)"
                  >上报</el-button
                >
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-scissors"
                  @click="handleCut(splitItem)"
                >
                  截图</el-button
                >
              </div>
            </div>
          </div> -->
        </div>
        <div class="controler-wrapper">
          <div class="controler-left">
            <div>
              间隔时间
              <el-tooltip
                class="item"
                effect="dark"
                content="最小间隔时间10秒"
                placement="top"
              >
                <i class="el-icon-info"></i> </el-tooltip
              >：
              <el-input-number
                :min="10"
                :controls="false"
                style="width: 80px"
                v-model="intervalTime"
                @change="changeInterval"
              >
              </el-input-number>
              秒
            </div>
            <div>
              分屏：
              <el-select
                style="width: 80px"
                v-model="split"
                @change="handleArrangeWindow"
              >
                <el-option
                  v-for="item in splitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div>
            <div>
              <el-button
                size="small"
                type="primary"
                @click="handlePlay"
                :title="playing ? '暂停轮播' : '开始轮播'"
                :icon="playing ? 'el-icon-video-pause' : 'el-icon-video-play'"
              ></el-button>
              <el-button
                title="上一屏"
                size="small"
                type="primary"
                icon="el-icon-d-arrow-left"
                @click="handleChangePage('prev')"
              ></el-button>
              <el-button
                title="下一屏"
                size="small"
                type="primary"
                icon="el-icon-d-arrow-right"
                @click="handleChangePage('next')"
              ></el-button>
              <el-button
                size="small"
                title="巡检完成"
                @click="handleFinish"
                type="primary"
                icon="el-icon-circle-check"
              >
              </el-button>
              <el-button
                size="small"
                type="warning"
                icon="el-icon-s-opportunity"
                @click="handleReport"
                >异常上报
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <report-dialog
      ref="reportDialog"
      :isShow.sync="reportDialog"
      :videoList="treeData"
    ></report-dialog>
  </div>
</template>

<script>
import {refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import {
  taskDetail,
  previewURLs,
  saveResultBatch,
  taskUpdate,
} from '@/api/patrolAndRescue/videoPatrol/videoInspection'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import VideoPlayer from '@/components/VideoPlayer/index.vue'
import treeSide from '@/components/treeSide/index.vue'
import ReportDialog from './components/ReportDialog/index'

export default {
  name: 'TablePage',
  components: {
    treeSide,
    VideoPlayer,
    ReportDialog,
  },
  data() {
    return {
      pubSub: null,
      originTreeData: [],
      searchSite: '',
      treeData: [],
      tempData: [], // 区别已检查和未检查的临时数据
      treeLoading: false,
      treeItem: {}, // 树形节点选中对象
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      initVideo: false,
      intervalTime: 10,
      split: 3,
      playing: false,
      splitOptions: [
        {
          label: '3X3',
          value: 3,
        },
        {
          label: '2X2',
          value: 2,
        },
      ],
      videoWrapper: 0,
      readyCount: 0,
      currentPlayer: 1,
      timer: null,
      reportDialog: false,
      taskData: null,
      urlList: [], // 播放地址
      tempRankList: [], // 基于上次查看结果重组的播放顺序
      querys: [], //  每屏请求参数
      querysCount: 1, // 请求次数
      querysCountTotal: 1, // 总请求次数
    }
  },
  created() {},
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal !== this.$options.name) {
          this.clear()
        }
      },
    },
  },
  mounted() {
    this.pubSub = PubSub.subscribe('VideoPage', (_, data) => {
      this.changeTaskStatus(data.taskData, 1)
      this.loadTree(data?.taskData || {})
    })
  },
  methods: {
    dictionaryEscape,

    handleFinish() {
      this.changeTaskStatus(this.taskData, 2)
    },

    async changeTaskStatus(data, status) {
      const {taskStatus, ...task} = data
      if (
        (status === 1 && taskStatus === 0) ||
        (status === 2 && taskStatus === 1)
      ) {
        const {state, message} = await taskUpdate({
          taskStatus: status,
          ...task,
        })
        if (state && status === 2) {
          this.$message.success('任务已完成')
        } else if (!state && status === 2) {
          this.$message.warning(message || '任务更新失败')
        }
      }
    },

    preloadVideoUrl() {
      if (
        this.taskData.rank === 0 ||
        this.taskData.rank === this.treeData.length - 1
      ) {
        this.tempData = [...this.treeData]
      } else {
        const tempBefore = this.treeData.slice(this.taskData.rank + 1)
        const tempAfter = this.treeData.slice(0, this.taskData.rank + 1)
        this.tempData = [...tempBefore, ...tempAfter]
      }
      this.getURlQuerys(this.split)
      this.querysCount = 1
      this.getUrl()
    },

    getURlQuerys(split) {
      let splitNum = split * split
      this.querys = this.chunkArray(this.tempData, splitNum)
      this.querysCountTotal = Math.ceil(this.querys.length / 10)
      console.log(this.querys, this.querysCountTotal, 'this.querys')
    },

    // 分屏大于1  拆分数据分离每屏请求数量
    chunkArray(array, chunkSize) {
      if (array.length === 0) {
        return []
      }
      const chunks = []
      let i = 0
      while (i < array.length) {
        chunks.push(array.slice(i, i + chunkSize))
        i += chunkSize
      }
      return chunks
    },

    getUrl() {
      let tempRequestData = []
      if (this.videoWrapper > 10) {
        tempRequestData = this.querys.slice(
          this.querysCount > 1 ? this.querysCount * 10 - 9 : 0,
          this.querysCount * 10
        )
        this.querysCount++
      } else {
        tempRequestData = this.querys
      }
      tempRequestData.forEach(async (siteArr, arrIndex) => {
        try {
          let ids = {
            monitorPointInfoIds: siteArr.map((i) => i.cameraIndexCode),
          }
          const {value} = await previewURLs(ids)
          if (value && value.length) {
            let urls = []
            value.forEach((item, i) => {
              urls.push(item.url)
              this.$refs[`videoPlayer${arrIndex + 1}`][0].realplay(item.url, i)
            })
            if (this.currentPlayer === 1) {
              this.tagVideo()
            }
          }
        } catch {
          console.log('请求失败')
        }
      })
    },

    // 视频播放器全部准备状态更新
    handleReady() {
      this.readyCount += 1
      if (this.readyCount === this.videoWrapper) {
        this.playerReady = true

        // 不自动播放，为获取资源保留时间间隔
        // this.startPlay()
        // this.playing = true
      }
    },
    // 计算屏幕数量
    countWrapper() {
      this.videoWrapper = Math.ceil(
        this.treeData.length / (this.split * this.split)
      )
      this.currentPlayer = 1
      this.initVideo = true
    },

    // 开启、暂停轮播
    handlePlay() {
      this.playing = !this.playing
      if (this.playing) {
        this.startPlay()
      } else {
        if (this.timer) {
          clearInterval(this.timer)
        }
      }
    },

    playerStart() {
      if (this.split > 1) {
        this.$nextTick(() => {
          this.urlList.forEach((urlArr, playerindex) => {
            urlArr.forEach((url, urlindex) => {
              if (
                this.$refs[`videoPlayer${playerindex + 1}`][0] &&
                this.$refs[`videoPlayer${playerindex + 1}`][0].realplay
              ) {
                this.$refs[`videoPlayer${playerindex + 1}`][0].realplay(
                  url,
                  urlindex
                )
              }
            })
          })
        })
      }
    },

    handleArrangeWindow(val) {
      this.split = val
      this.initVideo = false
      this.countWrapper()
      this.$nextTick(() => {
        console.log(this.videoWrapper, this.$refs)
        for (let i = 1; i < this.videoWrapper; i++) {
          if (
            this.$refs[`videoPlayer${i}`] &&
            this.$refs[`videoPlayer${i}`].arrangeWindow
          ) {
            this.$refs[`videoPlayer${i}`].arrangeWindow(val)
          }
        }
        this.startPlay()
      })
      //   this.$message.success('分屏设置将刷新页面，请耐心等待')
      //   this.$router.push({})
    },

    stopAll() {
      this.$nextTick(() => {
        for (let i = 1; i < this.videoWrapper; i++) {
          if (
            this.$refs[`videoPlayer${i}`] &&
            this.$refs[`videoPlayer${i}`].stopAllPlay
          ) {
            this.$refs[`videoPlayer${i}`].stopAllPlay()
          }
        }
      })
    },
    changeInterval() {
      this.startPlay()
      this.$message.success('设置时间间隔成功')
    },
    // 开始轮询
    startPlay() {
      this.timer && clearInterval(this.timer)
      this.timer = null
      this.timer = setInterval(() => {
        this.setCurrentPlayer('next')
        this.$refs?.carousel?.next()
        this.tagVideo()
      }, this.intervalTime * 1000)
    },

    // 设置当前播放序号
    setCurrentPlayer(type) {
      if (type === 'prev') {
        // 当前播放屏的序号
        this.currentPlayer === 1
          ? (this.currentPlayer = this.videoWrapper)
          : this.currentPlayer--
      } else {
        this.currentPlayer < this.videoWrapper
          ? this.currentPlayer++
          : (this.currentPlayer = 1)
        if (
          this.currentPlayer % 5 &&
          this.querysCount < this.querysCountTotal
        ) {
          this.querysCount = this.currentPlayer / 5
          this.getUrl()
        }
      }

      console.log(
        '当前播放屏的序号',
        this.currentPlayer,
        '/',
        this.videoWrapper
      )
    },
    // 已经看过的tag为已巡检
    tagVideo() {
      this.originTreeData.forEach((item, index) => {
        const minIndex =
          this.currentPlayer === 1
            ? 0
            : this.currentPlayer * this.split * this.split
        const maxIndex = this.currentPlayer * this.split * this.split - 1

        const indexRange = Array.from(
          {length: maxIndex - minIndex + 1},
          (_, i) => minIndex + i
        )
        if (indexRange.includes(index)) {
          item.checked = 1
        }
      })
      if (this.searchSite) {
        this.treeData = this.originTreeData.filter((item) => {
          return item.name.includes(this.searchSite)
        })
      } else {
        this.treeData = [...this.originTreeData]
      }
    },

    // 切换屏幕时默认上报正常
    changePlayer(newIndex, oldIndex) {
      this.uploadStatus(oldIndex) // 默认上报正常
    },

    async uploadStatus(oldIndex) {
      if (this.split > 1) {
        try {
          let target = this.querys[oldIndex]
          let query = []
          target.forEach((item) => {
            query.push({
              inspecetStatus: 0, //0 正常
              rank: item.rank,
              videoId: item.id,
              taskId: this.taskData.id,
            })
          })

          // const data = await saveResultBatch()
        } catch {}
      } else {
      }
    },

    // 切换
    handleChangePage(type) {
      this.$refs.carousel[type]()
      this.setCurrentPlayer(type)
      this.tagVideo()
    },

    handleReport(index) {
      if (this.playing) this.handlePlay()
      console.log(index)
      this.reportDialog = true
    },

    handleCut() {
      if (this.playing) this.handlePlay()
      console.log(index)
    },

    handleSearchSite(val) {
      if (val) {
        this.treeData = this.originTreeData.filter((item) => {
          return item.name.includes(val)
        })
      } else {
        this.treeData = [...this.originTreeData]
      }
    },

    //获取数据
    async loadTree(taskData) {
      if (!taskData.id) return
      try {
        this.treeLoading = true
        const data = await taskDetail(taskData.id)
        this.taskData = data
        this.treeData = data.taskVideo || []
        this.originTreeData = [...this.treeData]
        this.treeLoading = false
        this.countWrapper()
        this.preloadVideoUrl()
      } catch (err) {
        console.log(err)
      }
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      this.clear()
      this.$emit(
        'changePage',
        pageName,
        (_) => {
          PubSub.publish(pageName, row)
        },
        row.id ? '编辑' : '添加'
      )
    },
    clear() {
      this.initVideo = false
      this.playing = false
      this.readyCount = 0
      this.timer && clearInterval(this.timer)
      this.timer = null
      this.taskData = null
      this.stopAll()
      this.currentPlayer = 1
    },
  },
  beforeDestroy() {
    this.clear()
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  },
}
</script>

<style lang="scss" scoped>
.table-page {
    .basis {
        min-width: 400px !important;
    }
    .left-tree{
        width: 360px!important;
        padding: 16px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
    }
    .right-table{
        margin: 16px;
        
    }
    .video-site-table{
        margin-top: 16px;
    }
    .player-wrapper{
        width: 100%;
        height: calc(100% - 60px);
        background-color: rgb(0, 0,0);
        position: relative;
        .el-carousel{
            width: 100%;
            height: 100%;
        }
    }
    .controler-wrapper{
        height: 60px;
        width: 100%;
        padding: 0 20px;
        box-sizing: border-box;
        background-color: rgb(17, 64, 102);
        border-radius:0 0 8px 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20px;
        .controler-left{
            display: flex;
            gap: 26px;
        }
        div {
            font-size: 15px;
        }
        
        ::v-deep .el-button{
            i{
                font-size: 18px!important;
            }
        }
        
    }
    ::v-deep .tree-node-icon {
        width: 15px;
        height: 15px;
    }

    .el-icon-info{
        color: $--color-warning;
    }
    .el-icon-check{
        color: $--color-success;
    }
    .search-wrapper{
        display: flex;
        .el-input{
            flex: 1;
            margin-right: 10px;
        }
        .el-button{
            font-size: 16px;
        }
    }
    .video-site-table{
        flex: 1;
        overflow-y: auto;
        overflow-x: hidden;
        .site-item{
            padding: 4px 6px;
            margin: 4px 0;
            display: flex;
            align-items: center;
            font-size: 16px;
            gap: 6px;
            background: rgba(81, 176, 240, 0.05);
        }
        .site-name{
            flex: 1;
            overflow: hidden;
            font-size: 14px;
        }
        .empty-item{
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #999;
        }
    }
    .overlay{
        width: 100%!important;
        height: 100%!important;
        position: absolute;
        left: 0;
        top: 0;
        display:flex;
        flex-wrap: wrap;
        pointer-events: none;
    }
    .overlay-item{
        box-sizing: border-box;
        pointer-events: none;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        .overlay-btn-wrapper{
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 40px;
            z-index: 5;
            pointer-events: all;
            display: flex;
            justify-content: center;
            align-items: center;
            .el-button{
                display: none;
            }
        }
    }
    .overlay-btn-wrapper:hover{
        background-color: rgba(81, 176, 240, 0.8);
        .el-button{
            display: block;
        }
    }
    
}
</style>
