<template>
  <div class="preview-view">
    <div id="div3d"></div>
    <div class="btn-import">
      <Button
        customIcon="uino-icon uino-icon-daoru"
        tooltip="导入预制件数据"
        @click="importPrefabJson"
      ></Button>
    </div>
  </div>
</template>

<script>
import initScene from '@/mixins/initScene'
import storage from '@/utils/storage'
import pluginMixin from '@/mixins/plugin'

export default {
  name: 'HomeView',
  components: {},
  mixins: [initScene, pluginMixin],
  methods: {
    loadPrefabJson() {
      return new Promise((resolve, reject) => {
        let input = document.createElement('input')
        input.type = 'file'

        // 绑定onchange事件
        input.onchange = (event) => {
          let files = event.target.files
          if (!files || !files.length) {
            input = null
            reject(new Error('No files'))
          }

          // 当选择文件后，使用FileReader API读取文件，返回数据
          let reader = new FileReader()
          reader.onload = (eve) => {
            try {
              resolve(eve.target.result)
            } catch (e) {
              reject(e)
            }
          }
          reader.readAsText(files[0])
        }

        // 触发上传文件
        input.click()
      })
    },
    async importPrefabJson() {
      // 加载预制件
      this.$Modal.info({
        title: '导入文件将会覆盖当前场景的预制件',
        onOk: async () => {
          // 读取 json 数据
          const res = await this.loadPrefabJson()
          this.parse(res)
        },
      })
    },
    loadLocalPrefabData() {
      return new Promise((resolve) => {
        let prefabList = storage.getItem('prefabList')
        if (prefabList) {
          this.parse(prefabList, resolve)
        } else {
          resolve()
        }
      })
    },
    parse(prefabList, resolve) {
      if (!prefabList) return
      const importer = new THING.SceneLoader()
      importer.parse(
        THING.SceneResourceType.Object,
        prefabList,
        () => {
          resolve()
          app.query('.PrefabObject').forEach((item) => {
            item.name = item.userData._name || item.name
          })

          // 所有预制件加载完毕
          // 这里定义了一个事件，用于预制件内部监听。
          app.trigger('AllPrefabsLoadedEvent', { objects: prefabList.objects })
        },
        null,
        null,
        {
          autoCompile: false,
        }
      )
    },
  },
  mounted() {
    this.initScene()
  },
}
</script>

<style scoped lang="less">
.btn-import {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #000;
  border-radius: 4px;
}
</style>
