<template>
    <Password />
    <LoadingLogo :thumb="true" />
    <div class="ui-view-layout" :class="{ show: show }">
        <div class="scene" ref="scene$"></div>
        <!-- <template v-show="sceneUi"> -->
        <div>
            <UiTags />
            <Information />
            <BottomControl />
        </div>
        <!-- </template> -->
    </div>
    <DesignOption />
</template>

<script setup>
import { useMusicPlayer } from '@/utils/sound'
const musicPlayer = useMusicPlayer()
import UiTags from '@/components/Tags'
import DesignOption from './DesignOption'
import Information from '@/components/Information'

import BottomControl from '@/components/Controls/BottomControl'
import Password from '@/components/shared/Password.vue'
import LoadingLogo from '@/components/shared/Loading.vue'
import { createApp } from '@/app'
import { listenMessage } from '@/utils/messageHandler'
import {Dialog} from '@/global_components'


import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useApp, getApp } from '@/app'
import browser from '@/utils/browser'
import { useI18n, getLocale } from '@/i18n'
const { t } = useI18n({ useScope: 'global' })



const autoPlayMedia = player => {
    function onclick() {
        window.parent.postMessage(
            {
                source: "qjkankan",
                event: "autoPlayBgm",
                params: {
                    status: true,
                },
            },
            "*"
        );
        $player.removeEventListener('click', onclick)
        $player.removeEventListener('touchstart', onclick)
    }
    const $player = document.querySelector('.player')
    $player.addEventListener('click', onclick)
    $player.addEventListener('touchstart', onclick)
}

const store = useStore()
const show = ref(false)
const scene$ = ref(null)

const sceneUI = computed(() => store.getters['sceneUI'])

listenMessage()

onMounted(() => {
    const app = createApp({
        num: browser.getURLParam('m'),
        dom: scene$.value,
        lang: getLocale(),
        langs: {
            en: {
                'model.enter': t('model.enter'),
            },
        },
        useShortcutKeys: true,
    })
    app.use("MinMap", { theme: { camera_fillStyle: "#0076f6" } });
    app.use('Tag')
    app.use('TourPlayer')
    app.Scene.lock()
    app.Scene.on('ready', () => {
        show.value = true
    })
    app.Scene.on('error', data => {
        console.error(data)
        switch (data.code) {
            case 5033:
                window.location.replace(`/5033.html?m=` + browser.getURLParam('m'))
                break
            case 5034:
                window.location.replace(`/5034.html?m=` + browser.getURLParam('m'))
                break
            case 5009:
                window.location.replace(`/5034.html?m=` + browser.getURLParam('m'))
                break
            case 5005:
                Dialog.toast({
                    content: t('guide.no_scene'),
                    type: 'error',
                })
                break
        }
    })
    app.Scene.on('loaded', pano => {
        store.commit('setFloorId', pano.floorIndex)
        useMusicPlayer()
        let music = store.getters['scene/musicURL']
        window.parent.postMessage(
            {
                source: "qjkankan",
                event: "fdkkBgmLink",
                params: {
                    music,
                },
            },
            "*"
        );
        autoPlayMedia()
    })
    app.store.on('tags', tags => {
        store.commit('tag/load', tags)
    })
    app.store.on('metadata', metadata => {
        store.commit('scene/load', metadata)
        console.log(metadata, 'metadata');
        if (!metadata.controls.showMap) {
            app.MinMap.hide(true)
        }
    })
    app.Scene.on('panorama.videorenderer.resumerender', () => {
        console.log(1111111);
        window.parent.postMessage(
            {
                source: "qjkankan",
                event: "togglefdkkBGM",
                params: {
                    paly: false,
                },
            },
            "*"
        );

        window.parent.postMessage(
            {
                source: "qjkankan",
                event: "toggleBgmStatus",
                params: {
                    status: false,
                },
            },
            "*"
        );
    })

    app.Scene.on('panorama.videorenderer.suspendrender', async () => {
        let player = await getApp().TourManager.player
        if (!player.isPlaying) {
            // musicPlayer.resume()
            window.parent.postMessage(
                {
                    source: "qjkankan",
                    event: "togglefdkkBGM",
                    params: {
                        paly: true,
                    },
                },
                "*"
            );
            window.parent.postMessage(
                {
                    source: "qjkankan",
                    event: "toggleBgmStatus",
                    params: {
                        status: true,
                    },
                },
                "*"
            );
        }
    })
    app.Camera.on('mode.beforeChange', ({ fromMode, toMode, floorIndex }) => {
        if (fromMode) {
            store.commit('setFlying', true)
        }
    })
    app.Camera.on('mode.afterChange', ({ toMode, floorIndex }) => {
        store.commit('setFlying', false)
    })
    app.Camera.on('flying.started', pano => {
        store.commit('setFlying', true)
    })
    app.Camera.on('flying.ended', ({ targetPano }) => {
        store.commit('setFlying', false)
        store.commit('setPanoId', targetPano.id)
    })
    app.TourManager.on('loaded', async tour => {
        let tours = JSON.parse(
            JSON.stringify(app.TourManager.tours, (key, val) => {
                if (key === 'audio') {
                    return null
                } else {
                    return val
                }
            })
        )
        store.commit('tour/setData', {
            tours: tours,
        })

        window.parent.postMessage(
            {
                source: "qjkankan",
                event: "toursList",
                params: {
                    tours,
                },
            },
            "*"
        );

        store.commit('tour/setBackUp', {
            tours: JSON.parse(
                JSON.stringify(app.TourManager.tours, (key, val) => {
                    if (key === 'audio') {
                        return null
                    } else {
                        return val
                    }
                })
            ),
        })
    })
    app.store.on('floorcad', floor => store.commit('scene/loadFloorData', floor))
    app.store.on('flooruser', floor => store.commit('scene/loadFloorData', floor)) //4.7以后新楼层方式
    app.render()
})
</script>
