<template>
  <RightFillPano>
    <ui-group :title="`${tagging?.title}放置位置`" class="position-group">
      <PositionSign 
        v-for="(position, i) in positions" 
        :key="position.id" 
        :position="position"
        :title="`位置${i + 1}`"
        @delete="deletePosition(position)"
        @fixed="flyTaggingPosition(position)"
      />
    </ui-group>
  </RightFillPano>
</template>


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

import type { TaggingPosition } from '@/store'

const tagging = computed(() => getTagging(router.currentRoute.value.params.id as string))
const positions = computed(() => tagging.value && getTaggingPositions(tagging.value))

const flyTaggingPosition = (position: TaggingPosition) => {
  const model = getFuseModel(position.modelId)
  if (!model || !getFuseModelShowVariable(model).value) {
    return;
  }
  
  const pop = showTaggingPositionsStack.push(ref(new WeakSet([position])))
  sdk.comeTo({ 
    position: position.localPos, 
    modelId: position.modelId,
    dur: 300,
    distance: 3
  })
  
  setTimeout(pop, 2000)
}

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

watchEffect((onCleanup) => {
  if (tagging.value) {
    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)
      }
    }
    sdk.layout.addEventListener('click', clickHandler, false)

    onCleanup(() => {
      sdk.layout.removeEventListener('click', clickHandler, false);
    })
  }
})
useViewStack(autoSaveTaggings)
useViewStack(() => {
  const hide = Message.show({ msg: '请在模型上单击选择标注位置', type: 'warning' })
  enterEdit(() => router.back())
  return hide
})
</script>

<style lang="scss" scoped src="./style.scss"></style>
<style lang="scss">
.position-group .group-title{
  margin-bottom: 0;
}
</style>