<template>
    <div>
        <a-modal title="图片上传" :visible="visible" :mask-closable="false" :confirm-loading="confirmLoading" :width="1200"
            :z-index="10000" :footer="null" @cancel="cancelHandel">
            <a-row>
                <a-col :xs="24" :md="20" :style="{ height: '850px' }">
                    <vue-cropper ref="cropper" :img="options.img" :info="true" :auto-crop="options.autoCrop"
                        :auto-crop-width="options.autoCropWidth" :auto-crop-height="options.autoCropHeight"
                        :fixed-box="options.fixedBox" @realTime="realTime">
                    </vue-cropper>
                </a-col>
                <a-col :xs="24" :md="4" :style="{ height: '850px' }">
                    <div style="margin:10px;">
                        <div v-html="imgInfos">
                        </div>
                        剪裁宽度：<a-input v-model="options.autoCropWidth" />
                        剪裁高度：<a-input v-model="options.autoCropHeight" />
                    </div>

                </a-col>
            </a-row>
            <a-row style="margin-top: 20px;">
                <a-col :lg="2" :md="2" style="margin-right: 20px;">
                    <a-upload name="file" accept="image/*" :before-upload="beforeUpload" :show-upload-list="false">
                        <a-button icon="upload">选择图片</a-button>
                    </a-upload>
                </a-col>
                <a-col :lg="{ span: 1, offset: 2 }" :md="2">
                    <a-button icon="plus" @click="changeScale(1)" />
                </a-col>
                <a-col :lg="{ span: 1, offset: 1 }" :md="2">
                    <a-button icon="minus" @click="changeScale(-1)" />
                </a-col>
                <a-col :lg="{ span: 1, offset: 1 }" :md="2">
                    <a-button icon="undo" @click="rotateLeft" />
                </a-col>
                <a-col :lg="{ span: 1, offset: 1 }" :md="2">
                    <a-button icon="redo" @click="rotateRight" />
                </a-col>
                <a-col :lg="{ span: 2, offset: 2 }" :md="2">
                    <a-button type="primary" @click="finish('blob')">确定</a-button>
                </a-col>
                <a-col :lg="{ span: 2, offset: 2 }" :md="2">
                    <a-button type="primary" @click="finish2('blob')">使用原图</a-button>
                </a-col>
            </a-row>
        </a-modal>

        <a-button v-if="buttonText" type="primary" @click="visible = true">{{ buttonText }}</a-button>
    </div>
</template>
 
<script>

export default {
    name: 'MkCropper',
    props: {
        buttonText: String,
        cropWidth: {
            type: Number,
            default: 300
        },
        cropHeight: {
            type: Number,
            default: 300
        },
    },
    data() {
        return {
            visible: false,
            id: null,
            confirmLoading: false,
            fileName: '',
            fileUid: '',
            file: null,
            options: {
                img: '',  // 需要剪裁的图片
                autoCrop: true, // 是否默认生成截图框
                autoCropWidth: 300, // 默认生成截图框的宽度
                autoCropHeight: 300, // 默认生成截图框的长度
                fixedBox: false // 是否固定截图框的大小 不允许改变
            },
            imgInfos: " ",
            previews: {} // 裁剪之后的结果
        }
    },
  created() {
     this.options.autoCropWidth = this.cropWidth;
     this.options.autoCropHeight = this.cropHeight;
  },
    watch: {  

    },
    methods: {
        show(file) {
            if (file) {
                this.file = file;
                const reader = new FileReader();
                this.fileName = file.name;
                // 转化为base64
                reader.readAsDataURL(file)
                reader.onload = () => {
                    // 获取到需要剪裁的图片 展示到剪裁框中
                    this.options.img = reader.result

                    this.visible = true;
                }
            } else {
                this.visible = true;
            }

        },
        edit(id) {
            this.visible = true
            this.id = id
        },
        close() {
            this.id = null
            this.visible = false
        },
        cancelHandel() {
            this.close()
        },
        // 图片放大/缩小
        changeScale(num) {
            num = num || 1
            this.$refs.cropper.changeScale(num)
        },
        // 左旋转
        rotateLeft() {
            this.$refs.cropper.rotateLeft()
        },
        // 右旋转
        rotateRight() {
            this.$refs.cropper.rotateRight()
        },
        beforeUpload(file) {
            const reader = new FileReader();
            this.fileName = file.name;
            this.fileUid = file.uid;
            this.file = file;
            // 转化为base64
            reader.readAsDataURL(file)
            reader.onload = () => {
                // 获取到需要剪裁的图片 展示到剪裁框中
                this.options.img = reader.result;

                let img = new Image();
                img.src = reader.result;
                img.onload = () => {
                    this.imgInfos = "原图片尺寸：" + img.width + "x" + img.height
                }
            }
            return false
        },

        base64ToBlob(base64Data) {
            let arr = base64Data.split(","),
                fileType = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), l = bstr.length,
                u8Arr = new Uint8Array(l);
            while (l--) {
                u8Arr[l] = bstr.charCodeAt(l);
            }
            return new Blob([u8Arr], { type: fileType });
        },
        blobToFile(newBlob, fileName) {
            newBlob.lastModifiedDate = new Date();
            newBlob.name = fileName;
            return newBlob;
        },
        // 上传图片（点击保存按钮）
        finish() {
            this.$refs.cropper.getCropData((data) => {
                this.visible = false


                var b1 = this.base64ToBlob(data);
                var file = this.blobToFile(b1, this.fileName);
                var suffix = this.fileName.substring(this.fileName.lastIndexOf(".") + 1);
                this.$mk.uploadFile(file, suffix, (url) => {

                    this.$emit('save', { url: url, fileUid: this.fileUid, fileName: this.fileName, fileExt: suffix });

                });
            })
        },
        finish2() {
            var file = this.file;
            var suffix = this.fileName.substring(this.fileName.lastIndexOf(".") + 1);

            this.$mk.uploadFile(file, suffix, (url) => {
                this.visible = false

                this.$emit('save', { url: url, fileUid: this.fileUid, fileName: this.fileName, fileExt: suffix });

            });
        },
        // 裁剪之后的数据
        realTime(data) {
            this.previews = data
        }
    }
}
</script>

<style></style>