<template>
  <view class="wk-sigature-view" @click="handleToPreview">
    <image
      :style="{
        width: imgStyle.width + 'px',
        height: imgStyle.height + 'px'
      }"
      :mode="mode"
      :src="fileTempUrl"
      class="img" />
  </view>
</template>

<script>
  import { FileQueryOneByBatch } from 'API/file.js'
  import { BASE_URL_FN } from '@/config.js'

  export default {
    name: 'WkSignatureView',
    props: {
      batchId: {
        type: String,
        required: true
      },
      mode: {
        type: String,
        default: 'scaleToFill'
      },
      preview: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        fileData: null,
        fileTempUrl: '',
        imgStyle: {
          width: 0,
          height: 0
        }
      }
    },
    watch: {
      batchId: {
        handler() {
          if (this.batchId) {
            this.$nextTick(() => {
              this.getStyle()
            })
          }
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      getStyle() {
        const that = this
        uni.createSelectorQuery()
          .in(this)
          .select('.wk-sigature-view')
          .boundingClientRect(data => {
            console.log('wk-sigature-view', data)
            that.imgStyle = {
              width: data.width,
              height: data.width / 2.6
            }
            that.getImage()
          })
          .exec()
      },

      getUrl(path) {
        let url = BASE_URL_FN() + (path.startsWith('/') ? path.replace('/', '') : path)
        const token = uni.getStorageSync('token') || ''
        const appid = uni.getStorageSync('appid') || ''
        const arr = []

        if (token) {
          arr.push(`c=${token}`)
        }
        if (appid) {
          arr.push(`k=${appid}`)
        }
        arr.push(`t=${new Date().getTime()}`)
        if (arr.length > 0) {
          return url + '?' + arr.join('&')
        } else {
          return url
        }
      },

      /**
       * 通过请求挂载图片
       */
      getImage() {
        const that = this
        FileQueryOneByBatch({
          batchId: this.batchId
        }).then(res => {
          if (res) {
            this.fileData = res
            this.fileTempUrl = this.getUrl(res.url)
          }
        }).catch(() => {
          this.fileData = null
        })
      },

      /**
       * 预览签名
       */
      handleToPreview() {
        if (!this.preview) return
        console.log('preview: ', this.fileTempUrl)
        uni.previewImage({
          urls: [this.fileTempUrl]
        })
      }
    }
  }
</script>

<style scoped lang="scss">
.wk-sigature-view {
	width: 100%;
	height: 100%;

	.img {
		vertical-align: middle;
	}
}
</style>
