<template>
  <div class="videos">

    <div class="image-block">

      <div class="header">
        <div class="title">
          <div class="icon"></div>
          <div class="text">卡口抓拍图片</div>
        </div>
      </div>

      <div class="content">

        <div class="x-box">

          <div class="image-group">
            <ImageSome empty-text="卡口图片加载中..." :images="viewImages" />
          </div>

          <div class="footer">
            <div class="text">{{ nowCar?.name || '' }}</div>
          </div>
          
          <div @click="openImage" class="full-screen"></div>

        </div>

      </div>

    </div>

    <div class="video-block">

      <div class="header">

        <div class="title">
          <div class="icon"></div>
          <div class="text">追踪车辆最近监控</div>
        </div>

        <div class="lock">
          车辆锁定：
          <el-switch
            inline-prompt
            active-text="开"
            inactive-text="关"
            :before-change="handleChange"
            v-model="trackers.cameraLock"
          />
        </div>

      </div>

      <div class="content">

        <div
          v-for="(item, x) in nowCameras"
          :key="item.id"
          :class="['x-video', { 'focus': focus === x }]"
        >

          <div class="tips">
            <Timer symbols="/" />
            <div class="text">全息断面 {{ item.section }}</div>
          </div>

          <VideoPlayer
            @click="() => videoFocus(x)"
            v-bind="{
              frameW: 583,
              frameH: 285,
              vcode: item.cameraIndexCode,
              pileNumber: item.pileNumber
            }"
          />

          <div v-if="!trackers.cameraLock" class="ctrls">
            <div @click="cameraChange(item, x, 'prev')" :class="['circle-btn', { disabled: !item.hasPrev }]">上一路</div>
            <div @click="cameraChange(item, x, 'next')" :class="['circle-btn', { disabled: !item.hasNext }]">下一路</div>
          </div>

          <div class="footer">
            <div class="text">{{ item.pileNumber }}</div>
          </div>

          <div @click="openVideo(item)" class="full-screen"></div>

        </div>

      </div>

    </div>

  </div>

  <ImageView ref="imageRef" />

</template>

<script lang="ts" setup>
import { getCurrentInstance } from 'vue'
import { CAR_TYPES } from '@/config/dict'
import { ElMessage } from 'element-plus'
import ImageView from '@/components/ImageView/index.vue'
import { useTunnelStoreWithOut } from '@/store/modules/tunnel'
import bus from '@/utils/eventBus'


import VideoPlayer from '@/views/components/VideoPlayer/index.vue'
import ImageSome from '@/components/ImageSome/index-cards.vue'

const BASE_PATH = import.meta.env.VITE_PORT_IMAGE_BASE

const videosRef = ref<any>(null)
const imageRef = ref<any>(null) // 图片预览弹窗实例
const tunnelStore = useTunnelStoreWithOut()
const nowCameras = ref<any[]>()
const trackers = defineModel<any>()
const nowCar = ref<any>(null)
const focus = ref<number | null>(null)

const app = getCurrentInstance()

const viewImages = computed(() => {
  if (nowCar.value) {
    return nowCar.value.images.map(item => BASE_PATH + item)
  } else {
    return []
  }
})

// 当前隧道
const tunnel = computed(() => {
  return [
    tunnelStore.getUpTunnel,
    tunnelStore.getDownTunnel
  ][trackers.value.direction]
})

// 获取所有摄像头
const allCameras = computed(() => {

  let arr = tunnel.value.cameras.map(item => {
    return { ...item }
  }).filter(item => item.cameraLable === 1)

  !trackers.value.direction && arr.reverse()
  
  const alls = arr.map((item, x) => {
    return {
      ...item, 
      realx: x,
      hasNext: x < arr.length - 1,
      hasPrev: x > 0
    }
  })

  return alls

})

