// 事件流控制器

import TrafficSocket from '@/views/3DModel/socket'
import EventModel from './event'
import { getEventList } from '@/api/event'
import { sleep } from '@/utils'
import { eventFormate } from '../utils'
import dayjs from 'dayjs'

export default class Traffic {

  events = [] // 事件缓存
  direct = null // 车流方向（0 出发、1 返回）

  tunnel = null // 隧道
  socket = null // 链接

  // socket 模拟
  state = 'off' // 状态
  pulse_frequency = 5000 // 间隔

  constructor (configs) {

    this.direct = configs.direct
    this.tunnel = configs.tunnel

    const keySocket = ['IN_EVENT', 'OUT_EVENT'][this.direct]
    this.socket = new TrafficSocket(keySocket)

  }

  // 开启事件流
  start (call) {

    /* this.socket.start(res => {
      console.log(res)
    }) */
    
    this.state = 'on'

    const today = (new Date()).getTime()
    const nextDay = today + 24 * 3600 * 1000
    const resolve = null

    const socketMook = async () => {

      try {
        const res = await getEventList({
          eventStatusSearch: 0,
          pageNo: 1,
          pageSize: 100,
          direction: [['上行', '下行'][this.direct]],
          eventType: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "100"],
          eventStartTimeSearchStart: dayjs(today).format('YYYY-MM-DD') + ' 00:00:00',
          eventStartTimeSearchEnd: dayjs(nextDay).format('YYYY-MM-DD') + ' 00:00:00'
        })

        this.events = res.list.map(xevent => eventFormate(xevent)).filter(item => item.location)

        call(this.events)

        if (this.state === 'on') {
          await sleep(this.pulse_frequency)
          socketMook()
        }

      } catch (error) {
        console.log(error)
        this.state === 'off'
      }

    }

    socketMook()


  }

  // 关闭连接
  close () {
    this.state === 'off'
    // this.socket.close()
  }

  // 输出供给
  exportEvents () {
    return JSON.parse(JSON.stringify(this.events))
  }

}