<template>
  <RightFillPano>
    <h3>{{ tagging?.title }}放置位置</h3>
    <Collapse v-model:activeKey="showId" ghost accordion expandIconPosition="end">
      <PositionSign
        v-for="(position, i) in positions"
        :key="position.id"
        :position="position"
        :title="`位置${i + 1}`"
        @applyGlobal="(keys) => applyGlobal(position, keys)"
        @delete="deletePosition(position)"
      />
    </Collapse>
  </RightFillPano>
</template>

<script lang="ts" setup>
import PositionSign from "./sign.vue";
import { router } from "@/router";
import { Dialog, Message } from "bill/index";
import { RightFillPano } from "@/layout";
import { asyncTimeout } from "@/utils";
import { useViewStack } from "@/hook";
import { computed, nextTick, onUnmounted, ref, watch, watchEffect } from "vue";
import { sdk } from "@/sdk";
import { showTaggingPositionsStack } from "@/env";
import {
  autoSaveTaggings,
  getFuseModel,
  getFuseModelShowVariable,
  getTaggingPositions,
  taggingPositions,
  createTaggingPosition,
  getTagging,
  enterEdit,
} from "@/store";
import { Collapse, CollapsePanel } from "ant-design-vue";

import type { TaggingPosition } from "@/store";
import { distance } from "@/utils/math";

const showId = ref<TaggingPosition["id"]>();
const tagging = computed(() => getTagging(router.currentRoute.value.params.id as string));
const positions = computed(() => tagging.value && getTaggingPositions(tagging.value));

watch(showId, (id) => {
  const position = positions.value?.find((item) => item.id === id);
  position && flyTaggingPosition(position);
});

let pop: () => void;
const flyTaggingPosition = (position: TaggingPosition) => {
  pop && pop();
  const model = getFuseModel(position.modelId);
  if (!model || !getFuseModelShowVariable(model).value) {
    return;
  }

  pop = showTaggingPositionsStack.push(ref(new WeakSet([position])));
  sdk.comeTo({
    position: position.localPos,
    modelId: position.modelId,
    dur: 300,
    distance: 3,
  });
  // setTimeout(pop, 2000);
};
onUnmounted(() => pop && pop());

const deletePosition = (position: TaggingPosition) => {
  const index = taggingPositions.value.indexOf(position);
  if (~index) {
    taggingPositions.value.splice(index, 1);
  }
};

const applyGlobal = async (position: TaggingPosition, keys: string | string[]) => {
  if (!(await Dialog.confirm("确定要将此属性应用到所有位置？"))) return;
  keys = Array.isArray(keys) ? keys : [keys];
  for (const current of positions.value!) {
    let val: any = current;
    let newVal: any = position;
    for (let i = 0; i < keys.length; i++) {
      if (i === keys.length - 1) {
        val[keys[i]] = newVal[keys[i]];
      } else {
        val = val[keys[i]];
        newVal = newVal[keys[i]];
      }
    }
  }
};

// const cameraPos = ref<SceneLocalPos>();
// sdk.sceneBus.on("cameraChange", (pos) => (cameraPos.value = pos));

let unKeepAdding: () => void;
const keepAdding = () => {
  const hide = Message.show({ msg: "请在模型上单击选择标签位置", type: "warning" });
  const clickHandler = async (ev: MouseEvent) => {
    await nextTick();
    await asyncTimeout();
    const position = sdk.getPositionByScreen({
      x: ev.clientX,
      y: ev.clientY,
    });

    if (!position) {
      Message.error("当前位置无法添加");
    } else {
      const storePosition = createTaggingPosition({
        ...position,
        taggingId: tagging.value!.id,
      });
      taggingPositions.value.push(storePosition);

      showId.value = storePosition.id;
      // if (cameraPos.value && distance(cameraPos.value, position.worldPos) > 8) {
      //   flyTaggingPosition(storePosition);
      // }
    }
  };
  sdk.layout.addEventListener("click", clickHandler, false);

  unKeepAdding = () => {
    hide();
    sdk.layout.removeEventListener("click", clickHandler, false);
  };
};

useViewStack(autoSaveTaggings);
</script>

<style lang="scss" scoped>
h3 {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: bold;
  font-size: 16px;
  color: #999999;
  margin-bottom: 4px;
}
</style>
<style lang="scss">
.position-group .group-title {
  margin-bottom: 0;
}
</style>
