<template>
  <codemirror
    v-model="item"
    :options="cmOption"
    class="code-mirror"
    :style="styleObj"
    @ready="onCmReady"
    @focus="onCmFocus"
    @input="onCmCodeChange"
    ref="myCmGenerate"></codemirror>
</template>

<script>
import { codemirror } from 'vue-codemirror'
import 'codemirror/mode/javascript/javascript.js'
import './setting.js'
// https://github.com/surmon-china/vue-codemirror/tree/v4.0.6
export default {
  components: {
    codemirror
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'sql' // 目前只有 sql/go/js 如果需要配置其他语言，需要在 setting.js 中配置 更多看官方文档
    },
    styleObj: {
      type: Object,
      default: () => {
        return { fontSize: '16px' }
      }
    },
    theme: {
      type: String,
      default: 'dracula'
    },
  },
  watch: {},
  data () {
    return {
      item: this.value,
      cmOption: {
        autoCloseBrackets: true,
        extraKeys: { Ctrl: 'autocomplete' },
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
        hintOptions: { completeSingle: false },
        keyMap: 'sublime',
        line: true,
        lineNumbers: true,
        matchBrackets: true,
        mode: { name: this.mode, json: true },
        readOnly: this.readonly ? 'nocursor' : undefined,
        showCursorWhenSelecting: true,
        styleActiveLine: true,
        styleSelectedText: true,
        tabSize: 2,
        theme: this.theme,
      }
    }
  },
  methods: {
    onCmReady () {
    },
    onCmFocus (instance, event) {
      // console.log(instance)
      // console.log(event)
    },
    onCmCodeChange (instance, _obj) {
      this.$emit('input', instance)
      // console.log(instance)
      // console.log(_obj)
    }
  }
}
</script>
<style lang="less" scoped>
.CodeMirror-scroll {
  overflow: scroll !important;
  margin-bottom: 0;
  margin-right: 0;
  padding-bottom: 0;
  height: 100%;
  outline: none;
  position: relative;
  border: 1px solid #dddddd;
}

@font-face {
  font-family: 'JetBrains Mono';
  src: url('@vue2-client/assets/ttf/JetBrainsMono-Light.woff2') format('woff2'), /* 字体文件路径和格式 */ url('@vue2-client/assets/ttf/JetBrainsMono-Light.woff2') format('woff');
}

:deep(.CodeMirror) {
  height: 100%;
}

.code-mirror {
  height: 100%;
  line-height: 150%;
  text-align: left;
  font-family: "JetBrains Mono", serif !important;
}

:deep(.CodeMirror-line), :deep(.CodeMirror-line-like) {
  font-family: "JetBrains Mono", serif !important;
}

</style>
