<template>
    <div ref="editorContainer" class="editor-container"></div>
</template>

<script>
import * as monaco from 'monaco-editor';

export default {
    name: 'codeEditor',
    props: {
        modelValue: {
            type: String,
            required: true,
        },
        language:{
            type:String,
            default:"json"
        },
        readOnly:{
            type:Boolean,
            default:false,
        },
        theme:{
            type:String,
            default:"vs-dark"
        }

    },
    emits: ['update:modelValue'],
    setup(){
        return {
            editor:null,
            editCode:"",
        }
    },  
    watch:{
        modelValue(val){
            
            if(val != this.editCode){
                this.editCode = val;
                this.editor.setValue(val)
            }
        }
    },
    mounted() {

        // this.editCode = this.modelValue || '{}'
        // 初始化 Monaco Editor
        this.editor = monaco.editor.create(this.$refs.editorContainer, {
            value:'{}',
            fontSize:16,
            language: this.language, // 'css' | 'html' | 'json' | 'typescript' | 'editorWorkerService', sql
            theme: this.theme, // 可选主题：'vs', 'vs-dark', 'hc-black'
            automaticLayout: true,
            minimap: { enabled: false },
            readOnly:this.readOnly,
        });

        if(this.modelValue){
            this.editCode = this.modelValue;
            this.editor.setValue(this.modelValue)

        }

        // 监听内容变化并更新父组件
        this.editor.onDidChangeModelContent(() => {
            const newValue = this.editor.getValue();
            this.editCode = newValue;
            this.$emit('update:modelValue', newValue);
        });
    },
    beforeUnmount() {
        if (this.editor) {
            this.editor.dispose();
        }
    },
};
</script>

<style lang="scss" scoped>
.editor-container {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    border-radius: 8px;
    overflow: hidden;
    /* width: 100%;
    height: 100%; */
}
</style>