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

  props: {
    size: {
      type: [Number, String],
      default: 'medium',
      validator(val) {
        if (typeof val === 'string') {
          return ['large', 'medium', 'small', "mini"].includes(val);
        }
        return typeof val === 'number';
      }
    },
    shape: {
      type: String,
      default: 'circle',
      validator(val) {
        return ['circle', 'square'].includes(val);
      }
    },
    icon: String,
    src: String,
    alt: String,
    srcSet: String,
    error: Function,
    // 是否自动根据头像尺寸调整字体大小
    autoFixFontSize: {
      type: Boolean,
      default: true
    },
    fit: {
      type: String,
      default: 'cover'
    },
    // 头像是否需要交互
    isEdit: {
      type: Boolean,
      default: false
    },
    styles: {
      type: Object,
      default: () => {}
    },
    // 是否是登录状态
    isLogin: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      isImageExist: true,
      hasModal: false // 是否有交互遮罩
    };
  },

  computed: {
    avatarClass() {
      const { size, icon, shape, groupSize, hasModal, isLogin, src } = this;
      let classList = ['el-avatar'];
      
      if (groupSize) {
        // 头像组size large 对应 头像size medium的大小，以此类推
        const sizes = {
          large: 'large',
          medium: 'medium',
          small: 'small',
          mini: 'mini'
        }
        classList.push(`el-avatar--${sizes[this.groupSize]}`);
      } else if (size && typeof size === 'string') {
        classList.push(`el-avatar--${size}`);
      }

      if (icon) {
        classList.push('el-avatar--icon');
      }

      if (shape) {
        classList.push(`el-avatar--${shape}`);
      }

      if (hasModal) {
        classList.push('is-interactive')
      }

      if (isLogin && !src) {
        classList.push('is-login')
      }

      return classList.join(' ');
    },
    _avatarGroup() {
      let parent = this.$parent;
        while (parent) {
          if (parent.$options.componentName !== 'ElAvatarGroup') {
            parent = parent.$parent;
          } else {
            return parent;
          }
        }
        return false;
    },
    groupSize() {
      return this._avatarGroup.avatarGroupSize || (this.$ELEMENT || {}).size
    }
  },

  methods: {
    handleError() {
      const { error } = this;
      const errorFlag = error ? error() : undefined;
      if (errorFlag !== false) {
        this.isImageExist = false;
      }
    },

    renderAvatar() {
      const { icon, src, alt, isImageExist, srcSet, fit, size } = this;

      if (isImageExist && src) {
        return <img
          src={src}
          onError={this.handleError}
          alt={alt}
          srcSet={srcSet}
          style={{ 'object-fit': fit }}/>;
      }

      if (icon) {
        // 以大尺寸宽高64为基准
        return (<i style={typeof size === 'number' ? `transform: scale(${(size / 64).toFixed(3)};` : ''} class={icon} />);
      }

      if (this.$slots.default[0].tag === 'img') {
        return this.$slots.default
      } else {
        return <span class="el-avatar--text-wrap" ref="textWrap">{ this.$slots.default }</span>;
      }
    },

    handleOperate(bool) {
      if (this.isEdit) {
        this.hasModal = bool;
      }
    },

    handleClick() {
      this.$emit('avatarEdit', this.src)
    },

    autoFixFontSizeHandler() {
      if (!this.src && !this.icon) {
        this.$nextTick(() => {
          if (!this.$slots.default) {
            return;
          }
          const textWidth = this.$refs.textWrap.offsetWidth;
          const avatarWidth = typeof this.size === 'number' ? this.size : this.$refs.avatarWrap.clientWidth;
          const avatarHeight = this.$refs.avatarWrap.clientHeight;
          const scale = avatarWidth / 64
          if (!this.groupSize) {
            if (avatarWidth && scale < 1) {
              // this.$refs.avatarWrap.style.transform = `scale(${scale}) translateX(-50%)`
            } else {
              // this.$refs.avatarWrap.style.transform = ''
            }
          } else {
            switch(this.groupSize) {
              case 'large':  
                // this.$refs.avatarWrap.style.transform = `scale(1) translateX(-50%)`
                break
              case 'medium':
                // this.$refs.avatarWrap.style.transform = `scale(0.625) translateX(-50%)`
                break
              case 'small':
                // this.$refs.avatarWrap.style.transform = `scale(0.5) translateX(-50%)`;
                break
              case 'mini':
                // this.$refs.avatarWrap.style.transform = `scale(0.375) translateX(-50%)`;
                break
            }
            this.$refs.avatarWrap.style.lineHeight = avatarHeight + 'px';
          }
          
        })
      }
    }
  },

  render() {
    const { avatarClass, size, styles } = this;

    const sizeStyle = typeof size === 'number' ? {
      height: `${size}px`,
      width: `${size}px`,
      lineHeight: `${size}px`
    } : {};

    return (
      <span class={ avatarClass } style={[ sizeStyle, styles ]} ref="avatarWrap"
        onMouseenter={() => { this.handleOperate(true)}} onMouseleave={() => { this.handleOperate(false)}}>
        {
          this.renderAvatar()
        }
        <i class="el-icon-editor el-avatar--edit-icon" onClick={this.handleClick}></i>
      </span>
    );
  },

  mounted() {
    if (this.autoFixFontSize) {
      this.autoFixFontSizeHandler()
    }
    // this.handleClick()

  }
};
</script>
