import dayjs from 'dayjs'
import { getFlowCars } from '@/api/history'
import { getRunFlows, getUpdateFlows } from '../Common'
import { awaitGet } from '@/utils/tunnel'
import { useTunnelStoreWithOut } from '@/store/modules/tunnel'
import TrafficEngine from '@/views/traffic/roads/Engine/index'
import bus from '@/utils/eventBus'

const DIRECTION_MAP = {
  xl_tunnel_up: 0,
  xl_tunnel_down: 1
}

const tunnelStore = useTunnelStoreWithOut()

const params = reactive({
  mode: 'section', // 视图模式
  direction: null, // 方向
  infos: null, // 记录信息
  flows: [], // 车流
})

// 隧道引擎
const traffic = ref<any>(null)

// 隧道信息
const nowTunnel = computed(() => {
  return [
    tunnelStore.getUpTunnel,
    tunnelStore.getDownTunnel
  ][params.direction] || null
})

// 时间分片
const computTimePice = (infos) => {
  const { inTunnelTime, outTunnelTime, carId } = infos
  const start = (new Date(inTunnelTime)).getTime()
  const end = (new Date(outTunnelTime)).getTime()

  const left = (end - start) % 5000
  const nums = (end - start - left) / 5000 + (left > 0 ? 1 : 0)

  return (new Array(nums)).fill(null).map((_, x) => {
    return [
      dayjs(start + 5000 * x).format('YYYY-MM-DD HH:mm:ss'),
      dayjs(x === nums - 1 ? end : (start + 5000 * (x + 1))).format('YYYY-MM-DD HH:mm:ss'),
    ]
  })
}

// 链式获取车流数据
const linkRun = async (carId, tunnelId, arr, x = 0) => {

  const res = await getFlowCars({
    tunnelId,
    startTime: arr[x][0],
    endTime: arr[x][1]
  })

  if (carId !== params.infos.carId) return // 数据已切换

  params.flows = [
    ...params.flows,
    ...res.map(item => item.frame)
  ]

  if (x === 0) {
    traffic.value.startMook(JSON.parse(JSON.stringify(params.flows)), true)
  } else {
    traffic.value.updateMooks(JSON.parse(JSON.stringify(res.map(item => item.frame))), x === arr.length - 1)
  }
  

  if (x < arr.length - 1) {
    await linkRun(carId, tunnelId, arr, x + 1)
  }

}

// 构建隧道引擎
const goCreateTraffic = async () => {

  const isAvl = await awaitGet(() => nowTunnel.value?.long)

  if (isAvl) {
    const { start, end, long } = nowTunnel.value
    traffic.value = new TrafficEngine(params.mode, {
      direction: params.direction,
      start: +start,
      end: +end,
      miles: +long
    })
  }

}

// 设置模式
const setMode = async (e) => {
  params.mode = e
  traffic.value.sceneChange(e)
}

// 设置轨迹
const setTrack = async (e) => {

  if (traffic.value) {
    traffic.value.cleanRoad()
  }

  params.infos = JSON.parse(JSON.stringify(e))
  params.direction = DIRECTION_MAP[e.tunnelId]
  await goCreateTraffic()
  linkRun(e.carId, e.tunnelId, computTimePice(e))

  bus.emit('track-change')
  
}

// 行车向供给
const getDirection = () => params.direction

// 记录基础信息供给
const getInfos = () => params.infos

// 引擎供给
// const getTraffic = computed(() => traffic.value)

export {

  traffic,

  setTrack,
  setMode,

  getDirection,
  getInfos,
  // getTraffic
}