<template>
  <div class="traffic">
    <!-- <Scales
      @plate-change="plateChange"
      v-model:sceneMode="sceneMode"
      v-model:useMaterial="commons.useMaterial"
      class="scale-ctrls"
    /> -->

    <FlowCarCtrl
      @car-filter="carFilter"
      @hole-type-change="handleHoleTypeChange"
      :infos="{ ...summary, direction: commons.direction, holeType: commons.holeType }"
    />

    <!-- 新洞 -->
    <XDirectionSectionRoad
      ref="xDirectionSectionRoadRef"
      v-bind="{
        ...commons,
        traffic: newTraffic,
        section: false,
        roadHeight: newTraffic?.road_section_w,
        act: commons.holeType === 'new'
      }"
      v-model:sectionAct="commons.sectionAct"
      @car-socket="carSocket"
      @section-change="sectionChange"
      @go-track="goTrack"
      @camera-change="(e) => emits('camera-change', e)"
      @update-space-axis="(scrollLeft) => updateSpaceAxis('new', scrollLeft)"
    />

    <!-- 老洞 -->
    <XDirectionSection
      ref="xDirectionSectionRef"
      v-bind="{
        ...commons,
        traffic,
        section: false,
        roadHeight: traffic?.road_section_w,
        act: commons.holeType === 'old'
      }"
      v-model:sectionAct="commons.sectionAct"
      @car-socket="carSocket"
      @section-change="sectionChange"
      @go-track="goTrack"
      @camera-change="(e) => emits('camera-change', e)"
      @update-space-axis="(scrollLeft) => updateSpaceAxis('old', scrollLeft)"
    />
    <!-- 空间轴 -->
    <div class="space-axis-block">
      <span class="title">
        <Icon icon="ep:info-filled" class="icon" :size="14" color="#0BC7FA" />
        拖动滑块查看隧道局部
      </span>
      <SpaceAxis
        ref="spaceAxisRoadRef"
        @space-axis-scroll="(scrollLeft) => spaceAxisScroll('new', scrollLeft)"
        v-bind="{
          traffic: newTraffic,
          direction: commons.direction,
          holeType: 'new',
          act: commons.holeType === 'new'
        }"
      />
      <SpaceAxis
        ref="spaceAxisRef"
        @space-axis-scroll="(scrollLeft) => spaceAxisScroll('old', scrollLeft)"
        v-bind="{
          traffic,
          direction: commons.direction,
          holeType: 'old',
          act: commons.holeType === 'old'
        }"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import FlowCarCtrl from '../FlowCarCtrls/index.vue'
import XDirectionSection from '@/views/traffic/roads/XDirectionSectionV2/index.vue'
import XDirectionSectionRoad from '@/views/traffic/roads/XDirectionSectionV2/Road.vue'

// import Scales from '@/views/traffic/components/Scales/index.vue'
import Cameras from '../components/Cameras/index.vue'
import TrafficEngine from '@/views/traffic/roads/Engine/index'
import SpaceAxis from '@/views/traffic/roads/XDirection/comps/SpaceAxis/index.vue'

import { ElMessage } from 'element-plus'

import { isSomeNone } from '@/utils/is'
import { useTunnelStoreWithOut } from '@/store/modules/tunnel'

const emits = defineEmits(['camera-change'])

const sceneMode = ref('section') // 模式

const route = useRoute()
const router = useRouter()
const tunnelStore = useTunnelStoreWithOut()

// 页面公共参数
const commons = defineModel<any>()
const freshKey = ref(true)
const traffic = ref(null)
const newTraffic = ref(null)

const summary = ref<any>({
  dangerousCount: 0,
  truckCount: 0,
  passengerCount: 0,
  sedanCount: 0,
  otherCount: 0,
  total: 0
})

// watch(
//   () => sceneMode.value,
//   (e) => {
//     if (e === 'panorama')
//       router.push({
//         path: 'home'
//       })
//   }
// )

// 汇总同步
const carSocket = (e) => {
  const { dangerousCount, truckCount, passengerCount, sedanCount, otherCount } = e

  summary.value = {
    ...summary.value,
    ...{
      dangerousCount,
      truckCount,
      passengerCount,
      sedanCount,
      otherCount,
      total: dangerousCount + dangerousCount + passengerCount + sedanCount + otherCount
    }
  }
}

// 车流筛选
const carFilter = ({ e }) => {
  commons.value.filterType = e?.type || null
}

// // 展示牌切换
// const plateChange = (e) => {
//   commons.value.plateType = e
// }

