<template>
  <div class="el-badge">
    <slot></slot>
    <transition name="el-zoom-in-center">
      <sup
        v-show="!hidden && (content || content === 0 || isDot || icon)"
        v-text="getlength(content)"
        class="el-badge__content"
        :style="icon ? 'background-color: white;padding:0;height:auto;line-height:1;' : ''"
        :class="[
          type ? 'is-dot--' + type : '',
          icon ?  icon : '',
          icon ? 'el-badge__icon': '',
          'is-' + site,
          {
            'is-fixed': $slots.default,
            'is-dot': isDot,
            'is-disabled': disabled
          }
        ]">
      </sup>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'ElBadge',

  props: {
    value: [String, Number],
    icon: {
      type:String,
    },
    max: {
      type: Number,
      default: 999,
      validator(val) {
        return val <= 999;
      }
    },
    isDot: Boolean,
    hidden: Boolean,
    type: {
      type: String,
      validator(val) {
        return ['success', 'warning', 'error', 'progress', 'info'].indexOf(val) > -1;
      }
    },
    disabled: Boolean,
    site: {
      type: String,
      default: 'rt'
    }
  },

  computed: {
    content() {
      if (this.isDot) return;

      const value = this.value;
      const max = this.max;

      if (typeof value === 'number' && typeof max === 'number') {
        return max < value ? `${max}+` : value;
      }

      return value;
    }
  },
  methods: {
    getlength(val) {
      return val ? this.filterStr(val.toString()) : val
      // eslint-disable-next-line no-control-regex
      // console.log(val.toString().replace(/[^\x00-\xff]/g, 'xx').length)
    },
    filterStr(str) { 
      let realLength = 0, len = str.length, charCode = -1
      for (let i = 0; i < len; i++) {
        charCode = str.charCodeAt(i)
        if (charCode >= 0 && charCode <= 128) realLength += 1
        else {
            realLength += 2
        }
        if (realLength > 4) { 
          return str.substring(0, i)
        }   
      }
      return str
    }
  }
};
</script>
