<template>
  <view style="position: fixed; top: 100vh;">
    <image :src="imageUrl" @load="crop" @error="afterLoadImg" />  
    <canvas class="canvas" canvas-id="canvas" style="width: 500px; height: 400px;"></canvas>
  </view>
</template>

<script>
import utils from '@/utils/utils.js'

export default {
  data() {
    return {
      imageUrl: null,
    }
  },
  methods: {
    afterLoadImg() {
      uni.hideLoading()
    },
    cutImgShare(imgUrl, w, h, that) {
      console.log('--imgUrl', imgUrl)
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: imgUrl,
          success(res) {
            try {

              const context = uni.createCanvasContext('canvas', that);
              console.log('--context', context)
              let sWidth = w
              let sHeight = h
              let sx = 0
              let sy = 0;
              let dWidth = 500
              let dHeight = 400

              console.log('--w', w, '--h', h)

              if (w <= h) {
                sHeight = Math.floor(sWidth / 5 * 4);
                sy = Math.floor((h - sHeight) / 2)
              } else {
                sWidth = Math.floor(sHeight / 4 * 5);
                sx = Math.floor((w - sWidth) / 2)
              }
              
              console.log('--sx', sx, '--sy', sy, '--sWidth', sWidth, '--sHeight', sHeight)
              context.drawImage(res.path, sx, sy, sWidth, sHeight, 0, 0, dWidth, dHeight);

              context.draw(true, setTimeout(() => {
                uni.canvasToTempFilePath({
                  canvasId: 'canvas',
                  fileType: 'jpg',
                  success: (res) => {
                    console.log(res.tempFilePath)
                    resolve(res.tempFilePath);
                  },
                  fail(err) {
                    console.log(err);
                    reject(err)
                  }
                }, that);
              }, 200));

            } catch (err) {
              reject(err)
            }

          },
          fail(err) {
            console.log('获取图片信息失败', err);
            reject(err)
          }
        });
      });
    },
    set(imageUrl) {
      console.log('--set', imageUrl)
      this.imageUrl = imageUrl
      uni.showLoading({
        title: '上传中...'
      })
    },
    async crop(e) {
      
      console.log('--crop', e)
      let that = this

      try {
        const { width, height } = e.target
        let fileUrl = await this.cutImgShare(this.imageUrl, width, height, that)
        
        this.$Oss.ossUpload(fileUrl).then(url => {
          console.log('--shareImg', url)
          this.$emit('change', url)
        })
      } catch (err) {
        console.log('--err', err)
        this.$emit('change', this.imageUrl)
      }

      this.afterLoadImg()
    },
  },
}
</script>

<style>

</style>