import * as TWEEN from '@tweenjs/tween.js'
import * as THREE from 'three'
import CarModel from '../models/car'

import { sceneCheck } from '@/views/3DModel/state'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { POINT_START, POINT_END, POINT_SCANE } from '../points'
import { numToStone } from '@/utils/tunnel'

import { scaneSet, scaneClean } from './scane'
import { trackSet } from './track'

import { bus, events } from '@/views/3DModel/state'

let env = {}

// 添加控制器
const addControls = (target) => {
  const context = env.getContext()
  const controls = new OrbitControls(context.camera, context.renderer2d.domElement)
  controls.target = target
  context.controls = controls
}

// 删除控制器
const removeControls = () => {
  const context = env.getContext()
  if (context.controls) {
    context.controls.dispose()
    context.controls = null
  }
}

// 视角设置
const viewReset = (key) => {

  if (!sceneCheck('locate')) {
    return
  }

  const context = env.getContext()

  removeControls()

  const { pos, direct } = [POINT_SCANE, POINT_END, POINT_START][key]

  context.camera.position.copy(pos)
  context.camera.setLook(direct.x, direct.y, direct.z)
  context.scene.add(context.camera)
  
  addControls(new THREE.Vector3(direct.x, direct.y, direct.z))

  // 内存清理
  scaneClean()

}

// 铭牌切换
const plateChange = (type) => {

  console.log(type)

  const cars = env.getTunnles().map(item => item.cars).flat()
  cars.forEach(xCar => {
    xCar.vm_instance.typeChange(type)
  })
  // console.log(cars)

  // const typeFlex = ['危化品车', '客车', '轿车', '货车', '其他车']

  // const getPlate = (infos, type) => {
  //   if (type === 'plate') return infos.plate
  //   if (type === 'type') return typeFlex[infos.type]
  //   if (type === 'speed') return infos.speed + 'km/h'
  //   if (type === 'locate') return numToStone(infos.milestone)
  // }

  // let SIGN_KEY_CHANGE = CarModel.setRunningCall((plate, infos) => {
  //   plate.element.innerHTML = getPlate(infos, 'plate')
  // })

  // return (type) => {
  //   SIGN_KEY_CHANGE = CarModel.setRunningCall((plate, infos) => {
  //     plate.element.innerHTML = getPlate(infos, type)
  //   }, SIGN_KEY_CHANGE)
  // }

}

// 连接建立
const useConnectCall = (provides) => {

  env = { ...provides }

  bus.on('view-reset', direct => {
    viewReset(direct)
  })

  // 车辆标签切换
  // const signCall = plateChange()
  bus.on('plate-change', type => {
    plateChange(type)
  })

  // 初始化
  scaneSet(env)
  trackSet({ ...env, removeControls })

}

// 控制器缓存清理
const controlsClean = () => {
  bus.off('view-reset')
  bus.off('plate-change')
}

export {
  useConnectCall,
  controlsClean
}