<template>
  <div class="cropper-box" v-dom-portal v-show="isShowCropper">
    <div class="cropper-title">将照片任意移动或放大缩小，将人脸放置在画框区域</div>
    <div class="cropper-wrapper" >
    <!-- 遮罩层 -->
      <div>
        <img id="image" :src="imgUrl" alt="Picture">
      </div>
      <!-- 底部按钮 -->
    </div>
    <div class="btn-wrapper">
      <button type="button" class="cancel" @click="handleCropCancel">取消</button>
      <button type="button" class="sure" @click="handleCropSubmit">确定</button>
    </div>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
export default {
    name: 'VCropper',
    props: {
        isShowCropper: {
            type: Boolean,
            default: true
        },
        imgUrl: {
            type: String,
            default: ''
        },
        minSize: {
            type: Number,
            default: 50
        }
    },
    components: {

    },
    watch: {
        isShowCropper (val) {
            if (val) {
                this.$nextTick(() => {
                    var image = document.getElementById('image')
                    this.cropper = new Cropper(image, {
                        dragMode: 'none',
                        preview: '.small',
                        aspectRatio: 1,
                        enlarge: 1,
                        viewMode: 2,
                        background: false,
                        zoomable: true,
                        ready: () => {
                            console.log(222)
                            this.croppable = true
                        }
                    })
                })
            }
        }
    },
    data () {
        return {
            cropper: null,
            croppable: false
            // offset:{//偏移量
            //   x:0,
            //   y:0
            // },
            // cropBox:{//裁剪框宽高
            //   width:0,
            //   height:0
            // }
        }
    },

    methods: {
        handleCropCancel () {
            this.$emit('cancel')
        },
        handleCropSubmit () {
            console.log('croppable', this.croppable)
            if (!this.croppable) {
                return
            }
            // Crop
            let croppedCanvas = this.cropper.getCroppedCanvas()
            // this.offset.x = Math.round(this.cropper.cropBoxData.left);//X轴偏移量，四舍五入
            // this.offset.y = Math.round(this.cropper.cropBoxData.top);//y轴偏移量，四舍五入
            // this.cropBox.width = Math.round(this.cropper.cropBoxData.width);//裁剪框宽度，四舍五入
            // this.cropBox.height = Math.round(this.cropper.cropBoxData.height);//裁剪框高度，四舍五入
            // roundedCanvas = this.getRoundedCanvas(croppedCanvas);
            let imgUrl = croppedCanvas.toDataURL()
            let size = this.showSize(imgUrl)
            if (size < this.minSize) {
                this.$vux.toast.show({
                    text: `裁剪图片不能小于${this.minSize}kb,请重新裁剪`,
                    type: 'warn'
                })
                return
            }
            this.$emit('submit', imgUrl)
        },
        getRoundedCanvas (sourceCanvas) {
            var canvas = document.createElement('canvas')
            var context = canvas.getContext('2d')
            var width = sourceCanvas.width
            var height = sourceCanvas.height
            canvas.width = width
            canvas.height = height

            context.imageSmoothingEnabled = true
            context.drawImage(sourceCanvas, 0, 0, width, height)
            context.globalCompositeOperation = 'destination-in'
            context.beginPath()
            // context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);//裁剪框是圆形的设置
            context.fill()
            return canvas
        },
        showSize (base64url) {
            // 获取base64图片大小，返回MB数字
            var str = base64url.replace('data:image/png;base64,', '')
            var equalIndex = str.indexOf('=')
            if (str.indexOf('=') > 0) {
                str = str.substring(0, equalIndex)
            }
            var strLength = str.length
            var fileLength = parseInt(strLength - (strLength / 8) * 2)
            // 由字节转换为KB
            var size = ''
            size = (fileLength / (1024)).toFixed(2)
            var sizeStr = size + '' // 转成字符串
            var index = sizeStr.indexOf('.') // 获取小数点处的索引
            var dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
            if (dou == '00') { // 判断后两位是否为00，如果是则删除00
                return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
            }
            return parseInt(size)
        }
    },
    mounted () {
    }

}
</script>

<style lang="less" >
  @import './style/cropper.less';
</style>
