<template>
  <div class="pre">
    <template>
      <code class="sv-code sv-code-javascript" v-if="language === 'javascript'">
        <pre ref="codeRef" class="sv-code-pre">
          <slot></slot>
        </pre>
      </code>
       <code class="sv-code sv-code-html" ref="codeRef" v-else>
         <slot></slot>
       </code>
     </template>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'svCode',
    data () {
      return {
        keywords: ['var', 'let', 'const', 'this', 'import', 'from', 'export', 'default', 'module', 'return', 'true', 'false']
      }
    },
    props: {
      language: {
        type: String,
        default: 'text'
      }
    },
    methods: {
      removeExtraSpace (str) {
        return str
//        let result = str.trim() // 去掉前面空格
//        let startSpaceLength = str.length - result.length - 1 // 得到开始空格数量
//        let regExp = new RegExp(`\\s{4}`, 'gm')
//        console.log(startSpaceLength)
//        console.log(str.replace(regExp, '@'))
//        return str.replace(regExp, '')
      },
      addWrap (str) {
        return str.replace(/\n/img, `<br/>`)
      },
      highlightSyntax (str) {
        //高亮字符串
        let strings = str.match(/['|"]\S+['|"]/gm)
        if (strings && strings.length > 0) {
          strings.map(string => {
            str = str.replace(string, `<span class="string">${string}</span>`)
          })
        }

        // 高亮关键字
        this.keywords.map(keyword => {
          str = str.replace(keyword, `<span class="keyword">${keyword}</span>`)
        })
        return str
      }
    },
    mounted () {
      let $code = this.$refs.codeRef

      if ($code) {
        let str = $code.innerHTML
        let res = this.removeExtraSpace(str)

        if (this.language === 'javascript') {
          res = this.highlightSyntax(res)
          res = this.addWrap(res)
        }

        if (this.language === 'html') {

        }
        $code.innerHTML = res
      }

    }
  }
</script>

<style lang="scss" rel="stylesheet/scss">
  .pre{
    margin:0;
    padding:0;
    background-color: #f8f8f8;
    &:not(:first-child){
      margin-top: 10px;
    }
    .sv-code{
      display: block;
      overflow:auto;
      padding: 20px;
      color:#333;
      &.sv-code-javascript{
        .sv-code-pre{
          display: inline;;
        }
        .keyword{
          color: #a71d5d;
        }
        .string{
          color: #df5000;
        }
      }
    }
  }
</style>
