<!-- 只支持单个图片和文件的上传。此组件图片预览和上传有冲突，建议使用UploadImage.vue -->
<template>
    <div id="UploadFile">
        <el-upload
            v-if="!judgeEmpty( uploadProps.listType) || uploadProps.listType === 'picture-card'"
            class="picture-card-box"
            action=""
            list-type="picture-card"
            :file-list="fileList"
            :limit="uploadProps.limit || 1"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="(file, fileList) => { handleChange(file, fileList); }"
            :auto-upload="false"
            :with-credentials="true"
            :multiple="uploadProps.limit === 1 ? false : uploadProps.multiple"
            :class="[showProcess || uploadProps.limit === 1 && fileList.length === 1 ? 'disabled' : '', uploadProps.isBtn ? 'btn-upload' : '']"
        >

            <el-button v-if="uploadProps.isBtn" size="mini" type="primary" :disabled="fileList.length >= (uploadProps.limit || 1)">
                {{ uploadProps.buttonName || '点击上传' }}
            </el-button>
            <!-- <el-image v-if="imageUrl && uploadProps.showImageUrl" :src="imageUrl" class="avatar" :preview-src-list="[imageUrl]" /> -->
            <div v-else class="ps-r">
                <i class="el-icon-plus" />
                <div class="ft12 c-799 line-height20 sub-tip">{{ uploadProps.subTip }}</div>
            </div>
            <el-progress v-show="showProcess" :percentage="processLen" />
        </el-upload>
        <el-upload
            v-else
            ref="uploadFile"
            class="ps-r uploadBox mt10"
            :class="showProcess || uploadProps.limit === 1 && fileList.length === 1 ? 'disabled' : ''"
            action=""
            :list-type="uploadProps.listType || 'picture'"
            :limit="uploadProps.limit || 1"
            :on-preview="handlePreview"
            :file-list="fileList"
            :show-file-list="uploadProps.showFileList || false"
            :on-error="handleError"
            :on-change="(file, fileList) => { handleChange(file, fileList); }"
            :on-remove="handleRemove"
            :auto-upload="false"
            :multiple="uploadProps.limit === 1 ? false : uploadProps.multiple"
            :with-credentials="true"
        >
            <el-button v-if="uploadProps.isBtn" size="mini" type="primary" :disabled="fileList.length >= (uploadProps.limit || 1)">
                {{ uploadProps.buttonName || '点击上传' }}
            </el-button>
            <el-image v-if="imageUrl && uploadProps.showImageUrl" :src="imageUrl" class="avatar" />
            <i v-else-if="uploadProps.type==='img'" class="el-icon-plus avatar-uploader-icon" />
            <div class="ft12 c-799 line-height20 mt5">{{ uploadProps.subTip }}</div>
            <el-progress v-show="showProcess" :percentage="processLen" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

    </div>
</template>
<script>
const COS = require('cos-js-sdk-v5');
import api_cos from '@/api/api_cos';
import { notEmpty } from '@/tool/func';

