<template>
  <div class="rc-cropper" v-if="originImg">
    <div
      :class="{
        'rc-cropper__canvasCrop1': cropOption.uploadType == 1,
        'rc-cropper__canvasCrop2': cropOption.uploadType == 2,
      }"
    >
      <img :src="originImg" v-if="!cropper" />
      <canvas :id="originImg" ref="canvas" />
      <!--<div class="rc-cropper__iconCrop">-->
      <!--<el-tooltip content="确认裁剪" placement="right" v-if="cropper">-->
      <!--<el-button type="primary" size="mini" @click="sureCropper()" style="margin-top:530px;margin-right: 320px;"><i class="el-icon-check">确认裁剪</i></el-button>-->
      <!--</el-tooltip>-->
      <!--</div>-->
      <div class="rc-cropper__iconCrop">
        <el-tooltip content="确认裁剪" placement="right" v-if="cropper">
          <el-button type="primary" size="mini" @click="sureCropper()"
            ><i class="el-icon-check">确认裁剪</i></el-button
          >
        </el-tooltip>
      </div>
    </div>
  </div>
</template>

<script>
import { $on, $off, $once, $emit } from '../../../utils/gogocodeTransfer'
let vm = null
// import Cropper from 'cropperjs'
import Cropper from '../../utils/cropperjs/cropper'
import 'cropperjs/dist/cropper.min.css'
export default {
  name: 'rc-cropper2',
  props: {
    cropOption: {
      type: Object,
      required: true,
      default: () => {},
    },
    originImg: {
      required: true,
    },
  },
  created() {
    vm = this
  },
  data() {
    return {
      cropper: null,
      croppShow: false,
    }
  },
  mounted() {
    this.drawImg()
  },
  unmounted() {
    this.cropper && this.cropper.destroy()
  },
  methods: {
    // 在canvas上绘制图片
    drawImg() {
      const _this = this
      this.$nextTick(() => {
        let canvas = document.getElementById(this.originImg)
        if (canvas) {
          // canvas.width = 1000
          // canvas.height = 800
          //
          // let int_x = _this.cropOption.cvWidth/800;
          // if(int_x >= 1){
          //   int_x = 800/_this.cropOption.cvWidth;
          // }
          //
          // let int_y = _this.cropOption.cvHeight/540;
          // if(int_y >= 1){
          //   int_y = 540/_this.cropOption.cvHeight;
          // }
          //
          //
          // if(int_x >= int_y){
          //   canvas.width = _this.cropOption.cvWidth * int_y;
          //   canvas.height = _this.cropOption.cvHeight * int_y;
          // }
          // else {
          //   canvas.width = _this.cropOption.cvWidth * int_x;
          //   canvas.height = _this.cropOption.cvHeight * int_x;
          // }

          canvas.width = _this.cropOption.cvWidth
          canvas.height = _this.cropOption.cvHeight
          let ctx = canvas.getContext('2d')
          ctx.clearRect(0, 0, canvas.width, canvas.height)
          let img = new Image()
          img.crossOrigin = 'Anonymous'
          img.src = this.originImg
          img.onload = function () {
            // ctx.drawImage(img, 0, 0, canvas.width, canvas.height, 0, 0, 130, 600)
            // ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, 130, 600)
            console.log(
              'drawImage: canvas width:' +
                canvas.width +
                ',height:' +
                canvas.height
            )
            console.log(
              'drawImage: img width:' + img.width + ',height:' + img.height
            )
            // ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
            // ctx.drawImage(img, 230, 230, canvas.width * 0.15, canvas.height * 0.35)
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
            _this.initCropper()
          }
        }
      })
    },
    // 显示裁剪框
    initCropper() {
      if (!HTMLCanvasElement.prototype.toBlob) {
        console.log('HTMLCanvasElement.prototype.toBlob####')
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var canvas = this
            setTimeout(function () {
              var binStr = window.atob(
                canvas.toDataURL(type, quality).split(',')[1]
              )
              var len = binStr.length
              var arr = new window.Uint8Array(len)
              for (var i = 0; i < len; i++) {
                arr[i] = binStr.charCodeAt(i)
              }
              // callback(new window.Blob([arr], { type: type || 'image/jpeg' }));
              callback(new window.Blob([arr], { type: type || 'image/jpeg' }))
            })
          },
        })
      }

      this.croppShow = true
      this.cropper = new Cropper(this.$refs.canvas, {
        checkCrossOrigin: true,
        viewMode: 3,
        zoomOnWheel: true, // 是否可以通过移动鼠标来放大图像
        dragMode: 'move',
        // autoCropArea: 0.6,
        // center: true,
        // autoCrop: true,
        restore: false,
        modal: true,
        guides: true,
        highlight: true,
        cropBoxMovable: true,
        // zoomable: true,
        cropBoxResizable: vm.cropOption.cropBoxResizable, //是否显示等比例缩放
        minCropBoxWidth: vm.cropOption.minCropBoxWidth, // 剪切区域的最小宽度
        minCropBoxHeight: vm.cropOption.minCropBoxHeight, // 剪切区域的最小高度
        // minContainerHeight: 500,
        // minCanvasHeight: 500,
        // restore: true,
        toggleDragModeOnDblclick: false,
        // aspectRatio: 75/42,
        aspectRatio: this.cropOption.aspectRatio, // 显示等比例缩放的比例
        ready: () => {
          this.cropper.setData({
            x: vm.cropOption.offset_x,
            y: vm.cropOption.offset_y,
            width: vm.cropOption.width,
            height: vm.cropOption.height,
          })
          // this.cropper.setCropBoxData({
          //   width: 750,
          //   height: 100
          // })
          // this.cropper.move(1, -1).rotate(0).scale(1, -1);
          // this.cropper.zoom(-2);

          const imageData = this.cropper.getImageData()
          const canvasData = this.cropper.getCanvasData()
          const cropBoxData = this.cropper.getCropBoxData()
          console.log('imageData width:' + imageData.width)
          console.log('imageData height:' + imageData.height)
          console.log('imageData naturalWidth:' + imageData.naturalWidth)
          console.log('imageData naturalHeight:' + imageData.naturalHeight)
          console.log('canvasData naturalWidth:' + canvasData.naturalWidth)
          console.log('canvasData naturalHeight:' + canvasData.naturalHeight)
          console.log('canvasData width:' + canvasData.width)
          console.log('canvasData height:' + canvasData.height)
          console.log('cropBoxData width:' + cropBoxData.width)
          console.log('cropBoxData height:' + cropBoxData.height)

          // this.cropper.zoomTo(-0.2);
          const containerData = this.cropper.getContainerData()

          console.log('containerData width:' + containerData.width)
          console.log('containerData height:' + containerData.height)

          // Zoom to 50% from the center of the container.
          //               this.cropper.zoomTo(-0.5, {
          //                 x: containerData.width / 2,
          //                 y: containerData.height / 2,
          //               });
        },
        // cropstart:(event) => {
        //   console.log(event.detail.originalEvent);
        //   console.log(event.detail.action);
        //
        //   if(this.cropOption.aspectRatio == 0){
        //   if(event.detail.action == "w"
        //     || event.detail.action == "e"
        //     || event.detail.action == "se"
        //     || event.detail.action == "sw"
        //     || event.detail.action == "ne"
        //     || event.detail.action == "nw"){
        //     event.preventDefault();
        //   }
        //   }
        // },

        // zoom: function (event) {
        //   // Keep the image in its natural size
        //   if (event.detail.oldRatio === 1) {
        //     event.preventDefault();
        //   }
        // },
      })
    },
    // 确认裁剪
    sureCropper() {
      let _this = this
      const cropParam = this.cropper.getData()
      console.log('cropParam', cropParam)
      // cropParam.width = 160;
      // cropParam.height = 120;
      this.cropper.getCroppedCanvas().toBlob(function (blob) {
        var objecturl = window.URL.createObjectURL(blob)
        console.log('objecturl', objecturl)
        let files = new window.File([blob], 'cropper.jpg')
        console.log('getCroppedCanvas', files)
        let oFileReader = new window.FileReader()
        console.log('oFileReader', oFileReader)
        oFileReader.onloadend = function (e) {
          console.log('e.target.result', e, e.target, e.target.result)
          let base64 = e.target.result
          $emit(_this, 'getCropImg', base64, cropParam, files, _this.cropper)
        }
        oFileReader.readAsDataURL(blob)
      }, 'image/jpeg')
    },
  },
  emits: ['getCropImg'],
}
</script>

<style lang="scss" scoped>
 {
}
.rc-cropper__canvasCrop1 {
  width: 800px;
  height: 540px;
}
.rc-cropper__canvasCrop2 {
  width: 400px;
  height: 300px;
}
.rc-cropper__iconCrop {
  position: absolute;
  right: 45%;
  top: 91%;
}
.el-tooltip {
  margin: 20px 4px;
  display: block;
  z-index: 10000;
}
</style>
