<template>
  <div :style="wrapStyle">
    <textarea ref="mycode" v-model="code" @refresh="refreshValue"></textarea>
  </div>
</template>

<script>
import { iscriptString } from "../../assets/js/chartExample.js";
// 核心样式
import "codemirror/lib/codemirror.css";
// 引入主题后还需要在 options 中指定主题才会生效

// 需要引入具体的语法高亮库才会有对应的语法高亮效果
import "codemirror/mode/javascript/javascript.js";

// require active-line.js
import "codemirror/addon/selection/active-line.js";

let CodeMirror = require("codemirror/lib/codemirror");

export default {
  name: "codeMirror",
  data() {
    return {
      editor: null,
      options: {
        mode: "javascript",
        tabSize: 0, // 缩进格式
        lineNumbers: true, // 显示行号
        // autofocus: true, //初始化时自动获取焦点
        autoRefresh: true,
      },
    };
  },

  methods: {
    // 获取编辑器的值
    getEditor() {
      return this.editor.doc.getValue();
    },
    // 将值传给父组件去更新
    setEditor() {
      this.$emit("setEditor", iscriptString(this.typeChart));
      return this.editor.doc.setValue(iscriptString(this.typeChart));
    },
    // 传值进来设置
    setCodeEditor(val) {
      this.editor.doc.setValue(val);
      setTimeout(() => {
        this.editor.refresh();
      }, 100);
    },
    undo() {
      // 判断是否与原来的代码一致，一致就操作
      let chartCode = this.code;
      if (chartCode !== this.getEditor()) {
        this.editor.doc.undo();
      }
    },
    redo() {
      this.editor.doc.redo();
    },
    refresh() {
      // return this.editor.refresh();
      setTimeout(() => {
        this.editor.refresh();
      }, 1);
    },
    refreshValue() {
      alert();
    },

    _initEditor() {
      if (!this.editor) {
        this.editor = CodeMirror.fromTextArea(this.$refs.mycode, this.options);
      }
      this.editor.setValue(this.value || this.code || '');
      this.editor.setSize("auto", this.editorHeight);
    },
  },
  mounted() {
    this.$nextTick(() => {
      this._initEditor();
    });
  },
  watch: {
    editorHeight(){
     this.editor.setSize("auto",this.editorHeight)
    },
    code() {
      this.$nextTick(() => {
        this._initEditor();
      });
    },
    wrapStyle() {
      setTimeout(() => {
        this.refresh();
      }, 100);
    },
  },
  computed: {
    wrapStyle() {
      return { fontSize: this.fontSize + "px" };
    },
  },
  props: {
    fontSize: {
      type: String,
    },
    // 内部真实的内容
    code: {
      type: String,
      default: "",
    },
    // 图表类型
    typeChart: {
      type: String,
      default: "",
    },
    // 脚本编辑器高度
    editorHeight: {
      type: String,
      default: "600px",
    },
  },
};
</script>

<style>
