<template>
  <div class="g-p20 record">
    <div class="list g-p20" v-loading="loading">
      <el-tabs v-model="activeName" class="tabs" @tab-click="handleClick">
        <el-tab-pane label="实时监控" name="1">
          <div v-if="videoData.data.cameras" class="g-p20 g-fx-j">
            <div class="video" ref="myVideoRef" id="video-container"></div>
            <div class="right">
              <div
                class="video1"
                v-for="(item, index) in videoData.data.cameras"
                :key="item.channelNo"
                @click="onPitchVideo(index, item)"
                :class="{ 'video1--active': pitchVideo === index }"
              >
                <span v-show="pitchVideo === index">
                  <el-icon style="margin: 10px 10px 0 0; vertical-align: sub">
                    <Histogram /> </el-icon
                  >当前：</span
                >
                {{ item.channelName }}
              </div>

              <div>
                <div class="recent">近期监控</div>
                <el-divider />
              </div>
              <div class="video-list">
                <div class="video-list__item" v-for="item in threeVideo.arr" @click="toVideo(item)">
                  <div class="item__time">
                    {{ dayjs(item.startTime).format('HH:mm:ss') + '至' + dayjs(item.endTime).format('HH:mm:ss') }}
                  </div>
                  <div class="item__img" />
                  <el-icon class="item__paly">
                    <VideoPlay />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
          <div style="height: 500px; width: 500px" v-else>
            <el-empty :description="description" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="视频回放" name="2">
          <base-search
            isShowDate
            :isShowIpt="false"
            @update-dateValue="dateValue.arr = $event"
            @on-search="search"
            @reset="reset"
          ></base-search>
          <div class="playback">
            <div class="playback__item" v-for="(item, index) in videoHistoryData.data" @click="toVideo(item)">
              <div class="item__time">
                {{
                  dayjs(item.startTime).format('YYYY-MM-DD HH:mm:ss') + ' 至 ' + dayjs(item.endTime).format('HH:mm:ss')
                }}
              </div>
              <div class="item__img" />
              <el-icon class="item__paly">
                <VideoPlay />
              </el-icon>
            </div>
            <!-- <pro-pagination class="pagination" :pageObj="pageObj"></pro-pagination> -->
          </div>
          <el-empty v-if="videoHistoryData?.data?.length === 0" :description="description" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup name="视频监控">
  import { getDeviceMonitors, getDeviceVideos } from '@/api'
  import EZUIKit from 'ezuikit-js'
  import { ElMessage } from 'element-plus'
  import dayjs from 'dayjs'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const activeName = ref('1')
  const pitchVideo = ref(0)
  const myVideoRef = ref(null)
  const pageObj = reactive({
    SkipCount: 1,
    MaxResultCount: 10
  })
  let videoUrl = ref('')
  let channelNo = ref('')
  let loading = ref(false)
  let myVideo: any = ref(null)
  var isPlaying = ref(false)
  let dateValue = reactive({
    arr: []
  })
  const handleClick = (e: any) => {
    if (e.props.name === '1') {
      myVideo.value.resume()
    } else {
      myVideo.value.pause()
    }
  }
  const onPitchVideo = (e: number, el: any) => {
    videoUrl.value = el.url
    channelNo.value = el.channelNo
    vPlay()
    pitchVideo.value = e
  }
  let threeVideo: any = reactive({
    arr: []
  })

  onUnmounted(() => {
    if (myVideo.value) {
      myVideo.value.stop()
    }
  })

  onMounted(async () => {
    init()
    document.addEventListener('visibilitychange', (e) => {
      if (!myVideo.value && !videoUrl.value) return
      if (document.visibilityState === 'hidden') {
        // 离开
        myVideo.value.pause()
      } else {
        // 回来
        myVideo.value.resume()
      }
    })
  })
  const description = ref('暂无数据')
  const init = async () => {
    loading.value = true
    try {
      await videoData.getData()

      if (!videoData.data.token) return (description.value = '此设备未开通视频监控服务')
      if (videoData.data?.cameras?.length === 0) description.value = '录像机或摄像头未连接网络'
      channelNo.value = videoData.data.cameras[0].channelNo
      videoUrl.value = videoData.data.cameras[0].url
      myVideo.value = new EZUIKit.EZUIKitPlayer({
        id: 'video-container', // 视频容器ID
        width: 1272,
        height: 770,
        accessToken: videoData.data.token,
        url: videoData.data.cameras[0].url,
        template: 'security',
        audio: 0,
        footer: ['hd', 'fullScreen'],
        handleSuccess: () => {
          ElMessage.success('连接成功!')
          loading.value = false
          isPlaying.value = true
        },
        handleError: () => {
          ElMessage.error('连接失败')
          loading.value = false
          isPlaying.value = false
        }
      })
      await videoHistoryData.getData()
      threeVideo.arr = videoHistoryData.data.slice(0, 3)
    } finally {
      loading.value = false
    }
  }

  const videoData = useRequest(() => getDeviceMonitors({ deviceId: useQuery('id') }), false)
  const videoHistoryData = useRequest(
    () =>
      getDeviceVideos({
        deviceId: useQuery('id'),
        channelNo: channelNo.value,
        startTime: dateValue.arr.length > 0 ? dayjs(dateValue.arr?.[0]).format('x') : undefined,
        endTime: dateValue.arr.length > 0 ? dayjs(dateValue.arr?.[1]).format('x') : undefined
      }),
    false
  )
  // watchEffect(() => {
  //
  //   if (dateValue.arr.length > 0) {
  //     videoHistoryData.getDate()
  //   }
  // })
  const toVideo = (e: any) => {
    localStorage.setItem(
      'video',
      JSON.stringify({
        ...e,
        token: videoData.data.token
      })
    )
    window.open(`${location.origin}/#/view-video`, '_blank')
  }
  const search = (v: any) => {
    videoHistoryData.getData()
  }
  const reset = () => {
    dateValue.arr = []
    videoHistoryData.getData()
  }
  const vPlay = () => {
    try {
      // 切换播放地址场景（注意先执行stop方法停止上次取流）
      myVideo.value.stop().then(() => {
        myVideo.value.play({
          url: videoUrl.value
        })
      })
    } finally {
      loading.value = false
    }
  }
