<template>
  <!-- {{ sectionTrans }} -->
  <div :class="['x-direction', ['in', 'out'][direction]]">

    <!-- 段面控制器 -->
    <div class="section-box">
      <Section
        v-bind="{ data:_sections, scene: 'section', direction }"
        v-model="sectionAct"
        @go-section="handleChange"
      />

      <TrackPoint v-bind="{ trackers, direction }" />
    </div>

    <!-- 刻度线 -->
    <Scale v-bind="{ data:_sections, direction, tunnel }" />

    <div class="road-scale">
      
      <div :style="roadStyle" class="main-road">

        <!-- 停车带层 -->
        <Parking v-bind="{ scene: 'section', direction, tunnel,  _traffic: traffic  }" />

        <!-- 摄像机层 -->
        <Camera v-bind="{ direction, tunnel,  _traffic: traffic }" @camera-change="e => emits('camera-change', e)" />
       
        <!-- 路面层 -->
        <div class="level-road">

          <!-- 热力图层 -->
          <HeatRoad :direction />
         
          <!-- 虚实线 -->
          <Line v-bind="{ direction, tunnel,  _traffic: traffic }" />

          <!-- 路标 -->
          <Arrow v-bind="{ direction, tunnel,  _traffic: traffic }" />

          <!-- 车流层 -->
          <Cars
            v-model:cars="_cars"
            v-model:selected="_carSelected"
            v-bind="{
              scene: 'section',
              _traffic: traffic, _events, tunnel, filterType,
              direction, plateType, useMaterial,
              trackers, evtConfigs
            }"
            @car-socket="e => emits('car-socket', e)"
          />

          <!-- 事件层 -->
          <Events
            v-model:events="_events"
            v-model:selected="_eventSelected"
            v-bind="{
              scene: 'section',
              _traffic: traffic, direction, evtConfigs, tunnel
            }"
          />
        </div>

        <!-- 桩号层 -->
        <Pile v-bind="{ direction, tunnel, _traffic: traffic }" />

      </div>
    </div>

    <CarCollect
      v-model="_carSelected"
      :cars="_cars"
      ref="collectRef"
      @go-track="e => emits('go-track', e)"
    />

    <EventPop
      :events="_events"
      v-model="_eventSelected"
      ref="eventRef"
    />

  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

import Section from '../XDirection/comps/Section/index.vue'
import Scale from '../XDirection/comps/Scale/index.vue'
import Parking  from '../XDirection/comps/Parking/index.vue'
import Camera from '../XDirection/comps/Camera/index.vue'
import Line from '../XDirection/comps/Line/index.vue'
import Arrow from '../XDirection/comps/Arrow/index.vue'
import Cars from '../XDirection/comps/Cars/index.vue'
import Events from '../XDirection/comps/Events/index.vue'
import Pile from '../XDirection/comps/Pile/index.vue'
import HeatRoad from '../XDirection/comps/HeatRoad/index.vue'
import TrackPoint from '../XDirection/comps/TrackPoint/index.vue'

import CarCollect from '@/views/traffic/components/CarCollect/index.vue'
import EventPop from '@/views/traffic/components/EventPop/index.vue'
import tunnelConfigs from '@/config/tunnel'

import TrafficEngine from '@/views/traffic/roads/Engine/index'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useTunnelStoreWithOut } from '@/store/modules/tunnel'

import { useRoute } from 'vue-router'

const props = withDefaults(
  defineProps<{
    filterType?: null | string // 筛选类型
    trackers?: any // 追踪车辆
    evtConfigs?: any, // 事件详情
    traffic?: any, // 车流引擎

    direction: number // 道路方向
    plateType: number // 铭牌类型
    useMaterial: boolean // 是否使用动态车辆贴图
  }>(),
  {
    trackers: {},
    filterType: null
  }
)

const emits = defineEmits(['open-video', 'cars-update', 'go-track', 'car-socket', 'section-change', 'camera-change'])

const tunnelStore = useTunnelStoreWithOut()
const appStore = useAppStoreWithOut()
const route = useRoute()
const collectRef = ref<any>(null) // 车辆 pop
const eventRef = ref<any>(null) // 事件 pop


