<template>
  <RightFillPano>
    <div class="btns header-btns">
      <ui-button class="start" @click="getView">
        <ui-icon type="add" />
        视图提取
      </ui-button>
    </div>

    <ui-group title="全部视图" class="tree" >
      <Draggable :list="views" draggable=".sign" itemKey="id">
        <template #item="{ element: view }">
          <Sign 
            :view="view" 
            :key="view.id" 
            @delete="() => deleteView(view)"
            @updateTitle="title => view.title = title"
            @updateCover="cover => view.cover = cover"
          />
        </template>
      </Draggable>
    </ui-group>
  </RightFillPano>
</template>

<script lang="ts" setup>
import { views, createView, autoSaveViews, initialViews } from '@/store'
import { RightFillPano } from '@/layout'
import { useViewStack } from '@/hook'
import Draggable from 'vuedraggable'
import Sign from './sign.vue'
import { loadModel, currentModel, fuseModel } from '@/model'
import { loadPack, togetherCallback } from '@/utils'
import { Message } from 'bill/index'
import { showLeftPanoStack } from '@/env'
import { ref, watch } from 'vue'

import type { View } from '@/store'

initialViews()

const getView = async () => {
  try {
    const { image, flyData } = await loadPack(async () => {
      const modelSDK = await loadModel(currentModel.value)
      return await modelSDK.getView()
    })

    const type = currentModel.value !== fuseModel 
      ? { numType: currentModel.value.type, num: currentModel.value.num }
      : {}

    views.value.push(createView({
      flyData,
      cover: {
        blob: image,
        url: URL.createObjectURL(image)
      },
      ...type
    }))
  } catch (e: any) {
    console.error(e)
    Message.error(e.message)
  }
}
const deleteView = (record: View) => {
  const index = views.value.indexOf(record)
  if (~index) {
    views.value.splice(index, 1)
  }
}

const showLeftPano = ref(false)
watch(currentModel, () => {
  if (currentModel.value) {
    showLeftPano.value = false
  }
})


useViewStack(autoSaveViews)
useViewStack(() => togetherCallback([
  showLeftPanoStack.push(showLeftPano) 
]))
</script>

<style lang="scss" src="./style.scss" scoped>
</style>