<template>
  <component
    :is="tag"
    :class="[
      className,
      { 'es-pointer': Object.keys(event).length, 'es-icon_image': tag == 'img' }
    ]"
    :src="tag == 'img' ? url : ''"
    v-on="event"
    v-html="code"
  />
</template>
<script>
import util from 'eoss-ui/src/utils/util';
import { previewAdjunct } from 'eoss-ui/src/config/api.js';
export default {
  name: 'EsIcon',
  inheritAttrs: true,
  props: {
    preview: {
      type: String,
      default: `${previewAdjunct}?adjunctId=`
    },
    contents: [Object, String]
  },
  watch: {
    contents: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) {
          if (typeof val == 'string' && val) {
            if (
              val.indexOf('.jpge') > 1 ||
              val.indexOf('.jpg') > 1 ||
              val.indexOf('.gif') > 1 ||
              val.indexOf('.png') > 1 ||
              val.indexOf('data:image/jpge;base64') > -1 ||
              val.indexOf('data:image/jpg;base64') > -1 ||
              val.indexOf('data:image/gif;base64') > -1 ||
              val.indexOf('data:image/png;base64') > -1 ||
              util.startWith(val, ['http', 'https', '/'])
            ) {
              this.tag = 'img';
              this.url = val;
            } else {
              this.tag = 'i';
              if (this.unicode(val)) {
                this.code = '';
                this.className = val;
              } else if (this.isId(val)) {
                this.tag = 'img';
                let dochubConfig = sessionStorage.getItem('dochubConfig');
                if (!dochubConfig) {
                  this.url = this.preview + val;
                } else {
                  dochubConfig = JSON.parse(dochubConfig);
                  this.url = `${dochubConfig.downloadDocumentUrl}?documentId=${val}`;
                }
              } else {
                this.code = val;
                this.className = 'es-icon';
              }
            }
          } else {
            this.code = val.code;
            this.className = val.class || val.className;
            val.events && (this.event = val.events);
          }
        }
      }
    }
  },
  data() {
    return {
      tag: 'i',
      url: '',
      code: '',
      className: '',
      event: { click: this.clickd }
    };
  },
  created() {},
  methods: {
    clickd(e) {
      this.$emit('click', e);
    },
    unicode(res) {
      if (!res) {
        return false;
      }
      var reg = new RegExp(/^(es-|el-)\S+/, 'g');
      return res.match(reg) ? res.match(reg).length : 0;
    },
    isId(res) {
      if (!res) {
        return false;
      }
      var reg = new RegExp(/[a-z0-9]+-[a-z0-9]+-[a-z0-9]+-[a-z0-9]+\S+/, 'g');
      return res.match(reg) ? res.match(reg).length : 0;
    }
  }
};
</script>