const sectionTrans = ref<any>(null) // 路段动画
const start = ref(true) // 是否初次追踪
// const sectionAct = ref(0)

const _traffic = ref<any>(null) // 车流引擎
const _sections = ref<any[]>([]) // 段面控制

const _cars = ref<any>() // 车流
const _carSelected= ref(null) // 选中车辆

const _events = ref<any[]>([]) // 事件
const _eventSelected= ref(null) // 选中车辆

const sectionAct = defineModel('sectionAct') // 选中段面

const tunnel = computed(() => {
  return [
    tunnelStore.getUpTunnel,
    tunnelStore.getDownTunnel
  ][props.direction]
})

// 车道初始化
const trafficInit = (e) => {

  if (_traffic.value) return

  if (props.traffic) {
    _traffic.value = props.traffic
  } else {
    const { start, end, long } = tunnel.value
    _traffic.value = new TrafficEngine('section', {
      direction: props.direction,
      start: +start,
      end: +end,
      miles: +long
    })
  }

  _sections.value = _traffic.value.sectionsCompute()

  nextTick(() => {
    sectionChange(sectionAct.value, true)
  })
}

// 车流切面
watch(
  () => _cars.value,
  (e) => {
    emits('cars-update', e)
  }
)

// 事件段面定位
watch(
  () => [props.evtConfigs?.infos, tunnel.value?.long],
  ([infos, _long]) => {

    if (!infos || !_long) return

    const { start, end, long } = tunnel.value
    const num = +infos.milestone
    const distance = props.direction ? num - start : end - num

    // const left = distance % 300
    // sectionAct.value = (distance - left) / 300 + (left > 0 ? 1 : 0) - 1

    const left = distance % tunnelConfigs.perSection
    sectionAct.value = (distance - left) / tunnelConfigs.perSection + (left > 0 ? 1 : 0) - 1

    nextTick(() => {
      sectionChange(sectionAct.value, true)
    })

  },
  {
    immediate: true
  }
)

// 段面物理总长
const roadStyle = computed(() => {
  if (!_sections.value.length) return
  const x = _sections.value.length - 1 + _sections.value.slice(-1)[0].grow
  return {
    width: x * appStore.getDesign + 'px',
    ...sectionTrans.value
  }
})

// 缎面切换
const sectionChange = (x, direct?: boolean) => {

  emits('section-change', x)
  
  let realx = x
  if (x >= _sections.value.length - 1) {
    realx = _sections.value.length - 2 + _sections.value.slice(-1)[0].grow
  }
  
  const dx = Math.abs(sectionAct.value - x)

  // 跳过动画
  if (direct) {
    sectionTrans.value = {
      transform: `translateX(${+props.direction ? '-' : ''}${realx * appStore.getDesign}px)`
    }
  } else {
    sectionTrans.value = {
      transform: `translateX(${+props.direction ? '-' : ''}${realx * appStore.getDesign}px)`,
      transitionProperty: 'all',
      transitionDuration: `${1 * dx}s`,
      transitionTimingFunction: 'ease-in-out'
    }
  }

  sectionAct.value = x
}


// 车辆追踪
watch(
  () => props.trackers.car,
  (xcar) => {
    if (xcar && props.trackers.tracking) {

      // const distance = props.direction ? xcar.originalCar.carMilestone - tunnel.value.start : tunnel.value.end - xcar.originalCar.carMilestone
      const distance = xcar.distance
      // const left = distance % 300
      // const sections = (distance - left) / 300 + (left > 0 ? 1 : 0)

      const left = distance % tunnelConfigs.perSection
      const sections = (distance - left) / tunnelConfigs.perSection + (left > 0 ? 1 : 0)

      sectionChange(sections - 1, start.value)
      start.value = false

    }
  },
  {
    immediate: true,
    deep: true
  }
)

watch(
  () => props.traffic,
  e => {
    if (e) {
      _sections.value = e.sectionsCompute()
      nextTick(() => {
        sectionChange(sectionAct.value, true)
      })
    }
  },
  {
    immediate: true
  }
)

