<script>
export default {
  name: "jsonEditor",
  model: {
    event: "input",
    prop: "value"
  },
  props: {
    value: {default: () => ({})}
  },
  data() {
    return {
      editor: null,
      fullscreen: false
    }
  },
  methods: {
    init() {
      const {JSONEditor} = window
      if (!this.editor && JSONEditor) {
        const {mode, search, mainMenuBar, navigationBar} = this.$attrs
        this.editor = new JSONEditor(this.$el, {
          modes: ['code', 'form', 'tree'],
          language: 'zh-CN', mode, search, mainMenuBar, navigationBar, statusBar: true,
          onChange: () => {
            this.$emit("input", this.editor.get())
          },
        }, this.value)
      } else setTimeout(() => this.init(), 500)
      const fullscreenBtn = document.querySelector(".fullscreenBtn")
      if (!fullscreenBtn) {
        const btn = document.createElement("div")
        btn.className = "fullscreenBtn el-icon-full-screen"
        btn.onclick = evt => {
          evt.stopPropagation()
          this.fullscreen = !this.fullscreen
        }
        this.$el.appendChild(btn)
      }
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.editor?.destroy()
  }
}
</script>

<template>
  <section class="jsoneditor" @contextmenu.stop :class="{fullscreen}"/>
</template>

<style scoped lang="scss">
.jsoneditor {
  position: relative;

  &.fullscreen {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 80vw;
    height: 80vh;
    z-index: 202403221146;
  }

  :deep(.ace-jsoneditor) {
    font-size: 14px !important;
  }

  :deep(.fullscreenBtn) {
    position: absolute;
    z-index: 202403221132;
    right: 6px;
    top: 0;
    height: 35px;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    &:hover {
      color: rgba(white, .6);
    }
  }
}
</style>