<template>
  <div ref="editor" class="ace-container">
    <div ref="ace" class="ace-editor"></div>
  </div>
</template>

<script>
import ace from 'ace-builds'

//在 webpack 环境中使用必须要导入
import "./webpack-resolver.js"

export default {
  name: "Editor",
  props: {
    // 是否自动换行
    wrap: {type: Boolean, default: true},
    // 代码模式
    mode: {type: String, default: ""},
    // 主题控制
    theme: {type: String, default: "monokai"},
    // 代码内容
    value: {type: String, default: ""},
    // 高度
    lines: {type: Number, default: 20},
    // 只读
    readOnly: {type: Boolean, default: false},
    // 是否弹窗打开
    isDialog: {type: Boolean, default: false},
  },
  data() {
    return {
      aceEditor: null,
    }
  },
  watch: {
    mode: {
      deep: true,
      handler(newVal, oldVal) {
        if (newVal) {
          this.handleModelPathChange(newVal)
        }
      }
    },
    value: {
      deep: true,
      handler(newVal, oldVal) {
        if (newVal) {
          this.aceEditor.setValue(newVal)
        }
      }
    },
    theme: {
      deep: true,
      handler(newVal, oldVal) {
        if (newVal) {
          this.handleThemePathChange(newVal)
        }
      }
    }
  },
  mounted() {
    this.initAceEdit()
  },
  methods: {
    // 初始化控件
    initAceEdit() {
      let maxLines = this.lines
      if (this.isDialog) {
        let editorH = this.$refs.editor.offsetHeight || 400
        maxLines = editorH / 17
      }

      this.aceEditor = ace.edit(this.$refs.ace, {
        maxLines: maxLines,
        minLines: maxLines,
        fontSize: 14, // 字号
        value: this.value,//初始显示内容
        theme: this.theme, // 主题
        mode: this.mode, // 语言模式
        wrap: this.wrap,
        tabSize: 4
      })
      // 激活自动提示
      this.aceEditor.setOptions({
        enableSnippets: true,
        enableLiveAutocompletion: true,
        enableBasicAutocompletion: true
      })
      this.aceEditor.setReadOnly(this.readOnly)
      this.aceEditor.getSession().on('change', this.change)
    },

    // 实时获取当前输入内容
    change() {
      this.$emit("change", this.aceEditor.getSession().getValue())
    },

    // 获取当前输入内容
    getValue() {
      return this.aceEditor.getSession().getValue()
    },

    // 如果有语言切换需求
    handleModelPathChange(modelPath) {
      this.aceEditor.getSession().setMode(modelPath)
    },
    // 如果有主题切换需求
    handleThemePathChange(ThemePath) {
      this.aceEditor.setTheme(ThemePath)
    },
    // 是否自动换行
    handleWrapChange(wrap) {
      this.aceEditor.getSession().setUseWrapMode(wrap)
    },
  }
}
</script>

<style scoped>
.ace-container {
  height: 100%;
}

.ace-editor--height {
  height: 100% !important;
}
</style>
