<template>
    <CfFlex class="material-view">
        <div ref="container" class="material-view-container" />
        <MaterialAdjuster ref="adjuster" class="material-view-sider" :name="matName" :textures="textures" :ignore-texture="editMode"
            @cancel="config.cancelCallback" @submit="config.submitCallback" />
    </CfFlex>
</template>
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, useTemplateRef } from 'vue';
import MaterialAdjuster from './MaterialAdjuster.vue';
import { useScene } from '../stores/sceneStore';
import CfFlex from './CfFlex.vue';
import { GetConfig } from '../lib/libOutputConfig';
import { useEvent } from '../stores/eventStore';
import { FromDeflateBase64 } from '../helpers/helper.material';

const scene = useScene();
const eventbus = useEvent();
const container = useTemplateRef('container');
const adjusterRef = useTemplateRef('adjuster');
const config = GetConfig();
const textures = ref<{name: string, src: string}[]>(Array.from(config.textures));
const matName = ref<string>();
const editMode = ref(false);

// 禁用右键菜单
document.addEventListener('contextmenu', (e) => e.preventDefault());
onMounted(async () => {
    scene.Initial(container.value);
    await HandleUpdateConfig();

    eventbus.Subscribe('submit', HandleUpload);
    eventbus.Subscribe('update-texture', HandleChangeTexture);
    eventbus.Subscribe('update-config', HandleUpdateConfig)
});

onBeforeUnmount(() => {
    eventbus.Unsubscribe('submit', HandleUpload);
    eventbus.Unsubscribe('update-texture', HandleChangeTexture);
    scene.Dispose();
});

function HandleUpload() {
    adjusterRef.value.Upload();
}

function HandleChangeTexture() {
    textures.value = Array.from(config.textures);
}

async function HandleUpdateConfig() {
    if (config.updateModel) {
        matName.value = config.updateModel.name;
        const json = FromDeflateBase64(config.updateModel.file);
        await scene.ImportMaterialAsync(json);
        editMode.value = true;
    }
    else { editMode.value = false; }
    if (config.textures) {
        textures.value = Array.from(config.textures);
        await scene.ChangeTextureFromUrlAsync(textures.value[0].src); // 这一行是保证首次Mount组件时纹理能够立刻刷新
    }
}

</script>

<style scoped lang="scss">
.material-view {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 0;
    margin: 0;
    overflow: hidden;

    &-container {
        flex: 3 1;
        height: 100%;
        box-sizing: border-box;
        overflow: hidden;
    }

    &-sider {
        flex: 1 1;
        overflow-y: auto;
        height: 100%;
        box-sizing: border-box;
    }
}
</style>