<template>
  <n-config-provider
    data-cy="app"
    inline-theme-disabled
    :theme="theme"
    :theme-overrides="themeOverrides"
    :class="{ dark: mode }"
    :locale="zhCN"
    :date-locale="dateZhCN"
  >
    <n-layout position="absolute" style="height: 100vh">
      <n-layout-header style="padding: 24px" bordered>
        <div class="flex justify-between items-center">
          <div class="back" style="position: relative; top: 4px; color: #fff">
            <n-icon size="24" :component="ChevronBackOutline" />
            <span style="position: relative; top: -6px">返回我的场景</span>
          </div>
          <n-button type="primary" @click="handleEditorSave"> 保存</n-button>
        </div>
      </n-layout-header>
      <n-layout
        class="bg-white dark:bg-gray-800 dark:text-white text-gray-800 h-screen w-screen"
        position="absolute"
        style="top: 83px; bottom: 64px"
        has-sider
      >
        <!-- collapse-mode="transform"
          @mouseover="collapsed = false"
          @mouseleave="collapsed = true" -->
        <n-layout-sider
          data-cy="sidebar"
          :width="180"
          :collapsed="collapsed"
          :native-scrollbar="false"
          bordered
        >
          <n-menu
            class="menu-class"
            v-model:value="activeKey"
            :options="menuOptions"
            @update:value="handleUpdateValue"
          />
        </n-layout-sider>
        <n-layout-content
          content-class="layoutContent"
          :native-scrollbar="false"
        >
          <div class="app-wrap">
            <div
              class="app-scene"
              ref="sceneRef"
              :style="{
                width: sceneRefWidth,
                visibility: showScene ? 'hidden' : 'visible'
                // display: showScene ? 'none' : 'block'
              }"
            >
              <iframe
                v-if="sceneURL"
                :src="sceneURL"
                frameborder="0"
                :style="sceneMobileMode && { width: '375px', height: '677px' }"
                @load="setupSDK($event.target)"
              ></iframe>
            </div>
          </div>
          <div
            :class="{ isTran: showScene }"
            class="app-view"
            id="drawer-target"
          >
            <n-message-provider>
              <n-dialog-provider>
                <router-view />
              </n-dialog-provider>
            </n-message-provider>
          </div>
        </n-layout-content>
      </n-layout>
    </n-layout>
  </n-config-provider>
</template>

<script setup lang="ts">
import { setupSDK } from '@/sdk'
import {
  darkTheme,
  // lightTheme,
  NDialogProvider,
  NMessageProvider,
  zhCN,
  dateZhCN,
  createDiscreteApi
} from 'naive-ui'

import { computed, ref, toRaw, watchEffect, h, onMounted, watch } from 'vue'
import type { Component } from 'vue'
import { useMainStore } from '@/store'
import { themeOverrides } from '@/styles/theme'
import { editorSave } from '@/api/module/editor'
import type { ConfigProviderProps } from 'naive-ui'

const configProviderPropsRef = computed<ConfigProviderProps>(() => ({
  theme: darkTheme
}))

const { message } = createDiscreteApi(['message'], {
  configProviderProps: configProviderPropsRef
})
import { useRouter, useRoute } from 'vue-router'
import {
  ChevronBackOutline,
  Layers,
  Cog,
  HomeOutline as HomeIcon,
  RepeatOutline,
  PeopleOutline,
  ChatboxEllipses
} from '@vicons/ionicons5'

