<template>
  <div class="traffic">
    <FlowCarCtrl
      @car-filter="carFilter"
      :holeTypeName="holeDirection ? '老洞' : '新洞'"
      :infos="holeDirection ? oldSummary : newSummary"
    />

    <div class="hole-select">
      <div class="name">聚焦方向：</div>
      <el-select v-model="holeDirection" popper-class="define-select" :teleported="false">
        <el-option
          v-for="{ name, inkey } in holeTypes"
          :key="inkey"
          v-bind="{ label: name, value: inkey }"
        />
      </el-select>
    </div>

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

    <!-- 新洞监控 -->
    <div class="cameras-block">
      <flow-chart
        ref="flowChartRef1"
        v-if="showFlow"
        :direction="holeDirection"
        :holeType="holeDirection ? 'old' : 'new'"
      />
      <cameras
        ref="cameraRef1"
        v-else
        :holeType="holeDirection ? 'old' : 'new'"
        :direction="holeDirection"
      />
    </div>

    <!-- 左洞 -->
    <template v-if="!holeDirection">
      <Road
        @go-section="goSection"
        @go-track="goTrack"
        @car-socket="(e) => carSocket(e, 'new')"
        v-bind="{
          ...configs,
          direction: holeDirection,
          traffic: newTraffic,
          act: true,
          section: false,
          roadHeight: newTraffic?.road_w,
          isNeedLeftCamera: true
        }"
      />

      <Facilities v-bind="{ traffic: newTraffic, direction: holeDirection, act: true }" />

      <XDirection
        @go-section="goSection"
        @go-track="goTrack"
        @car-socket="(e) => carSocket(e, 'old')"
        v-bind="{
          ...configs,
          direction: holeDirection,
          traffic: oldTraffic,
          act: true,
          section: false,
          roadHeight: oldTraffic?.road_w,
          isNeedLeftCamera: true
        }"
      />
    </template>

    <Facilities v-bind="{ traffic: oldTraffic, direction: holeDirection, act: true }" />

    <!-- 右洞 -->
    <template v-if="holeDirection">
      <XDirection
        @go-section="goSection"
        @go-track="goTrack"
        @car-socket="(e) => carSocket(e, 'old')"
        v-bind="{
          ...configs,
          isDownCtrls: true,
          direction: holeDirection,
          traffic: oldTraffic,
          act: true,
          section: false,
          roadHeight: oldTraffic?.road_w,
          isNeedLeftCamera: true
        }"
      />

      <Facilities v-bind="{ traffic: newTraffic, direction: holeDirection, act: true }" />

      <Road
        @go-section="goSection"
        @go-track="goTrack"
        @car-socket="(e) => carSocket(e, 'new')"
        v-bind="{
          ...configs,
          isDownCtrls: true,
          direction: holeDirection,
          traffic: newTraffic,
          act: true,
          roadHeight: newTraffic?.road_w,
          isNeedLeftCamera: true
        }"
      />
    </template>

    <div class="cameras-block">
      <flow-chart
        ref="flowChartRef2"
        v-if="showFlow"
        :direction="holeDirection"
        :holeType="!holeDirection ? 'old' : 'new'"
      />
      <cameras
        ref="cameraRef2"
        v-else
        :holeType="!holeDirection ? 'old' : 'new'"
        :direction="holeDirection"
      />
    </div>

    <FlowCarCtrl
      @car-filter="carFilter"
      :holeTypeName="!holeDirection ? '老洞' : '新洞'"
      :infos="!holeDirection ? oldSummary : newSummary"
    />

    <!-- 空间轴 -->
    <div class="space-axis-block">
      <span class="title">
        <Icon icon="ep:info-filled" class="icon" :size="14" color="#0BC7FA" />
        点击空间轴上对应位置放大隧道
      </span>
      <SpaceAxis
        ref="spaceAxisHNRef"
        @drag-end="(scrollLeft) => spaceAxisScroll(scrollLeft, holeDirection ? 'old' : 'new')"
        v-bind="{
          traffic: newTraffic,
          direction: holeDirection,
          holeType: holeDirection ? 'old' : 'new'
        }"
      />
      <SpaceAxis
        ref="spaceAxisHORef"
        @drag-end="(scrollLeft) => spaceAxisScroll(scrollLeft, !holeDirection ? 'old' : 'new')"
        v-bind="{
          traffic: oldTraffic,
          direction: holeDirection,
          holeType: !holeDirection ? 'old' : 'new'
        }"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useTunnelStoreWithOut } from '@/store/modules/tunnel'
