<template>
  <VAceEditor
    ref="editor"
    v-model:value="showText"
    style="width:100%;height:150px"
    lang="json"
    theme="chrome"
    @blur="handleInput"
    @init="initEditor"
  />
</template>

<script>
import { VAceEditor } from 'vue3-ace-editor'
import { reactive, toRefs } from 'vue'
import 'ace-builds/src-noconflict/mode-json.js'
import 'ace-builds/src-noconflict/theme-chrome.js'
import 'ace-builds/src-noconflict/ext-language_tools.js'
import { isArray } from '@/utils/is.js'
export default {
  name: 'JsonEditor',
  components: { VAceEditor },
  props: {
    jsonStr: {
      type: [Array, String],
      default: () => [{ label: '字段名', value: '字段值' }]
    }
  },
  emits: ['json-change'],
  setup(props, { emit }) {
    const data = reactive({
      options: {
        tabSize: 2,
        fontSize: 13
      },
      readOnly: false,
      showText: '',
      showJson: isArray(props.jsonStr) ? props.jsonStr : JSON.parse(props.jsonStr)
    })

    const initEditor = () => {
      data.showText = JSON.stringify(data.showJson, null, 2)
    }

    function handleInput() {
      emit('json-change', data.showText)
    }
    return {
      ...toRefs(data),
      initEditor,
      handleInput
    }
  }
}

</script>
<style scoped lang='scss'>
</style>
