<template>
  <image
    :src="imgSrc"
    :mode="mode"
    class="wk-auth-img"
    @error="errorCallback"
    @load="loadCallback"
    @click="showLargeImg" />
</template>

<script>
	/**
	 * 带权限的图片
	 * @author yxk
	 * @property {String} src 图片地址
	 * @property {String} mode image mode属性，默认 scaleToFill
	 * @property {Boolean} preview 是否可以查看大图，默认 true
	 */
  import request from '@/utils/request.js'
  import { BASE_URL_FN } from '@/config.js'
  import cookies from 'weapp-cookie'

  export default {
    name: 'WkAuthImg',
    props: {
      src: {
        type: String,
        default: ''
      },
      mode: {
        type: String,
        default: 'scaleToFill'
      },
      preview: {
        type: Boolean,
        default: true
      },
      isTemp: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        imgSrc: '',
        showImage: true
      }
    },
    watch: {
      src: {
        handler() {
          this.initSrc()
        },
        immediate: true
      }
    },
    methods: {
      getUrl() {		
        if (this.isTemp) return this.src
        let url = BASE_URL_FN() + (this.src.startsWith('/') ? this.src.replace('/', '') : this.src)
        const token = uni.getStorageSync('token') || ''
        const appid = uni.getStorageSync('appid') || ''
        const arr = []
				
        if (token) {
          arr.push(`c=${token}`)
        }
        if (appid) {
          arr.push(`k=${appid}`)
        }
        if (arr.length > 0) {
          return url + '?' + arr.join('&')
        } else {
          return url
        }
      },
			
      initSrc() {
        if (this.$isEmpty(this.src)) {
          this.imgSrc = ''
          return
        }
				
        const imgDict = getApp().globalData.imgDict
        if (imgDict.hasOwnProperty(this.src)) {
          this.imgSrc = imgDict[this.src]
          return
        }
				
        if (
          this.src &&
          typeof this.src === 'string' &&
          this.src.startsWith('data:')) {
          this.imgSrc = this.src
          return
        }

        this.imgSrc = this.getUrl()
        this.showImage = false
        this.$nextTick(() => {
          this.showImage = true
        })
      },
			
      /**
       * 通过请求挂载图片
       */
      getSrcByRequest() {
        const imgDict = getApp().globalData.imgDict
        imgDict[this.src] = '' // 防止同一时间多次请求同一张图片浪费资源
        const appid = uni.getStorageSync('appid') || ''
        const header = {
          'Admin-Token': uni.getStorageSync('token') || ''
        }
        if (appid) {
          header.k = appid
        }
        uni.request({
          url: this.getUrl(),
          header: header,
          responseType: 'arraybuffer',
          success: res => {
            console.log('image res: ', res)
            const contentType = res.header['Content-Type'] || res.header['content-type']
            this.imgSrc = `data:${contentType};base64,${uni.arrayBufferToBase64(res.data)}`
            imgDict[this.src] = this.imgSrc
            this.showImage = false
            this.$nextTick(() => {
              this.showImage = true
            })
          },
          fail: () => {
            this.imgSrc = ''
            delete imgDict[this.src]
          }
        })
      },

      errorCallback(evt) {
        console.log('error: ', evt)
        this.$emit('error', evt)
      },
			
      loadCallback(evt) {
        this.$emit('load', evt)
      },
			
      showLargeImg(evt) {
        if (!this.preview) return
        uni.previewImage({
          urls: [this.getUrl()],
          indicator: 'number'
        })
				
        // const imgDict = getApp().globalData.imgDict
        // uni.previewImage({
        // 	urls: [imgDict[this.src] || this.getUrl()],
        // 	indicator: 'number'
        // })
      }
    }
  }
</script>

<style scoped lang="scss">
	.wk-auth-img {
		width: 100%;
		height: 100%;
	}
</style>