// 追踪摄像头
const cameras = computed(() => {

  // 默认
  if (!nowCar.value) {
    return allCameras.value.slice(-2)
  }

  // 下行 正桩号序列
  if (trackers.value.direction) {

    const num = +nowCar.value.carMilestone

    // 初始位置
    if (num < allCameras.value[0].equipmentStation) {
      return allCameras.value.slice(0, 2)
    }

    // 末端位置
    if (num > allCameras.value.slice(-1)[0].equipmentStation) {
      return allCameras.value.slice(-2)
    }

    const x = allCameras.value.findIndex(item => item.equipmentStation > num)

    if (x + 2 > allCameras.value.length) {
      return allCameras.value.slice(-2)
    } else {
      return allCameras.value.slice(x, x + 2)
    }

  }
  
  // 上行 负桩号序列
  if (!trackers.value.direction) {

    const num = +nowCar.value.carMilestone

    // 初始位置
    if (num > allCameras.value[0].equipmentStation) {
      return allCameras.value.slice(0, 2)
    }

    // 末端位置
    if (num < allCameras.value.slice(-1)[0].equipmentStation) {
      return allCameras.value.slice(-2)
    }

    const x = allCameras.value.findIndex(item => item.equipmentStation < num)

    if (x + 2 > allCameras.value.length) {
      return allCameras.value.slice(-2)
    } else {
      return allCameras.value.slice(x, x + 2)
    }

  }

})

watch(
  () => cameras.value,
  e => {
    if (nowCameras.value?.length && (!trackers.value.tracking || !trackers.value.cameraLock)) return
    if (!e.some(item => !item)) {
      nowCameras.value = e
    }
  },
  {
    immediate: true
  }
)

watch(
  () => trackers.value,
  (e) => {
    if (e.car) {
      const { carId, vehicleType, carPlate, headImageUrl, plateImageUrl, carMilestone } = e.car.originalCar
      nowCar.value = {
        id: carId,
        name: CAR_TYPES[vehicleType].name + '(' + carPlate + ')',
        images: [headImageUrl, plateImageUrl],
        carMilestone
      }
    }
  },
  {
    deep: true
  }
)


// 摄像头切换
const cameraChange = (camera, x, type) => {

  if (!nowCameras.value) return
  if (type === 'prev') {
    nowCameras.value.splice(x, 1, allCameras.value[camera.realx - 1])
  } else {
    nowCameras.value.splice(x, 1, allCameras.value[camera.realx + 1])
  }

}

// 锁定控制
const handleChange = () => {
  if (!trackers.value.tracking) {
    ElMessage.warning('车辆已驶出隧道！')
    return false
  }

  return true
}

// 聚集视频画面
const videoFocus = (x) => {
  if (trackers.value.cameraLock) {
    return ElMessage.warning('车辆追踪中，不可进行此操作！')
  }
  focus.value = x
}

const openImage = () => {
 
  if (!nowCar.value) {
    return ElMessage.error('车辆信息有误！')
  }

  const { name } = nowCar.value
  imageRef.value.diaOpen(viewImages.value, name)
  
}

const openVideo = (item) => {
  app?.proxy?.$openVideo(item)
}

defineExpose({
  cameraSet (e) {
    if (focus.value === null || !nowCameras.value) return
    const nowCamera = allCameras.value.find(item => item.id === e.id)
    nowCameras.value.splice(focus.value, 1, nowCamera)
  }
})

const outSideClick = (e) => {

  const videos = document.querySelectorAll('.videos .x-video')
  const cameras = document.querySelectorAll('.x-camera')

  const inside = [...videos, ...cameras].some(item => {
    return item === e.target || item.contains(e.target)
  })

  if (!inside) {
    focus.value = null
  }

}

watch(
  () => nowCameras.value,
  (e) => {
    bus.emit('focus-camera', nowCameras.value.map(xcamera => {
      return xcamera.id
    }))
  },
  {
    deep: true,
    immediate: true
  }
)

onMounted(() => {
  document.addEventListener('click', outSideClick)
})

onUnmounted(() => {
  document.removeEventListener('click', outSideClick)
})

