<template>
  <view
    class="xd-image"
    @click.shop="handleClick"
    :style="{
      width: uiWidth + 'rpx',
      height: uiHeight + 'rpx',
      backgroundColor: bgc,
      borderRadius: radius + 'rpx',
      boxShadow: `0 0 ${shadow}rpx rgba(0,0,0,.05)`
    }"
  >
    <image
      :class="{gray: isGray}"
      :src="url"
      :mode="mode"
      @error="handleError"
    ></image>
  </view>
</template>

<script>
  import getServiceUrl from "@/common/getServiceUrl";

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

  export default {
    name: "XdJfbImage",
    props:{
      mode: {
        type: String,
        default: 'aspectFit'
      },
      width: {
        type: String|Number,
        default: 320
      },

      height: {
        type: String | Number,
        default: 240
      },

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

      radius: {
        type: Number | String,
        default: 0,
      },

      shadow: {
        type: Number | String,
        default: 0,
      },

      styleSize: {
        type: String,
        default: 'size4' //size1-size8
      },

      bgc: {
        type: String,
        default: '#fff'
      }

    },
    data(){
      return {
        url: null,
        uiWidth: 750,
        uiHeight: 750,
        isGray: false,
        error: '//img.jufubao.cn/front-error.png'
      }
    },

    created(){
      if (this.$xdUniHelper.checkVarType(this.width) === 'string' && /\d/.test(this.width)) {
        this.uiWidth = Number(this.width)
      }
      if (this.$xdUniHelper.checkVarType(this.height) === 'string' && /\d/.test(this.height)) {
        this.uiHeight = Number(this.height)
      }

      //图片设置
      if(this.src) this.url = getServiceUrl(this.src, this.styleSize);
      else this.url = this.error;

      this.isGray = this.$xdUniHelper.checkVarType(this.$settings.isGray) === 'boolean' ? this.$settings.isGray: false;
    },
    methods:{
      handleClick(e){
        this.$emit('click',e);
        this.$emit('tap', e);
      },

      handleError(){
        this.url = this.error;
      },
    }
  }
</script>

<style scoped lang="less">
  .xd-image {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    & > image {
      max-width: 100%;
      max-height: 100%;
    }

    & > view {
      width: 80%;
      height: 80%;
      background-repeat: no-repeat;
      background-position: center center;
      background-size: 100% 100%;
    }
  }

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