import { reactive, watch } from 'vue'
import TrafficEngine from '@/views/traffic/roads/Engine/index'
import { useTunnelStoreWithOut } from '@/store/modules/tunnel'
import { ROAD_DIRECTION } from '@/config/enum'
import { numToSection } from '@/utils/tunnel'

const tunnelStore = useTunnelStoreWithOut()

const params = reactive({
  inited: false, // 初始化状态
  mode: 'online', // 模式
  sceneMode: 'section', // 车流模式
  direction: 0, // 方向
  flows: [], // 车流
  sectionAct: 0, // 激活 act
  engine: null // 车流引擎
})

const setCommons = (infos) => {
  params.mode = infos.existHisData ? 'mook' : 'online'
  params.direction = ROAD_DIRECTION[infos.direction]
  params.flows = (infos?.hisVehicleInfo || []).map(item => item.frame)
  params.sectionAct = numToSection(+infos.milestone, params.direction)
  params.inited = true
}

const setParams = (key, value) => {
  params[key] = value
  if (key === 'mode') {
    runTraffic()
  }
}

const getParams = (key) => params[key]

const runTraffic = () => {
  if (!params.engine) return
  
  if (params.mode === 'online') {
    params.engine.startTraffic()
    return
  }
  
  if (params.mode === 'mook') {
    params.engine.startMook(params.flows)
  }
  
}

watch(
  [() => params.inited, tunnelStore.getUpTunnel],
  ([val1, val2]) => {

    if (val1 && tunnelStore.getUpTunnel.long && !params.engine) {

      const { start, end, long } = tunnelStore[['getUpTunnel', 'getDownTunnel'][params.direction]]

      params.engine = new TrafficEngine(params.sceneMode, {
        direction: val1,
        start: +start,
        end: +end,
        miles: +long
      })

      runTraffic()

    }
  },
  {
    immediate: true
  }
)

watch(
  () => params.sceneMode,
  mode => {
    if (params.engine) {
      params.engine.sceneChange(mode)
      params.engine.reMook()
    }
  }
)

export {
  setCommons,
  setParams,
  getParams
}