</script>

<style lang="scss" scoped>
$base-url: '@/assets/images/event/';
$base-common: '@/assets/images/common/';

.videos {
  margin: 32px 50px 50px;
  display: flex;
  justify-content: space-between;
  
  
  .header {
    display: flex;
    align-items: center;
    height: 30px;
    justify-content: space-between;
    .title {
      display: flex;
    }
    .lock {
      color: white;
      display: flex;
      align-items: center;
    }
    .icon {
      height: 30px;
      width: 30px;
      background: url($base-url + 'title.png') no-repeat;
      background-size: cover;
      margin-right: 2px;
    }
    .text {
      padding: 0 30px 0 12px;
      font-size: 16px;
      font-weight: 600;
      color: white;
      height: 30px;
      display: flex;
      align-items: center;
      border-radius: 30px 0 0 30px;
      background: linear-gradient(90deg, rgba(87, 115, 162, 0.81) 0%, rgba(87, 115, 162, 0) 99%);
    }
  }

  .full-screen {
    width: 20px;
    height: 20px;
    background: url($base-common + 'full-screen.png') no-repeat;
    background-size: cover;
    position: absolute;
    z-index: 3;
    bottom: 42px;
    right: 12px;
    cursor: pointer;
    transition-property: all;
    transition-duration: 0.2s;
    &:hover {
      box-shadow: 0 0 10px #a1a1a1;
    }
  }

  .image-block {
    width: 583px;
    .content {
      width: 583px;
      height: 317px;
      background: black;
      margin-top: 12px;
      position: relative;
      .image-group {
        width: 583px;
        height: 285px;
        // background: salmon;
      }
      .footer {
        height: 32px;
        width: 100%;
        position: absolute;
        left: 0;
        bottom: 0;
        z-index: 2;
        background: rgba(53, 102, 156, 0.7);
        padding: 0 12px;
        display: flex;
        box-sizing: border-box;
        align-items: center;
        .text {
          color: white;
          font-size: 12px;
        }
      }
    }
  }

  .video-block {
    .content {
      display: flex;
      .x-video {
        width: 583px;
        height: 317px;
        background: black;
        margin-top: 12px;
        position: relative;
        &.focus {
          transition-property: all;
          transition-duration: .3s;
          border: 1px solid #00ddff;
          box-shadow: 0 0 12px #00ddff;
          overflow: hidden;
          box-sizing: border-box;
        }
        &:first-child {
          margin-right: 15px;
        }
        .tips {
          position: absolute;
          left: 10px;
          top: 10px;
          z-index: 2;
          color: white;
          font-size: 14px;
          text-align: left;
        }
        .ctrls {
          display: flex;
          position: absolute;
          bottom: 42px;
          left: 12px;
          z-index: 3;
          .circle-btn {
            background: rgba(32, 58, 96, 0.5);
            border: 1px solid #00ddff;
            width: 66px;
            height: 24px;
            font-size: 14px;
            color: #00ddff;
            border-radius: 12px;
            text-align: center;
            line-height: 22px;
            box-sizing: border-box;
            margin-right: 14px;
            cursor: pointer;
            &.disabled {
              opacity: 0.6;
              cursor: not-allowed;
              pointer-events: none;
            }
          }
        }
        .footer {
          height: 32px;
          width: 100%;
          position: absolute;
          left: 0;
          bottom: 0;
          z-index: 2;
          background: rgba(53, 102, 156, 0.7);
          padding: 0 12px;
          display: flex;
          box-sizing: border-box;
          align-items: center;
          .text {
            color: white;
            font-size: 12px;
          }
        }
      }
    }
  }

  .combine {
    display: flex;
  }

  .x-video {
    height: 360px;
    position: relative;
 
  }
 
}
</style>

<style lang="scss">
.el-popover {
  &.car-select {
    background: rgba(53, 102, 156, 0.7);
    border: none;
    margin-left: -12px;
    border-radius: 0;
  }
}
</style>
