
<template>
  <div ref="container" class="monaco-editor" style="height: calc(100vh - 42px)" />
</template>

<script>
// import * as monaco from "monaco-editor";

import "monaco-editor/min/vs/loader.js";
import "monaco-editor/min/vs/editor/editor.main.nls.js";
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
// import "monaco-editor/esm/vs/basic-languages/mysql/mysql.contribution";
// import "monaco-editor/esm/vs/editor/contrib/suggest/suggestController.js";
// import "monaco-editor/esm/vs/editor/contrib/bracketMatching/bracketMatching.js";
// import "monaco-editor/esm/vs/editor/contrib/hover/hover.js";
import { isBase64 } from "../utils.js";
export default {
  name: "AcMonaco",
  inject: ["reload"],
  props: {
    opts: {
      type: Object,
      default() {
        return {};
      },
    },
    height: {
      type: Number,
      default: 300,
    },

    monacaValue: {
      type: String,
      default: "false",
    },
    onChange: {
      type: Function,
      default: new Function
    }
  },
  data() {
    return {
      isDiff: false,
      // 主要配置
      defaultOpts: {
        lineNumbersMinChars: 0,
        lineDecorationsWidth: 0,
        glyphMargin: false,
        value: "", // 编辑器的值
        wordWrap: "on",
        theme: "vs-dark", // 编辑器主题：vs, hc-black, or vs-dark，更多选择详见官网
        roundedSelection: false, // 右侧不显示编辑器预览框
        autoIndent: true, // 自动缩进
        quickSuggestions: true, // 快速搜索

        enableSplitViewResizing: false,
        scrollBeyondLastLine: false,
        quickSuggestions: false, //智能提示
        renderLineHighlight: false, //选中行外部边框
        lineHeight: 22

      },

      // 编辑器对象
      monacoEditor: {},
      oldValue: "123123/n\n",
      newValue: "123121311111111",
    };
  },
  watch: {
    opts: {

    },
    monacaValue: {
      handler(value) {
        if(this.isDiff) return ;
        const editor = this.monacoEditor
        const output = isBase64(value)
          ? Buffer.from(value, "base64").toString("utf8")
          : value;
        const positions = this.monacoEditor.getPosition()
        this.monacoEditor.setValue(output);
        this.monacoEditor.setPosition({
          lineNumber: positions.lineNumber,
          column: positions.column
        })
      },
      deep: true
    },
    // monacaValue(value) {
    //   alert(value)
    //   console.log(isBase64);
    //   const output = isBase64(value)
    //     ? Buffer.from(value, "base64").toString("utf8")
    //     : value;
    //   this.monacoEditor.setValue(output);
    // },
  },
  beforeDestroy() {
    document.removeEventListener("keyup", this.onSaveHandler);
  },
  mounted() {
    document.addEventListener("keyup", this.onSaveHandler, false);

    this.init();
  },
  methods: {
    init() {

      // 初始化container的内容，销毁之前生成的编辑器
      this.$refs.container.innerHTML = "";
      // 生成编辑器配置
      const editorOptions = Object.assign(this.defaultOpts, this.opts);
      if (!this.isDiff) {
        // 初始化编辑器实例
        this.monacoEditor = monaco.editor.create(
          this.$refs.container,
          editorOptions
        );
        this.monacoEditor.onDidChangeModelContent(
          event => {
            this.$emit("onChange", this.monacoEditor.getValue())
          },
        );

        // 编辑器内容发生改变时触发
      } else {
        editorOptions.readOnly = true;
        editorOptions.language = "javascript";
        // editorOptions.inlineHints = true;
        // 初始化编辑器实例
        this.monacoDiffInstance = monaco.editor.createDiffEditor(
          this.$refs.container,
          editorOptions
        );
        this.monacoDiffInstance.setModel({
          original: monaco.editor.createModel(
            this.oldValue,
            editorOptions.language
          ),
          modified: monaco.editor.createModel(
            this.newValue,
            editorOptions.language
          ),
        });
      }

      if (this.monacaValue) {
        const output = isBase64(this.monacaValue)
          ? Buffer.from(value, "base64").toString("utf8")
          : this.monacaValue;
        this.monacoEditor.setValue(output);
      }
    },
    upDateDiff(val) {
      this.monacoDiffInstance.updateOptions({
        renderSideBySide: !val,
      });
    },
    onSaveHandler(e) {
      if(this.isDiff) return;
      if (
        (window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) &&
        e.keyCode === 83
      ) {
        e.preventDefault();
        this.$emit("handleSave", this.monacoEditor.getValue());
      }
      this.$emit("handleSave", this.monacoEditor.getValue());
    },
    // 供父组件调用手动获取值
    getVal() {
      return this.monacoEditor.getValue();
    },
    setLanguage(lang) {
      setTimeout(() => {
        if (monaco.editor.setModelLanguage) {
          monaco.editor.setModelLanguage(this.monacoEditor.getModel(), lang)
        }
      }), 300;
      // alert(JSON.stringify(this.monacoEditor.getModel()))
    },
    updateOptions(opts) {
      const editorOptions = Object.assign(this.defaultOpts, opts);
      this.monacoEditor.updateOptions(editorOptions);
    },
    setTheme(theme) {
      monaco.editor.setTheme(theme);
    },
    setDiff(oldContent, newContent) {
      this.oldValue = isBase64(oldContent) ? Buffer.from(oldContent, "base64").toString("utf8") : oldContent;
      this.newValue = newContent;
      this.isDiff = true;
      this.init();
    },
    setCloseDiff() {
      if (this.isDiff) {
        this.isDiff = false;
        this.init();
      }
    },
  },
};
</script>

<style>
.margin-view-overlays {
  background: #f5f5f5;
}

/* .view-lines {
  padding-left: 10px;
} */
</style>
