import { ref, watch } from "vue"

export function useNavi(map) {
  const pathIdList = ref([])
  
  function addPath(polygon) {
    if(polygon?.id && pathIdList.value[pathIdList.value.length - 1] === polygon?.id) return // 不连续添加相同的项

    const modelId = polygon.extrasModelId;
    const model = map.value.getModelById(modelId)
    const modelName = model.userData.modelData.name
    console.log(modelName, 'model.name', polygon.id,'polygon.id')

    addPathId(polygon.id)
  }

  function addPathId(id) {
    if(id && pathIdList.value[pathIdList.value.length - 1] === id) return

    pathIdList.value.push(id)
  }

  function startNavi() {
    if(pathIdList.value.length < 2) return
    map.value.navi.simulate()
    map.value.navi.setSimulateSpeed(10)
  }

  function pauseNavi () {
    // 判断当前是否处于导航中
    if (map.value.navi.status.isSimulate) {
      map.value.navi.pauseSimulate()
    }
  }

  function restoreNavi () {
    // 判断当前是否处于暂停中
    if (!map.value.navi.isSimulatePause) {
      map.value.navi.resumeSimulate()
    }
  }

  function stopNavi () {
    // 退出模拟导航
    map.value.navi.stopSimulate()
    removePathLine()
    pathIdList.value = []
  }

  function removePathLine() {
    // 销毁箭头
    map.value.navi.removeNaviArrow()
    // 销毁线路
    map.value.navi.removeNaviLine()
    //移除途径点
    map.value.navi.removeAllWaypoint()
    //移除起点
    map.value.navi.removeStart()
    //移除终点
    map.value.navi.removeEnd()
  }

  watch(pathIdList, (pathIdList) => {
    if(pathIdList?.length < 2) {
      removePathLine()
      return
    }
    const end = pathIdList[pathIdList.length - 1]
    const [start, ...passPoints]= pathIdList.slice(0, -1);

    map.value.navi.removeAllWaypoint()

    map.value.navi.setStart(start)
    map.value.navi.setWaypoints(passPoints)
    map.value.navi.setEnd(end)

    map.value.navi.find()
  }, {
    deep: true,
  })

  return {
    pathIdList,
    addPath,
    addPathId,
    startNavi,
    pauseNavi,
    restoreNavi,
    stopNavi,
  }
}
