<template>
  <div v-highlight class="md-viewer">
    <VueShowdown :markdown="fileContent" />
  </div>
</template>
<script>
import utils from "@/utils.js";

export default {
  name: "MdView",
  props: {
    content: String,
    url: String,
  },
  data: function () {
    return {
      fileContent: null,
    };
  },
  created: function () {
    // 优先使用slot内容
    if (this.$slots && Object.keys(this.$slots).length > 0) {
      const slot = this.$slots.default
        ? this.$slots.default
        : this.$slots[Object.keys(this.$slots)[0]];
      if (slot && slot.length > 0 && slot[0].text) {
        // 因为md内容可能被格式化以后，每一行的开头有多个空格导致显示的格式错误，逐行去掉这些空格。
        this.fileContent = utils.trimEachLine(slot[0].text);
      }
    } else if (this.content) {
      // 其次，使用content属性
      this.fileContent = this.content;
    } else if (this.url) {
      // 再次，通过url属性来加载内容
      this.getContent();
    } else {
      this.fileContent = "没有内容可以显示.";
    }
  },
  methods: {
    getContent() {
      this.fileContent = "正在加载...";
      this.$http.get(this.url).then(
        (response) => {
          this.fileContent = response.body;
        },
        () => {
          this.fileContent = "内容加载失败.";
        }
      );
    },
  },
};
</script>
<style>
.md-viewer {
  margin: 20px 0 40px 0;
  font-size: initial;
}

pre > code {
  line-height: 20px;
  display: block;
}

code {
  background-color: #f9fafc;
  padding: 0 4px;
  border: 1px solid #eaeefb;
  border-radius: 4px;
  padding: 5px;
  margin: 0 5px;
}

code.hljs {
  border: none;
  border-radius: 0;
}

.md-viewer a:visited {
  color: #409eff;
}

.md-viewer table {
  width: 80%;
  border-top: 1px solid #ebeef5;
}

.md-viewer table > thead > tr > th,
.md-viewer table > tbody > tr > th {
  text-align: right;
  color: #999;
  font-weight: normal;
}

.md-viewer table > tbody > tr > th.group-th {
  text-align: left;
  background: #f9f9f9;
  font-weight: bold;
}

.md-viewer table > tbody > tr > th,
.md-viewer table > tbody > tr > td,
.md-viewer table > tfoot > tr > td,
.md-viewer table > thead > tr > th {
  border-bottom: 1px solid #ebeef5;
  padding: 10px;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}

.md-viewer table > tfoot > tr > td {
  padding: 5px 10px;
}
</style>