const darkStore = localStorage.getItem('dark')
import { RouterLink } from 'vue-router'
import { NIcon } from 'naive-ui'
import { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('hash')

const route = useRoute()
const activeKey = ref(route.name)

const showScene = ref(false)

watch(
  () => route.name,
  () => {
    console.log('activeKeys', route.name)
    activeKey.value = route.name
    if (route.name === 'textToaudio') {
      showScene.value = true
    } else {
      showScene.value = false
    }
    console.log('watch', route.name)
  }
)
const prefersDark: boolean = darkStore
  ? darkStore === 'true'
  : window.matchMedia('(prefers-color-scheme: dark)').matches

const mode = ref<boolean>(prefersDark)
const theme = computed(() => (mode.value ? darkTheme : darkTheme))

const sceneRefWidth = computed(() => {
  console.log('route', route, route.name)
  if (
    route.name === 'basicSettings' ||
    route.name === 'topicNavigation' ||
    route.name === 'digitalHuman'
  )
    return `calc(100% - ${240}px)`
  if (route.name === 'message') return `calc(100% - ${0}px)`
  return `calc(100% - ${mode.sceneRefWidth}px)`
})

const sceneURL = computed(() => main.sceneURL)
const sceneMobileMode = computed(() => main.sceneMode == 'mobile')

const sceneRef = ref()
const main = useMainStore()
const { setSceneLink, setSceneRef } = main

watchEffect(() => {
  localStorage.setItem('dark', `${mode.value}`)
})

function renderIcon(icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

const collapsed = ref(false)
const menuOptions = [
  {
    label: () =>
      h(
        RouterLink,
        {
          to: {
            name: 'basicSettings'
            // params: {
            //   lang: 'zh-CN'
            // }
          }
        },
        { default: () => '基础设置' }
      ),
    key: 'basicSettings',
    icon: renderIcon(Cog)
  },
  {
    label: () =>
      h(
        RouterLink,
        {
          to: {
            name: 'digitalHuman'
            // params: {
            //   lang: 'zh-CN'
            // }
          }
        },
        { default: () => '数字人播报' }
      ),
    key: 'digitalHuman',
    icon: renderIcon(PeopleOutline)
  },
  {
    label: () =>
      h(
        RouterLink,
        {
          to: {
            name: 'textToaudio'
            // params: {
            //   lang: 'zh-CN'
            // }
          }
        },
        { default: () => '文字语音互转' }
      ),
    key: 'textToaudio',
    icon: renderIcon(RepeatOutline)
  },
  {
    label: () =>
      h(
        RouterLink,
        {
          to: {
            name: 'message'
            // params: {
            //   lang: 'zh-CN'
            // }
          }
        },
        { default: () => '留言互动' }
      ),
    key: 'message',
    icon: renderIcon(ChatboxEllipses)
  },
  {
    label: () =>
      h(
        RouterLink,
        {
          to: {
            name: 'topicNavigation'
            // params: {
            //   lang: 'zh-CN'
            // }
          }
        },
        { default: () => '专题导航' }
      ),
    key: 'topicNavigation',
    icon: renderIcon(Layers)
  }
]
const handleUpdateValue = (value: string) => {
  console.log(value)
}

onMounted(() => {
  const sceneCode = params.m ? String(params.m) : 'KJ-t-3Y6dxgyehDk'
  main.setSceneCode(sceneCode)
  main.getSceneInfo()
  setSceneLink(`/page/spg.html?m=${main.sceneCode}`)
  setSceneRef(sceneRef.value)
})

const handleEditorSave = async () => {
  const data = main.getEditorData
  await editorSave(data)
  message.success('保存成功！')
}


</script>

<style lang="sass">
#app
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

.layoutContent
  position: relative
  padding: 0px
  height: calc(100vh - 83px)
  overflow: hidden

.app-wrap, .app-view
  position: absolute
  left: 0
  top: 0
  width: 100%
  height: 100%
  z-index: 10

.app-view
  z-index: 100
  pointer-events: none

  &.isTran
    pointer-events: all

.app-scene
  width: 100%
  height: 100%
  display: flex
  align-items: flex-start
  justify-content: center

.app-scene iframe
  width: 100%
  height: 100%

.required
  padding-left: 10px
  position: relative

  &:after
    content: " *"
    color: red
    position: absolute
    left: 0
</style>
