<template>
  <ui-editor-toolbar toolbar v-if="sceneModel">
    <span>长度：</span>
    <ui-input
      type="number"
      width="120px"
      class="leng-input"
      :ctrl="false"
      v-model="length"
    >
      <template #icon>m</template>
    </ui-input>
    <ui-button type="submit" width="160px" @click="resetMeasure">重新选点</ui-button>
  </ui-editor-toolbar>
</template>

<script lang="ts" setup>
import { Message } from "bill/index";
import { useViewStack } from "@/hook";
import { router, RoutesName } from "@/router";
import { ref, computed, watch, watchEffect } from "vue";
import { getSceneModel } from "@/sdk";
import { autoSaveFuseModels, FuseModel, getFuseModel, leave } from "@/store";
import { currentModelStack } from "@/env";

import type { ScaleSet } from "@/sdk";
import { round } from "@/utils";

const isCurrent = computed(
  () => router.currentRoute.value.name === RoutesName.proportion
);
const model = computed(() => {
  if (isCurrent.value) {
    const modelId = router.currentRoute.value.params.id as string;
    if (modelId) {
      return getFuseModel(modelId);
    }
  }
});

const sceneModel = computed(() => model.value && getSceneModel(model.value));

let scaleSet: ScaleSet | null = null;
const length = ref<number | null>(null);

watch(length, () => {
  const len = length.value;
  if (len !== null) {
    scaleSet?.setLength(len);
    length.value = round(len, 2);
  }
});

const resetMeasure = () => {
  scaleSet?.startMeasure();
};

watchEffect((onCleanup) => {
  const smodel = sceneModel.value;
  if (smodel) {
    scaleSet = smodel.enterScaleSet();
    scaleSet.startMeasure();
    const pop = currentModelStack.push(model as any);

    onCleanup(() => {
      smodel.leaveScaleSet();
      scaleSet = null;
      pop();
    });
  } else if (isCurrent.value) {
    leave();
  }
});

useViewStack(() => {
  const hide = Message.show({ msg: "请选择两点标记一段已知长度，并输入真实长度" });
  return () => {
    hide();
    length.value = null;
  };
});
useViewStack(autoSaveFuseModels);
</script>

<style lang="scss" scoped>
.leng-input {
  margin: 0 20px 0 10px;
}
</style>
