<template>
  <span class="x-icon" :class="classes" :style="styles" v-on="$listeners">
    <slot><component v-if="icon" :is="icon" :colors="colors"></component></slot>
  </span>
</template>

<script>
/**
 * 图标组件
 * @module XIcon
 */
const colors = ['primary', 'success', 'warning', 'danger'];

/**
 * 插槽
 * @member slots
 * @property {string} default 自定义图标内容
 */
export default {
  name: 'XIcon',
  /**
   * 属性参数
   * @member props
   * @property {string} [name] 图标名称，仅用用作css字体图标的样式名称
   * @property {string|number} [size] 图标尺寸，可选值：'default', 'large', 'small', 'mini'，数组表示像素
   * @property {string|string[]} [color] 颜色
   * @property {string|object|function} [icon] 图标，svg组件名称或组件对象
   */
  props: {
    name: {
      type: String
    },
    size: {
      type: [String, Number],
      default: 'default',
      validator(val) {
        if (typeof val === 'string') {
          return ['default', 'large', 'small', 'mini'].includes(val);
        }
        return val > 0;
      }
    },
    color: {
      type: [String, Array]
    },
    icon: [String, Object, Function]
  },
  computed: {
    colors() {
      const color = this.color;
      if (!color) return [];
      return Array.isArray(this.color) ? color : [color];
    },
    classes() {
      const cls = [];
      if (typeof this.name === 'string') {
        cls.push(this.name);
      }
      if (typeof this.size === 'string') {
        cls.push(`is-${this.size}`);
      }
      if (this.$listeners.click) {
        cls.push('is-pointer');
      }
      if (colors.includes(this.colors[0])) {
        cls.push(`is-${this.colors[0]}`);
      }
      return cls;
    },
    styles() {
      const style = {};
      if (typeof this.size === 'number') {
        const value = `${this.size}px`;
        Object.assign(style, {
          fontSize: value,
          width: value,
          height: value
        });
      }
      const color = this.colors[0];
      if (color && !colors.includes(color)) {
        style.color = color;
      }
      return style;
    }
  }
};
/**
 * 点击触发
 * @event click
 */
</script>
