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

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({
    type: 'JSFunction',
    value: '(function(){\r\n\r\n})'
  })
});

const codeEditor = ref();

const textValue = ref(props.modelValue.value);
const dialogVisible = ref(false);

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

const handleSubmit = () => {
  const editor = codeEditor.value?.getEditor();
  if (editor) {
    const content = editor.getValue();
    const js: JSFunction = {
      type: 'JSFunction',
      value: content
    };
    textValue.value = content;
    emit('change', js);
    dialogVisible.value = false;
  }
};
const openDialog = () => {
  dialogVisible.value = true;
};
</script>
