<template>
  <div class="vtj-setting-panel vtj-styles">
    <div class="vtj-styles__switch">
      代码模式 <ElSwitch size="small" v-model="codeMode"></ElSwitch>
    </div>

    <SubPanel class="vtj-styles__code" title="JSON" :body-padding="false">
      <CodeEditor
        ref="codeEditor"
        :model-value="styleJson"
        height="100%"
        lang="json"
        :dark="false"
        @blur="onCodeChange"></CodeEditor>
    </SubPanel>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { ElSwitch, ElMessage } from 'element-plus';
import { SubPanel, CodeEditor } from '@vtj/engine';
import { useSelected } from '../hooks/useDesigner';

const codeMode = ref(true);
const codeEditor = ref();

const { selected } = useSelected();

const node = computed(() => {
  return selected.value?.node;
});

const styleJson = computed(() => {
  return JSON.stringify(node.value?.style || {}, null, 2);
});

const onCodeChange = () => {
  const editor = codeEditor.value?.getEditor();
  if (editor) {
    const value = editor.getValue();
    try {
      const json = JSON.parse(value);
      node.value?.update({
        name: node.value.name,
        style: json
      });
    } catch (e: any) {
      ElMessage.warning({
        message: e?.message || e
      });
    }
  }
};
</script>