</script>

<style lang="less" scoped>
  .record {
    background: #c8cfdf;
    min-height: calc(100vh - 90px);
  }

  .list {
    min-height: calc(100vh - 160px);
    width: 100%;
    padding: 20px 40px;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 50px;
  }

  .video {
    width: 80%;
    padding-bottom: 45%;
    height: 0;
  }

  .right {
    margin-left: 20px;
    width: 18%;

    .video1 {
      width: 100%;
      cursor: pointer;
      min-width: 200px;
      height: 50px;
      font-size: 14px;
      line-height: 50px;
      text-align: center;
      border-radius: 10px;
      margin-bottom: 20px;
      background: #f4f6f9;
      color: #333;
      font-weight: bold;

      &--active {
        color: #5f7cd6;
        font-weight: 400;
        background: #cfd9fa;
        border: 1px solid #5f7cd6;
      }
    }

    .recent {
      font-size: 16px;
      font-weight: bold;
      margin-top: 40px;
      margin-left: 20px;
    }

    .video-list {
      display: flex;
      flex-direction: column;
      align-items: center;

      &__item {
        width: 200px;
        height: 120px;
        background: rgba(214, 220, 234, 1);
        border-radius: 5px;
        margin: 25px 0;
        position: relative;
        transition: 0.3s;
        cursor: pointer;

        &:hover {
          transform: scale(1.1);
        }
      }

      .item__time {
        position: absolute;
        bottom: -20px;
        font-size: 12px;
        left: 30px;

        &::after {
          content: '';
          width: 8px;
          height: 8px;
          background: #3ec962;
          border-radius: 50%;
          position: absolute;
          left: -15px;
          bottom: 4px;
        }
      }

      .item__img {
        width: 62px;
        height: 69px;
        background-image: url('../../../assets/img/video.png');
        background-size: cover;
        opacity: 0.2;
        position: absolute;
        bottom: -2px;
        right: 2px;
      }

      .item__paly {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 32px;
        color: #fff;
      }
    }
  }

  .el-empty {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .playback {
    position: relative;
    min-height: 300px;
    padding-bottom: 80px;
    display: flex;
    width: 100%;
    flex-wrap: wrap;

    &__item {
      width: calc(17% - 26px);
      min-width: 200px;
      aspect-ratio: 16 / 9;
      margin: 0 10px;
      margin-bottom: 50px;
      position: relative;
      border-radius: 5px;
      background: #d6dcea;
      transition: 0.3s;
      cursor: pointer;

      &:hover {
        transform: scale(1.05);
      }

      .item__time {
        position: absolute;
        bottom: -20px;
        font-size: 12px;
        left: 30px;

        &::after {
          content: '';
          width: 8px;
          height: 8px;
          background: #3ec962;
          border-radius: 50%;
          position: absolute;
          left: -15px;
          bottom: 4px;
        }
      }

      .item__img {
        position: absolute;
        width: 62px;
        height: 69px;
        background-image: url('../../../assets/img/video.png');
        background-size: cover;
        opacity: 0.2;
        bottom: -2px;
        right: 10px;
      }

      .item__paly {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 36px;
        color: #fff;
      }
    }

    .pagination {
      position: absolute;
      bottom: 20px;
      right: 20px;
    }
  }

  :deep(.tabs) {
    .el-tabs__item {
      color: #333;
      font-weight: bold;
    }

    .el-tabs__active-bar {
      width: 70px;
      height: 5px;
      background: #2dcadc;
      border-radius: 2px;
      bottom: -11px;
    }

    .el-tabs__nav-scroll {
      height: 50px;
    }
  }
</style>
