<template>
    <div>
        <!--<div class="upload">-->
        <!--<el-upload-->
        <!--class="avatar-uploader"-->
        <!--:action=domain-->
        <!--:http-request=upqiniu-->
        <!--:show-file-list="false"-->
        <!--:before-upload="beforeUpload">-->
        <!--<img v-if="imageUrl" :src="imageUrl" class="avatar">-->
        <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
        <!--</el-upload>-->
        <!--<ImgCutter v-on:cutDown="cutDown"></ImgCutter>-->
        <!--</div>-->
        <div class="one-form-item">
            <el-upload
                    class="avatar-uploader"
                    action
                    :auto-upload="false"
                    :on-change="uploadFileMethodAnswer"
                    :show-file-list="false"
                    :multiple="true"
                    :before-upload="beforeUpload"
            >
                <el-button class="uploader-button" type="primary">上传banner图</el-button>
            </el-upload>
        </div>

        <el-dialog title="图片剪裁(为确保剪切后图片的分辨率足够，请尽量不缩放剪切原图)" :visible.sync="dialogVisible" append-to-body width="70%">
            <div class="cropper-content">
                <div class="cropper" style="text-align:center">
                    <vueCropper
                            ref="cropper"
                            :img="option.img"
                            :outputSize="option.size"
                            :outputType="option.outputType"
                    ></vueCropper>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="finish" :loading="loading">确认</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import * as qiniu from 'qiniu-js';
    import ImgCutter from 'vue-img-cutter'
    import VueCropper from 'vue-cropper'
    let qs = require('qs');
    export default {
        data() {
            return {
                imageUrl: '',
                token: {},
                // 七牛云的上传地址，根据自己所在地区选择，我这里是华南区
                // domain: 'https://up-z1.qiniup.com',
                // 这是七牛云空间的外链默认域名
                // qiniuaddr: 'qjzpcd34v.hb-bkt.clouddn.com',
                // domain: 'https://up-z1.qiniup.com', // 这是七牛云空间的外链默认域名
                domain: 'https://up-z1.qiniup.com', // 这是七牛云空间的外链默认域名
                qiniuaddr: 'xhead.beswell.com',//xhead.beswell.com 旧的 qjzpcd34v.hb-bkt.clouddn.com
                option: {
                    img: "",
                    outputSize: 1, //剪切后的图片质量（0.1-1）
                    full: false, //输出原图比例截图 props名full
                    outputType: "png",
                    canMove: true,
                    original: false,
                    canMoveBox: true,
                    autoCrop: true,
                    autoCropWidth: 868,
                    autoCropHeight: 488,
                    fixedBox: false,
                    fixed: true,
                    maxImgSize: 3000, // 图片最大像素
                    fixedNumber: [16, 9]
                },
                dialogVisible: false,
                loading: false,
            };
        },
        methods: {
                finish()
                {
                    let _this = this;
                    this.$refs.cropper.getCropBlob(data => {
                        let base64Data = null;
                        let a = new FileReader();
                        a.onload = function (e) {
                            base64Data = e.target.result;
                            _this.loading = true;
                            const formData = new FormData();
                            formData.append("imageFile", base64Data);
                            uploadImg({
                                formData: formData
                            })
                                .then(res => {

                                })
                                .catch(() => {
                                    // this.$message.error('图片上传失败！');
                                });
                        };
                        a.readAsDataURL(data);
                    });
                }
            ,
                uploadFileMethodAnswer()
                {
                    this.dialogVisible = true;
                }
            ,
                cutDown(e)
                {
                    console.log(e);
                    this.imageUrl = e.dataURL;
                    this.upqiniu(e);
                }
            ,
                // 上传文件到七牛云
                upqiniu(req)
                {
                    const config = {
                        headers: {'Content-Type': 'multipart/form-data'}
                    };
                    let filetype = '';
                    if (req.file.type === 'image/png') {
                        filetype = 'png'
                    } else {
                        filetype = 'jpg'
                    }
                    // 重命名要上传的文件
                    const keyname = 'GoAllOut' + new Date().valueOf() + Math.floor(Math.random() * 100) + '.' + filetype;
                    // 从后端获取上传凭证token
                    let param = {
                        token: localStorage.token,
                    };
                    let postdata = qs.stringify(param);
                    this.axios.post('/api/v1/QiNiu/GetSimpleQiNiuToken', postdata).then(res => {
                        const formdata = new FormData();
                        formdata.append('file', req.file);
                        formdata.append('token', res.data.QiNinToken);
                        formdata.append('key', keyname);
                        // 获取到凭证之后再将文件上传到七牛云空间
                        this.axios.post(this.domain, formdata, config).then(res => {
                            this.imageUrl = 'http://' + this.qiniuaddr + '/' + res.data.key
                        })
                    })
                }
            ,
                // 验证文件合法性
                beforeUpload(file)
                {
                    // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt2M = file.size / 1024 / 1024 < 70;
                    // if (!isJPG) {
                    //     this.$message.error('上传头像图片只能是 JPG 格式!')
                    // }
                    if (!isLt2M) {
                        this.$message.error('上传头像图片大小不能超过 70MB!')
                    }
                    return isJPG && isLt2M
                }
            },
            components: {
                ImgCutter, VueCropper
            }
        }
</script>

<style scoped>
    .cropper-content .cropper {
        width: auto;
        height: 500px !important;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