import { awaitGet } from '@/utils/tunnel'
import TrafficEngine from '@/views/traffic/roads/Engine/index'

import XDirection from '@/views/traffic/roads/XDirection/index.vue'
import FlowCarCtrl from '../FlowCarCtrls/index.vue'
import Facilities from '@/views/traffic/roads/Facilities/index.vue'
// import Scales from '@/views/traffic/components/Scales/index.vue'
import SpaceAxis from '@/views/traffic/roads/XDirection/comps/SpaceAxis/index.vue'

import Road from '@/views/traffic/roads/XDirection/Road.vue'

import Cameras from '../Cameras/index.vue'
import FlowChart from '../FlowChart/index.vue'

import { ASYNC_DIRECTIONS } from '@/config/dict'

interface TrafficSummary<T = number> {
  name: string
  direction: T
  dangerousCount: T
  truckCount: T
  passengerCount: T
  sedanCount: T
  otherCount: T
}

interface HoleTypes<T = string> {
  name: T
  key: T
  inkey: number
  seKey: T
}

const holeTypes = ref<HoleTypes[]>([])

const tunnelStore = useTunnelStoreWithOut()

const props = defineProps<{
  useMaterial: boolean
  showFlow: boolean
}>()

const eventRef = ref<any>(null) // 事件弹窗实例
// const sceneMode = ref('panorama')
const router = useRouter()
const holeDirection = ref<number>(0)

const inNewTraffic = ref<TrafficEngine | null>(null) // 新洞上行隧道实例
const outNewTraffic = ref<TrafficEngine | null>(null) // 新洞下行隧道实例

const inOldTraffic = ref<TrafficEngine | null>(null) // 老洞上行隧道实例
const ouOldTraffic = ref<TrafficEngine | null>(null) // 老洞下行隧道实例

const flowChartRef1 = ref<InstanceType<typeof FlowChart> | null>(null)
const flowChartRef2 = ref<InstanceType<typeof FlowChart> | null>(null)

const newSummary = ref<TrafficSummary>({
  name: '杭州方向',
  direction: 0,
  dangerousCount: 0,
  truckCount: 0,
  passengerCount: 0,
  sedanCount: 0,
  otherCount: 0
})

const oldSummary = ref<TrafficSummary>({
  name: '杭州方向',
  direction: 0,
  dangerousCount: 0,
  truckCount: 0,
  passengerCount: 0,
  sedanCount: 0,
  otherCount: 0
})

// 路控配置
const configs = reactive<any>({
  plateType: 1, // 铭牌展示类型
  filterType: null, // 类型筛选
  useMaterial: true // 是否使用贴图
})

// 新洞实例
const newTraffic = computed(() => {
  return holeDirection.value === 1 ? outNewTraffic.value : inNewTraffic.value
})
// 老洞实例
const oldTraffic = computed(() => {
  return holeDirection.value === 1 ? ouOldTraffic.value : inOldTraffic.value
})

// 铭牌切换
const plateChange = (e: number) => {
  configs.plateType = e
}

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

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

  const summary = [newSummary, oldSummary][holeType === 'new' ? 0 : 1]

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

// 缎面跳转
const goSection = ({ x, direction, scrollLeft, holeType }) => {
  router.push({
    path: '/section',
    query: {
      x,
      direction,
      scrollLeft,
      holeType,
      from: 'home'
    }
  })
}

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