export default {
    name: 'UploadFile',
    props: {
        uploadProps: {
            type: Object,
            default: () => {}
        },
        // uploadProps.fileSize 限制文件大小,需传入数字类型
        // uploadProps.acceptAttribute 限制文件类型,需传入字符串类型 示例：acceptAttribute:'.PDF,.jpeg'
        // uploadProps.acceptMethods   判断当然传入文件格式,需传入数组 示例：acceptMethods:['application/pdf','image/jpeg']'
        // uploadProps.type  放在腾讯云的哪个文件夹下 video img file
        // uploadProps.limit  文件上传的总数限制
        // uploadProps.limitWidth  如果为图片，图片的宽度限制
        // uploadProps.limitHeight   如果为图片，图片的高度限制
        // uploadProps.showFileList 判断是否显示已上传文件列表
        // uploadProps.showImageUrl 判断是否显示已上传图片
        // uploadProps.multiple 传true支持上传多张
        // uploadProps.listType 文件列表的类型 text/picture/picture-card
        defaultFileList: {
            type: Array,
            default: () => []
        },
        defaultImage: {
            type: String,
            default: () => ''
        }
    },
    data() {
        return {
            coursewareId: 0,
            fileList: [],
            param: {},
            loading: false,
            showProcess: false,
            showFileList: false,
            processLen: 0,
            cos: {},
            COS_BUCKET: '',
            COS_REGION: '',
            imageUrl: '',
            dialogVisible: false,
            dialogImageUrl: ''
        };
    },
    watch: {
        // 父组件给子组件传递图片初始值进行图片回写
        defaultImage: {
            handler: function(newval, oldval) {
                this.imageUrl = newval;
            },
            immediate: true
        }
    },
    created() {
        // 文件列表回写
        if (this.defaultFileList && this.defaultFileList.length > 0 && this.defaultFileList[0].url) {
            this.fileList = this.defaultFileList;
        }
    },
    methods: {
        // 父组件调用子组件方法的形式进行图片回写
        initAttr(val) {
            this.imageUrl = val.imageUrl;
        },
        initFileList(val) {
            this.fileList = val;
        },
        handlePreview(file) {
            if (this.uploadProps.type === 'img' && (!this.uploadProps.listType || this.uploadProps.listType === 'picture' || this.uploadProps.listType === 'picture-card')) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            } else {
                if (!file.url) {
                    return;
                }
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = file.url;
                link.target = '_blank';
                link.setAttribute('download', file.name);
                document.body.appendChild(link);
                link.click();
                link.remove();
            }
        },
        handleChange(file, fileList) {
            console.log('==file', fileList);
            // 获取最后一个.的位置
            var index = file.name.lastIndexOf('.');
            // 获取后缀
            var ext = file.name.substr(index);
            // 文件类型校验
            const acceptAttributes = this.uploadProps.acceptAttribute.split(',');
            if (acceptAttributes.indexOf(ext.toLowerCase()) === -1) {
                this.$message.error(`文件格式有误`);
                this.handleRemove(file, fileList);
                return false;
            }
            const isLtM = file.size / 1024 / 1024 < this.uploadProps.fileSize; // M
            if (!isLtM) {
                this.$message.error(`'上传文件大小不能超过${this.uploadProps.fileSize}MB!'`);
                this.handleRemove(file, fileList);
                return false;
            }
            // return isSize & isLtM;
            if (file.status === 'ready') {
                this.showProcess = true; // 进度条显示
            }
            this.uploadFile(file.raw, this.uploadProps.type, result => {
                console.log('=result=', result);
                console.log('fileList----', fileList);
                this.processLen = 100;
                // 上传成功的信息
                const data = { url: result, name: fileList[fileList.length - 1].name };
                const width = parseFloat(this.uploadProps.limitWidth);
                const height = parseFloat(this.uploadProps.limitHeight);
                if (this.uploadProps.type === 'img' && (height > 0 || width > 0)) {
                    const img = new Image();
                    img.src = result;
                    img.onload = () => {
                        const imgWidth = img.width;
                        const imgHight = img.height;
                        const valid = imgWidth <= width && imgHight <= height; // && imgWidth <= 1600 && imgHight <= 1200;
                        console.log(imgWidth, imgHight);
                        if (valid) {
                            this.fileList = [...fileList];
                            this.imageUrl = data.url;
                            this.$emit('uploadSuccess', data);
                        } else {
                            console.log('this.fileList', this.fileList);
                            // this.$message.error('建议尺寸≤1600*1200px，最小尺寸≥800*600px');
                            if (height > 0 && width > 0) {
                                this.$message.error(`图片尺寸大小不能超过${width}*${height}像素!`);
                            } else if (width > 0) {
                                this.$message.error(`图片宽度大小不能超过${width}像素!`);
                            } else {
                                this.$message.error(`图片高度大小不能超过${height}像素!`);
                            }
                            // debugger;
                            this.handleRemove(file, fileList);
                            this.processLen = 0;
                        }
                    };
                } else {
                    this.fileList = [...fileList];
                    // 用于上传之后点击下载
                    this.fileList[0].url = result;
                    // data.name = this.fileList[0].name;
                    this.$emit('uploadSuccess', data);
                }
                this.showProcess = false;
            });
        },
        uploadFile(file, type, callback) {
            console.log('file', file);
            api_cos.getCosTempSign({ type: 'pc' }).then(res => {
                if (res && res.status === 'SUCCESS') {
                    this.COS_BUCKET = res.bucket;
                    this.COS_REGION = res.region;
                    this.cos = new COS({
                        Protocol: 'https:',
                        getAuthorization: function(options, callback) {
                            callback({
                                TmpSecretId: res.tmpSecretId,
                                TmpSecretKey: res.tmpSecretKey,
                                XCosSecurityToken: res.sessionToken,
                                StartTime: res.startTime,
                                ExpiredTime: res.expiredTime,
                                requestId: res.requestId
                            });
                        }
                    });
                    // 文件路径
                    let newKey = `/${process.env.VUE_APP_NAME}/${type}/${file.uid}/${file.name}`;
                    if (notEmpty(this.uploadProps.filePath)) {
                        newKey = this.uploadProps.filePath;
                    }
                    this.cos.sliceUploadFile(
                        {
                            Bucket: this.COS_BUCKET,
                            Region: this.COS_REGION,
                            Key: newKey,
                            Body: file,
                            onTaskReady: function(taskId) {
                                /* 执行队列taskId */
                                console.log('taskId:', taskId);
                            },
                            onProgress: progressData => {
                                /* 非必须 */
                                const percent = parseInt(progressData.percent * 10000) / 100;
                                // var speed = parseInt((progressData.speed / 1024 / 1024) * 100) / 100;
                                this.processLen = percent;
                                // console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
                            }
                        },
                        (err, data) => {
                            if (err) {
                                this.handleError('文件上传失败,请重新上传', file);
                            } else {
                                const fileUrl = 'https://' + data.Location;
                                console.log('fileUrl', fileUrl);
                                callback(fileUrl);
                            }
                        }
                    );
                }
            }).catch(() => {
                this.handleRemove(file, this.fileList);
            });
        },
        handleError(err, file, fileList) {
            this.handleRemove(file, fileList);
            return this.$message.error(err);
        },
        // 后台需提供删除接口
        handleRemove(file, fileList = []) {
            console.log('fileList00000--------', fileList, this.fileList);
            setTimeout(() => {
                const index = fileList.findIndex(item => item.uid === file.uid);
                if (index !== -1) {
                    fileList.splice(index, 1);
                }
                this.fileList = [...fileList];
                console.log('fileList111111111--------', fileList, this.fileList);
                this.showProcess = false;
            }, 0);
            // 调父组件方法删除上传文件信息
            this.$emit('removeFile', file);
        },
        // 置空
        resetFileList() {
            this.fileList = [];
        }
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader-icon {
        font-size: 38px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
}
.avatar {
        width: 100px;
        height: 100px;
        display: block;
}
.picture-card-box {
    .sub-tip {
        position: absolute;
        bottom: 10px;
        width: 120px;
        left: 10px;
    }
}
</style>
