<template>
  <div class="common-editor">
    <textarea ref="textarea" v-model="value" :placeholder="placeholder"></textarea>
  </div>
</template>

<script>
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/base16-dark.css'
import 'codemirror/theme/blackboard.css'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/javascript-hint'
import 'codemirror/addon/hint/sql-hint'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/vue/vue'
import 'codemirror/mode/markdown/markdown'
import 'codemirror/mode/sql/sql'
import 'codemirror/mode/php/php'
import 'codemirror/mode/python/python'
import 'codemirror/mode/shell/shell'
import 'codemirror/mode/powershell/powershell'
import 'codemirror/addon/display/placeholder.js'

import CodeMirror from 'codemirror/lib/codemirror'

/**
 * 一个代码编辑器,支持多种语言
 * 该组件已经全局注册,可以直接使用
 * - 示例
 *
 * ```vue
 * <ed-code-editor v-model="value"></ed-code-editor>
 * ```
 */

export default {
  name: 'EdCodeEditor',
  props: {
    // 编辑器的值, 可以通过 v-model 双向绑定
    value: {
      type: String,
      default: ''
    },
    // 编辑器的占位符
    placeholder: {
      type: String,
      default: ''
    },
    // 编辑器的语言
    language: {
      type: String,
      default: 'javascript'
    }
  },
  data() {
    return {
      CodeEditor: false,
      code: '',
      coder: null,
      mode: 'javascript',
      theme: 'default',
      modes: [
        {value: 'text/x-vue', label: 'Vue'},
        {value: 'text/javascript', label: 'Javascript'},
        {value: 'text/css', label: 'Css'},
        {value: 'x-java', label: 'Java'},
        {value: 'x-python', label: 'Python'},
        {value: 'x-sql', label: 'SQL'},
        {value: 'x-shell', label: 'Shell'},
        {value: 'x-powershell', label: 'PowerShell'},
        {value: 'x-php', label: 'PHP'}
      ]
    }
  },
  watch: {
    language: {
      handler(language) {
        this.getCoder().then(() => {
          // 尝试从父容器获取语法类型
          if (language) {
            // 获取具体的语法类型对象
            const modeObj = this.getLanguage(language)
            // 判断父容器传入的语法是否被支持
            if (modeObj) {
              this.mode = modeObj.label
              this.coder.setOption('mode', `text/${modeObj.value}`)
            }
          }
        })
      },
      immediate: true
    }
  },
  computed: {
    coderOptions() {
      return {
        autoRefresh: true,
        line: true,
        mode: 'application/json', // json数据高亮
        theme: 'blackboard', //设置主题 记得引入对应主题才有显示   import 'codemirror/theme/blackboard.css'
        tabSize: 1,
        lineNumbers: true, // 显示行号
        cursorHeight: 0.8, //光标高度，默认是1
        autoCloseBrackets: true,
        matchBrackets: true, // 括号匹配
        lineWrapping: 'wrap', // 文字过长时，是换行(wrap)还是滚动(scroll),默认是滚动
        showCursorWhenSelecting: true, // 文本选中时显示光标
        smartIndent: true, // 智能缩进
        completeSingle: false // 当匹配只有一项的时候是否自动补全
      }
    }
  },
  mounted() {
    // 初始化
    this.initialize()
  },
  methods: {
    /**
     * @public
     * 刷新编辑器
     */
    refresh() {
      this.coder.refresh()
    },
    // 初始化
    initialize() {
      // 初始化编辑器实例，传入需要被实例化的文本域对象和默认配置
      this.coder = CodeMirror.fromTextArea(
        this.$refs.textarea,
        this.coderOptions
      )
      this.coder.refresh()
      this.coder.on('inputRead', () => {
        this.coder.showHint()
      })
      // 编辑器赋值
      if (this.value || this.code) {
        this.setCodeContent(this.value || this.code)
      } else {
        this.coder.setValue('')
      }
      // 支持双向绑定
      this.coder.on('change', (coder) => {
        this.code = coder.getValue()
        if (this.$emit) {
          this.$emit('input', this.code)
          this.$emit('change', this.code)
        }
      })
    },
    /**
     * @private
     * @param val
     * 设置编辑器内容
     */
    setCodeContent(val) {
      setTimeout(() => {
        if (!val) {
          this.coder.setValue('')
        } else {
          this.coder.setValue(val)
        }
      }, 300)
    },
    /**
     * @private
     * @returns {Promise<unknown>}
     * 获取编辑器实例
     */
    getCoder() {
      const that = this
      return new Promise((resolve) => {
        (function get() {
          if (that.coder) {
            resolve(that.coder)
          } else {
            setTimeout(get, 10)
          }
        })()
      })
    },
    /**
     * @private
     * @param language
     * @returns {{label: string, value: string} | {label: string, value: string} | {label: string, value: string} | {label: string, value: string} | {label: string, value: string}}
     * 获取语法类型
     */
    getLanguage(language) {
      // 在支持的语法类型列表中寻找传入的语法类型
      return this.modes.find((mode) => {
        // 所有的值都忽略大小写，方便比较
        const currentLanguage = language.toLowerCase()
        const currentLabel = mode.label.toLowerCase()
        const currentValue = mode.value.toLowerCase()

        // 由于真实值可能不规范，例如 java 的真实值是 x-java ，所以讲 value 和 label 同时和传入语法进行比较
        return (
          currentLabel === currentLanguage || currentValue === currentLanguage
        )
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.common-editor {
  width: 100%;
  height: 100%;

  .CodeMirror {
    // color: #ccc;
    direction: ltr;
    line-height: 20px;
    width: 100%;
    height: 100%;
    // background-color: #000;
  }

  .CodeMirror-hints {
    z-index: 9999 !important;
  }

  .custom-class .CodeMirror {
    width: 100%;
  }
}

.CodeMirror-hints {
  z-index: 1000;
}

.CodeMirror pre.CodeMirror-placeholder {
  color: #999;
  font-size: 0.5rem;
}
</style>
