<template>
  <image @load="load" :src="url" :mode="mode" :style="{width,height}" @click="handleClick"></image>
</template>

<script>
import uniIm from '@/uni_modules/uni-im/sdk/index.js';
  export default {
    emits: ['click'],
    props: {
      src: {
        type: String,
        default: ''
      },
      mode: {
        type: String,
        default: ''
      },
      maxWidth: {
        type: [String,Boolean],
        default: false
      },
    },
    data() {
      return {
        width:"1px",
        height:"1px",
        url: ''
      }
    },
    watch: {
       src:{
        async handler(src) {
          if(src){
            this.url = await uniIm.utils.getTempFileURL(src)
            // src 是cloud://开头的云存储地址，是腾讯云，否则是阿里云
            if(src.indexOf('cloud://') === 0){
              this.url += '?imageMogr2/thumbnail/400x400>'
            }else if(src.indexOf('http') === 0){
              // 因为还可能是 base64 blob 的本地图片，所以这里判断是不是http开头的
              this.url += '?x-oss-process=image/resize,w_100/quality,q_80'
            }
          }
        },
        immediate: true
      }
    },
    methods: {
      load(e){
        // console.log('img load',e)
        this.width = e.detail.width
        // 如果以rpx为单位，转换为px
        let maxWidth = parseInt(this.maxWidth)
        if(this.maxWidth && this.maxWidth.indexOf('rpx') > -1){
          maxWidth = parseInt(this.maxWidth) * uniIm.systemInfo.windowWidth / 750
        }
        // console.log('maxWidth',maxWidth)
        if(maxWidth && this.width > maxWidth){
          this.width = maxWidth + 'px'
          this.height = maxWidth * e.detail.height / e.detail.width + 'px'
          // console.error('超了',this.width,this.height)
        }else{
          this.width = e.detail.width + 'px'
          this.height = e.detail.height + 'px'
        }
      },
      handleClick(){
        this.$emit('click')
      }
    }
  }
</script>

<style>
</style>