// 创建车流实例
const createTraffic = async () => {
  const isAvl = await awaitGet(() => tunnelStore.getUpTunnel?.long)

  // 隧道数据获取错误
  if (!isAvl) return

  const create = (direction, holeType) => {
    const key = direction ? 'getDownTunnel' : 'getUpTunnel'
    const { start, end, long } = tunnelStore[key]

    return new TrafficEngine('panorama', {
      direction,
      holeType, // （新洞/老洞）目前还没有实现，需后续补功能
      start: +start,
      end: +end,
      miles: +long,
      road_w: holeType === 'new' ? 90 : 64
    })
  }

  inNewTraffic.value = create(0, 'new')
  outNewTraffic.value = create(1, 'new')

  inOldTraffic.value = create(0, 'old')
  ouOldTraffic.value = create(1, 'old')

  // 后续接新洞后再做修改
  // newTraffic.value?.startTraffic((res) => {
  //   carSocket(res, 'new')
  // })

  oldTraffic.value?.startTraffic((res) => {
    carSocket(res, 'old')
  })
}

const spaceAxisHNRef = ref<InstanceType<typeof SpaceAxis> | null>(null)
const spaceAxisHORef = ref<InstanceType<typeof SpaceAxis> | null>(null)

// 点击滚动轴
const spaceAxisScroll = (e: number, holeType: string) => {
  if (holeType === 'new') {
    spaceAxisHNRef.value?.updateThumb({ scrollLeft: e })
  } else {
    spaceAxisHORef.value?.updateThumb({ scrollLeft: e })
  }
  goSection({ x: 0, direction: holeDirection.value, scrollLeft: e, holeType })
}

// watch(
//   () => sceneMode.value,
//   (e) => {
//     if (e === 'section') {
//       goSection({ x: 0, direction: 0 })
//     }
//   }
// )

watch(
  () => holeDirection.value,
  (e) => {
    // 刷新流量图
    nextTick(() => {
      flowChartRef1.value?.chartRender()
      flowChartRef2.value?.chartRender()
    })

    // 后续接新洞后再做修改
    // newTraffic.value?.startTraffic((res) => {
    //   carSocket(res, 'new')
    // })
    newSummary.value.direction = e
    oldSummary.value.direction = e

    if (e === 1) {
      inOldTraffic.value?.cleanRoad()

      // 暂时解决老洞下行没有车流数据接入，后续接入后需要调整 start
      carSocket(
        {
          name: '杭州方向',
          direction: 1,
          dangerousCount: 0,
          truckCount: 0,
          passengerCount: 0,
          sedanCount: 0,
          otherCount: 0
        },
        'old'
      )
      // 暂时解决老洞下行没有车流数据接入，后续接入后需要调整 end
    } else {
      ouOldTraffic.value?.cleanRoad()
    }

    oldTraffic.value?.startTraffic((res) => {
      carSocket(res, 'old')
    })
  }
)

watch(
  () => props.useMaterial,
  (e) => {
    configs.useMaterial = e
  }
)

watch(
  () => ASYNC_DIRECTIONS(),
  (directions) => {
    holeTypes.value = [...directions]
  },
  { deep: true, immediate: true }
)

// 打开事件弹窗
provide('openEventPop', (event) => {
  return eventRef?.value.diaOpen(event)
})

onMounted(() => {
  createTraffic()
})

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

defineExpose({
  plateChange
})
</script>

<style lang="scss" scoped>
.traffic {
  position: relative;
  text-align: center;
  overflow: hidden;
  .scale-ctrls {
    position: absolute;
    right: 85px;
    top: 15px;
  }
  .hole-select {
    position: absolute;
    color: white;
    display: flex;
    align-items: center;
    width: 200px;
    top: 10px;
    left: 85px;
    .name {
      font-size: 14px;
      white-space: nowrap;
    }
  }

  :deep(.define-select) {
    background: rgba(38, 67, 106);
    border: none;
    color: white;
    .el-popper__arrow::before {
      background: rgba(38, 67, 106);
      border: none;
    }
  }

  :deep(.el-select-dropdown__item) {
    color: white;
    &.is-hovering {
      background-color: rgb(54, 89, 128);
    }
  }

  .cameras-block {
    height: 200px;
    display: flex;
    flex-direction: column;
    margin-bottom: 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>
