<template>
  <view class="xd-image-icon" v-if="loaded" @click="handleClick" :style="getStyle">
    <image
      class="xd-image-icon__bg"
      :class="{gray: isGray}"
      :src="src"
      mode="aspectFit"
    ></image>
  </view>
</template>

<script>

  /**
   * XdImageIcon 全局Ui
   * @description 图片作为icon插件
   * @tutorial
   * @property {Number} size        元宝被放大倍数，值为0.1 - 2 之间， 默认值为0.5
   * @property {String} src         图片地址(本地图片或者base64)
   * @event {Function} click|tap    点击元宝事件
   */

  export default {
    name: "XdImage",
    props:{
      /**
       * @description 放大倍数 0.005 - 2 直接
       * @type number
       */
      size: {
        type: Number|String,
        default: 0.5,
      },

      src: {
        type: String,
        required: true
      },

      isGray: {
        type: Boolean,
        default: false
      }
    },
    data(){
      return {
        height: 0,
        width: 0,
        loaded: false
      }
    },
    computed:{
      getStyle(){
        let size = this.size;
        if (this.$xdUniHelper.checkVarType(size) === 'string') {
          try {
            size = Number(size);
          }catch (e) {
            size = 1;
          }
        }
        if (size < 0.005) size = 0.005;
        if (size > 2) size = 2;
        return `height:${this.height * size}rpx; width: ${this.width * size}rpx;`;
      }
    },
    created(){
      uni.getImageInfo({
        src: this.src,
        success: (image) => {
          this.height = image.height;
          this.width = image.width;
          this.loaded = true;
        },
        fail: () => {
          this.loaded = true;
          console.error('图片地址无效')
        }
      });

    },
    methods:{
      handleClick(e){
        this.$emit('click',e);
        this.$emit('tap', e);
      }
    }
  }
</script>

<style scoped lang="less">
  .xd-image-icon {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .xd-image-icon__bg {
    width: 100%;
    height: 100%;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: left top;
  }

  .gray {
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: gray;
  }
</style>
