<template>
  <RightFillPano>
    <ui-group borderBottom>
      <template #header>
        <ui-button @click="editTagging = createTagging()">
          <ui-icon type="add" />
          新增
        </ui-button>
      </template>
    </ui-group>
    <ui-group title="标注">
      <template #icon>
        <ui-icon 
          ctrl
          :type="custom.showTaggings ? 'eye-s' : 'eye-n'" 
          @click="custom.showTaggings = !custom.showTaggings" 
        />
      </template>
      <ui-group-option>
        <ui-input type="text" width="100%" placeholder="搜索">
          <template #preIcon>
            <ui-icon type="search" />
          </template>
        </ui-input>
      </ui-group-option>
      <TagingSign 
        v-for="tagging in taggings" 
        :key="tagging.id" 
        :tagging="tagging" 
        :selected="selectTagging === tagging"
        @edit="editTagging = tagging"
        @delete="deleteTagging(tagging)"
        @select="selectTagging = tagging"
        @flyPositions="flyTaggingPositions(tagging)"
      />
    </ui-group>
  </RightFillPano>

  <Edit 
    v-if="editTagging" 
    :data="editTagging" 
    @quit="editTagging = null" 
    @save="saveHandler"
  />
</template>

<script lang="ts" setup>
import Edit from './edit.vue'
import TagingSign from './sign.vue'
import { Message } from 'bill/index'
import { RightFillPano } from '@/layout'
import { togetherCallback } from '@/utils'
import { useViewStack } from '@/hook'
import { ref, watch } from 'vue';
import { sdk } from '@/sdk'
import { 
  taggings, 
  isTemploraryID, 
  Tagging, 
  autoSaveTaggings, 
  createTagging,
  enterEdit, 
  Model,
  getModel,
  getModelShowVariable,
  getTaggingPositions,
  taggingPositions,
createTaggingPosition
} from '@/store'
import { 
  custom, 
  showTaggingPositionsStack,
  showLeftCtrlPanoStack, 
  showLeftPanoStack,
  currentModelStack,
  showRightCtrlPanoStack,
  showRightPanoStack
} from '@/env'


const editTagging = ref<Tagging | null>(null)
const saveHandler = (tagging: Tagging) => {
  if (!editTagging.value) return;
  if (isTemploraryID(editTagging.value.id)) {
    taggings.value.push(tagging)
  } else {
    Object.assign(editTagging.value, tagging)
  }
  editTagging.value = null
}

const deleteTagging = (tagging: Tagging) => {
  const index = taggings.value.indexOf(tagging)
  taggings.value.splice(index, 1)
}

let stopFlyTaggingPositions: () => void
const flyTaggingPositions = (tagging: Tagging) => {
  const positions = getTaggingPositions(tagging)
  stopFlyTaggingPositions && stopFlyTaggingPositions()

  let isStop = false

  const flyIndex = (i: number) => {
    if (isStop || i >= positions.length) {
      return;
    }
    const position = positions[i]
    const model = getModel(position.modelId)
    if (!model || !getModelShowVariable(model).value) {
      flyIndex(i + 1)
      return;
    }

    
    const pop = showTaggingPositionsStack.push(ref(new WeakSet([position])))
    sdk.comeTo({ 
      position: position.localPos, 
      modelId: position.modelId,
      dur: 300,
      distance: 3
    })
    
    console.log('改变了', custom.showTaggingPositions.has(position))
    setTimeout(() => {
      pop()
      flyIndex(i + 1)
    }, 2000)
  }
  flyIndex(0)
  stopFlyTaggingPositions = () => isStop = true
}

const stopFlyKeyupHandler = (ev: KeyboardEvent) => {
  ev.code === 'Escape' && stopFlyTaggingPositions && stopFlyTaggingPositions()
}
useViewStack(() => {
  document.documentElement.addEventListener('keyup', stopFlyKeyupHandler, false)
  return () => document.documentElement.removeEventListener('keydown', stopFlyKeyupHandler, false)
})

const selectTagging = ref<Tagging | null>(null)
watch(selectTagging, (a, b, onCleanup) => {
  if (selectTagging.value) {
    const leave = () => selectTagging.value = null

    let currentModel: Model | null = custom.currentModel
    if (!currentModel) {
      for (const [model, show] of custom.showModelsMap.entries()) {
        show && (currentModel = model)
      }
      if (!currentModel) {
        Message.error('请显示要添加热点的模型') 
        leave()
        return
      }
    }

    const pop = togetherCallback([
      showLeftCtrlPanoStack.push(ref(true)), 
      showLeftPanoStack.push(ref(true)),
      currentModelStack.push(ref(currentModel)),
      showRightCtrlPanoStack.push(ref(false)),
      showRightPanoStack.push(ref(false))
    ])

    const clickHandler = (ev: MouseEvent) => {
      const position = sdk.getPositionByScreen({
        x: ev.clientX,
        y: ev.clientY
      }, custom.currentModel?.id)

      if (!position) {
        Message.error('当前位置无法添加')
      } else if (selectTagging.value) {
        const storePosition = createTaggingPosition({
          ...position,
          taggingId: selectTagging.value.id
        })
        taggingPositions.value.push(storePosition)
        leave()
      }
    }
    const keyupHandler = (ev: KeyboardEvent) => ev.code === 'Escape' && leave()

    document.documentElement.addEventListener('keyup', keyupHandler, false);
    sdk.layout.addEventListener('click', clickHandler, false)

    enterEdit(leave)
    onCleanup(() => {
      document.documentElement.removeEventListener('keyup', keyupHandler, false);
      sdk.layout.removeEventListener('click', clickHandler, false);
      pop()
    })
  }
})

useViewStack(autoSaveTaggings)
</script>