const handleChange = (x) => {
  if (props.trackers.tracking) {
    return ElMessage.warning('轨迹追踪过程中不支持此操作！')
  } else {
    sectionChange(x, true)
  }
}

defineExpose({
  sectionChange
})

// 打开单车弹窗
provide('openCarPop', (xcar) => {
  return collectRef.value.diaOpen(xcar)
})

// onBeforeMount(() => {

//   if (route.query.x) {
//     sectionAct.value = +route.query.x
//   }

// })

</script>

<style lang="scss" scoped>
@import url(@/views/traffic/css/car.scss);

$base-url: '@/assets/images/home/';
$base-event: '@/assets/images/event/';
$base-common: '@/assets/images/common/';

.x-direction {
  text-align: center;
  .section-box {
    position: relative;
  }
}

.ctrls {
  display: inline-flex;
  align-items: center;
  height: 42px;
  margin: 0 auto;
  .title {
    color: white;
    width: 316px;
    height: 38px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-image: url($base-url + 'arrow_lft.png');
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-position: 0 bottom;
    padding-bottom: 4px;

    .text {
      font-size: 24px;
      font-weight: 600;
      margin-left: 32px;
    }
    .more {
      font-size: 16px;
      color: rgba(240, 245, 255, 0.95);
      display: flex;
    }
  }
}

.filters {
  display: flex;
  margin-left: 15px;
  .x-car {
    height: 32px;
    font-size: 14px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 16px;
    color: #ffffff;
    background: rgba(0, 125, 250, 0.15);
    margin-left: 8px;
    cursor: pointer;
    &.act {
      background: rgba(124, 213, 255, 0.15);
      box-sizing: border-box;
      border: 1px solid #7cd5ff;
    }
  }
}

.road-scale {
  padding-top: 30px;
  height: 270px;
  padding-bottom: 30px;
  position: relative;
  overflow: hidden;
}

.main-road {
  height: 270px;
  position: relative;
  position: absolute;

  .line {
    height: 2px;
    position: absolute;
    top: 50%;
    width: 100%;
    margin-top: -1px;
    .x-line {
      height: 2px;
      position: absolute;
      &.dash {
        background: url($base-url + 'dash.png');
        background-size: 30px 2px;
      }
      &.solid {
        background: rgba($color: #ffffff, $alpha: 0.8);
      }
    }
  }

  .level-road {
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    position: absolute;
    background: url($base-url + 'road.png');
    background-size: auto 100%;
    .entry {
      height: 270px;
      width: 267px;
      background: url($base-url + 'entry.png') no-repeat;
      background-size: 100%;
      position: absolute;
      background-position-y: 10px;
      left: 0;
      top: 0;
      z-index: 1;
    }
    .export {
      height: 270px;
      width: 267px;
      background: url($base-url + 'entry.png') no-repeat;
      background-size: 100%;
      position: absolute;
      background-position-y: 10px;
      right: 0;
      top: 0;
      transform: rotateY(180deg);
      z-index: 1;
    }
  }
}

.x-direction {
  &.in {
    .running-car {
      right: -60px;
    }
    .main-road {
      right: 0;
    }
    .sections {
      flex-direction: row-reverse;
    }
  }

  &.out {
    .running-car {
      left: -60px;
      .core {
        transform: rotate(180deg);
      }
    }
    .main-road {
      left: 0;
    }
    .x-camera {
      background: url($base-url + 'camera_3.png');
      background-size: cover;

      &:hover {
        background: url($base-url + 'camera_4.png');
        background-size: cover;
      }

      &.act {
        background: url($base-url + 'camera_4.png');
        background-size: cover;
      }
    }
    .level-camera {
      left: 0;
    }
    .stone-num {
      &.first {
        transform: translateX(0%);
      }
      &.last {
        transform: translateX(-100%);
      }
    }
    .level-parking {
      left: 0;
    }
    .road-arrow {
      transform: rotateY(180deg);
    }
  }
}
</style>
