<script setup lang="ts">
import { ref } from 'vue'
import TreeItem from './index.menu.vue'

interface MenuItem {
  name: string
  text: string
  next?: Array<MenuItem> | undefined
  active?: Boolean
}

const menu = ref<Array<MenuItem>>([
  { text: '基础用法', name: 'basic' },
  { text: '固定截图', name: 'screenshot' },
  { text: '动态截图', name: 'extract' },
  { text: '场景滤镜', name: 'filter' },
  { text: '漫游可行', name: 'roam' },
  { text: '地面图标', name: 'floorlogo' },
  {
    text: '热点管理',
    name: 'tag',
    next: [
      { text: '添加热点', name: 'tag/add' },
      { text: '编辑热点', name: 'tag/edit' },
      { text: '删除热点', name: 'tag/delete' },
    ],
  },
  {
    text: '自动导览',
    name: 'tour',
    next: [
      { text: '录制导览', name: 'tour/record' },
      { text: '播放导览', name: 'tour/play' },
    ],
  },
  {
    text: '空间装饰',
    name: 'space',
    next: [
      { text: '添加视频', name: 'space/video' },
      { text: '添加图片', name: 'space/image' },
    ],
  },
  { text: '户型图', name: 'cad/index' },
])

const menuActive = ref(
  (window.location.hash || '').replace(/#\/?/, '').split('=')[1] || 'basic'
)
const menuSearch = (data: Array<MenuItem> | undefined) => {
  if (data === undefined) {
    data = menu.value
  }

  for (let i = 0; i < data.length; i++) {
    delete data[i].active
    if (data[i].next) {
      menuSearch(data[i].next)
    } else if (data[i].name == menuActive.value) {
      data[i].active = true
    }
  }
}

window.onhashchange = () => {
  menuActive.value = (window.location.hash || '')
    .replace(/#\/?/, '')
    .split('=')[1]
  menuSearch(undefined)
}
menuSearch(undefined)
let params = (window.location.hash || '').replace(/#\/?/, '')
if (params.indexOf('app') === -1) {
  params = `app=${menu.value[0].name}`
}
const link = ref('demo.html?' + params)
const onLoad = () => {
  let iframe = document.getElementById('demo') as HTMLIFrameElement
  if (iframe.contentWindow) {
    window.__sdk = iframe.contentWindow.__sdk
    window.KanKan = iframe.contentWindow.KanKan
    window.location.hash = iframe.contentWindow.location.search.substring(1)
  }
}
</script>

<template>
  <div class="playground">
    <aside>
      <ul>
        <tree-item v-for="model in menu" :data="model"></tree-item>
      </ul>
    </aside>
    <main>
      <iframe
        id="demo"
        name="demo"
        frameborder="0"
        :src="link"
        @load="onLoad"
      ></iframe>
    </main>
  </div>
</template>

<style>
#app {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
.playground {
  display: flex;
  width: 100%;
  height: 100%;
}
aside {
  width: 180px;
  height: 100%;
  overflow: hidden;
}
main {
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}
iframe {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  border: none;
}
ul {
  padding-left: 1em;
  line-height: 1.5em;
}
</style>
