<template>
  <div id="vditor" style="min-height: 192px;"></div>
</template>

<script>
import Vditor from 'vditor'
import 'vditor/dist/index.css'

export default {
  name: 'VditorEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      vditor: null
    }
  },
  mounted() {
    const config = {
      value: this.value,
      height: 360,
      cache: { enable: false },
      theme: 'dark',
      preview: {
        theme: {
          current: 'dark'
        }
      },
      after: () => {
        this.vditor.setValue(this.value || '')
      },
      input: (val) => {
        this.$emit('input', val)
      }
    };
    if (this.readonly) {
      config.toolbar = []; // 不显示工具栏
      config.editable = false;
    } else {
      config.toolbarConfig = { pin: true };
      config.editable = true;
    }
    this.vditor = new Vditor('vditor', config);
    if (this.readonly) {
      this.vditor.vditor.disabled()
    }
  },
  watch: {
    value(val) {
      if (this.vditor && val !== this.vditor.getValue()) {
        this.vditor.setValue(val || '')
        // 只读模式下内容变化时重新渲染mermaid
        if (this.readonly && window.VditorPreview && typeof window.VditorPreview.mermaidRender === 'function') {
          this.$nextTick(() => {
            window.VditorPreview.mermaidRender(document);
          });
        }
      }
    }
  }
}
</script>

<style scoped>
#vditor {
  border: 1px solid #e4e7ed;
  color: white;
  border-radius: 4px;
}
</style>