//  新/老洞切换
const handleHoleTypeChange = async () => {
  // commons.value.direction = 1 - commons.value.direction
  commons.value.holeType = commons.value.holeType === 'old' ? 'new' : 'old'

  summary.value.dangerousCount = 0
  summary.value.truckCount = 0
  summary.value.passengerCount = 0
  summary.value.sedanCount = 0
  summary.value.otherCount = 0
  summary.value.total = 0

  traffic.value?.cleanRoad()
  newTraffic.value?.cleanRoad()

  const configs = await getConfigs(commons.value.direction)

  if (configs) {
    if (commons.value.holeType === 'old') {
      traffic.value = new TrafficEngine(sceneMode.value, configs)
      traffic.value.startTraffic((res) => {
        carSocket(res)
      })
    } else {
      newTraffic.value = new TrafficEngine(sceneMode.value, configs)

      // 新洞还未对接，需后完善
      // newTraffic.value.startTraffic((res) => {
      //   carSocket(res)
      // })
      carSocket({
        dangerousCount: 0,
        truckCount: 0,
        passengerCount: 0,
        sedanCount: 0,
        otherCount: 0
      })
    }
  }
}

// 段面切换
const sectionChange = (x) => {
  commons.value.sectionAct = x
}

// 车辆追踪
const goTrack = ({ id, direction }) => {
  router.push({
    path: 'track',
    query: {
      id,
      direction,
      from: 'event'
    }
  })
}

// 获取隧道数据
const getConfigs = (direct) => {
  let wait = null
  let stop = null

  return new Promise((resolve) => {
    wait = setTimeout(() => {
      stop && stop()
      resolve(false)
    }, 5000)

    stop = watchEffect(() => {
      if (tunnelStore.init) {
        const { start, end, long } = [tunnelStore.getUpTunnel, tunnelStore.getDownTunnel][direct]
        stop && stop()
        resolve({
          direction: direct,
          start,
          end,
          miles: long,
          road_section_w: commons.value.holeType === 'old' ? 134 : 201,
          holeType: commons.value.holeType // 新老洞类型 old、new
        })
      }
    })
  })
}

const spaceAxisRef = ref<SpaceAxis>(null)
const spaceAxisRoadRef = ref<SpaceAxis>(null)
const xDirectionSectionRef = ref<XDirectionSection>(null)
const xDirectionSectionRoadRef = ref<XDirectionSectionRoad>(null)

// 空间轴滚动
const spaceAxisScroll = (holeType: string, scrollLeft: number) => {
  if (holeType === 'old') {
    xDirectionSectionRef.value.setRoadScroll(scrollLeft)
  } else {
    xDirectionSectionRoadRef.value.setRoadScroll(scrollLeft)
  }
}
// 更新空间轴
const updateSpaceAxis = (holeType: string, scrollLeft: number) => {
  if (holeType === 'old') {
    spaceAxisRef.value.updateThumb({ scrollLeft })
  } else {
    spaceAxisRoadRef.value.updateThumb({ scrollLeft })
  }
}

onBeforeMount(async () => {
  const { x, direction, holeType } = route.query

  if (isSomeNone([x, direction])) {
    return ElMessage.error('地址错误！')
  }

  commons.value.direction = +(direction as string)
  commons.value.holeType = holeType as string

  const configs = await getConfigs(+direction)

  if (configs) {
    traffic.value = new TrafficEngine(sceneMode.value, {
      ...configs,
      road_section_w: 134,
      holeType: 'old'
    })

    newTraffic.value = new TrafficEngine(sceneMode.value, {
      ...configs,
      road_section_w: 201,
      holeType: 'new'
    })
    
    if ( holeType === 'old' ) {
      traffic.value.startTraffic((res) => {
        carSocket(res)
      })
    } else {
  
      // 新洞还未对接，需后完善
      // newTraffic.value.startTraffic((res) => {
      // carSocket(res)
      // })
      carSocket({
        dangerousCount: 0,
        truckCount: 0,
        passengerCount: 0,
        sedanCount: 0,
        otherCount: 0
      })
    }
  }
})

onBeforeUnmount(() => {
  // 清理所有隧道实例的 WebSocket 连接
  [newTraffic.value, traffic.value].forEach(instance => {
    if (instance) {
      instance.cleanRoad() // 这会调用 socket.close()
    }
  })
})

</script>

<style lang="scss" scoped>
.traffic {
  position: relative;
  text-align: center;
  overflow: hidden;
  .scale-ctrls {
    position: absolute;
    right: 85px;
    top: 15px;
  }

  .space-axis-block {
    display: flex;
    flex-direction: column;
    // margin-top: 15px;
    .title {
      font-size: 14px;
      line-height: 22px;
      color: #fff;
      display: flex;
      align-items: center;
      margin-left: 17px;
      margin-bottom: 2px;
      .icon {
        margin-right: 5px;
      }
    }
  }
}
</style>
