<template>
  <div class="vtj-json-setter">
    <ElInput readonly @focus="openDialog" v-model="textValue" v-bind="$attrs">
      <template #prepend>
        <span @click="openDialog">JSON</span>
      </template>
    </ElInput>
    <Dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      title="JSON"
      width="60%"
      height="60%"
      cancel
      submit
      @submit="handleSubmit">
      <CodeEditor
        ref="codeEditor"
        height="100%"
        lang="json"
        :model-value="textValue"></CodeEditor>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { ElInput, ElMessage } from 'element-plus';
import CodeEditor from '../parts/CodeEditor.vue';
import Dialog from '../parts/Dialog.vue';
import { ref } from 'vue';
import { JSONValue } from '@vtj/engine';
export interface Props {
  modelValue?: JSONValue;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: ''
});

const codeEditor = ref();

const textValue = ref(JSON.stringify(props.modelValue, null, 2));
const dialogVisible = ref(false);

const emit = defineEmits(['change']);

const handleSubmit = () => {
  const editor = codeEditor.value?.getEditor();
  if (editor) {
    const content = editor.getValue();
    try {
      textValue.value = content;
      const json = JSON.parse(content);
      emit('change', json);
      dialogVisible.value = false;
    } catch (e: any) {
      ElMessage.warning({
        message: e?.message || e
      });
    }
  }
};
const openDialog = () => {
  dialogVisible.value = true;
};
</script>
