<template>
	<div class="pi-cropper">
		<div class="pi-cropper__img">
			<img :src="src" ref="imgRef">
		</div>
		<div class="pi-cropper__preview">
			<h4>图像预览</h4>
			<div class="pi-cropper__preview__img" ref="previewRef"></div>
		</div>
	</div>
</template>
<script setup>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import {ref, watch, onMounted} from "vue";

defineExpose({
	getCropFile
})

const props = defineProps({
	src: { type: String, default: "" },
	compress: {type: Number, default: 1},
	aspectRatio:  {type: Number, default: NaN},
})
const imgRef = ref(null)
const previewRef = ref(null)

let crop = ref(null)
watch(() => props.aspectRatio, (val) => {
	crop.value.setAspectRatio(val)
})

onMounted(() => {
	init()
})

function init(){
	crop.value = new Cropper(imgRef.value, {
		viewMode: 2,
		dragMode: 'move',
		responsive: false,
		aspectRatio: props.aspectRatio,
		preview: previewRef.value
	})
}
function setAspectRatio(aspectRatio){
	crop.value.setAspectRatio(aspectRatio)
}
function getCropData(cb, type='image/jpeg'){
	cb(crop.value.getCroppedCanvas().toDataURL(type, props.compress))
}

function getCropBlob(cb, type='image/jpeg'){
	crop.value.getCroppedCanvas().toBlob((blob) => {
		cb(blob)
	}, type, props.compress)
}

function getCropFile(cb, fileName='fileName.jpg', type='image/jpeg'){
	crop.value.getCroppedCanvas().toBlob((blob) => {
		let file = new File([blob], fileName, {type: type})
		cb(file)
	}, type, props.compress)
}
</script>

<style scoped>
	.pi-cropper {height:300px;}
	.pi-cropper__img {height:100%;width:400px;float: left;background: #EBEEF5;}
	.pi-cropper__img img {display: none;}
	.pi-cropper__preview {width: 120px;margin-left: 20px;float: left;}
	.pi-cropper__preview h4 {font-weight: normal;font-size: 12px;color: #999;margin-bottom: 20px;}
	.pi-cropper__preview__img {overflow: hidden;width: 120px;height: 120px;border: 1px solid #ebeef5;}
</style>
