<template>
    <div :class="'avatar-uploader-container' + (isDisabled ? ' table-pic-view-class' : '')">
        <p class="avater-uploader-title" v-if="!!title && !imageUrl">{{title}}</p>
        <el-upload
            class="avatar-uploader"
            :action="actionUrl"
            :accept="acceptFileType"
            :disabled="isDisabled"
            :show-file-list="false"
            :http-request="onUpload" :style="imgStyls">
            <img v-if="!!imageUrl" :src="imageUrl" :style="{'width':imgWidth+'px','height':imgHeight+'px'}" :onerror="defaultImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
    import axios from "axios";

    const operate = {
        isLtSize(size, maxSize, unit){
            const conversion = {
                KB(size){
                    return (size / 1024);
                },
                MB(size){
                    return (size / 1024 / 1024);
                },
                GB(size){
                    return (size / 1024 / 1024 / 1024)
                }
            };
            const converSize = conversion[unit](size);
            return converSize < maxSize;
        },
        async getImgInfo(vm){
            const res = await vm.spcpFormAxios.post(vm.api.baseUploadUrl+'viewFile', {fkId: vm.fkid});
            if(!res || !res.data || res.data.constructor !== Array || res.data.length <= 0){
                return [];
            }
            return res.data;
        }
    };

    export default {
        name: "plImage",
        props: {
            imgWidth: {
                type: Number,
                default: 80
            },
            imgHeight: {
                type: Number,
                default: 80
            },
            title: {
                type: String,
                default: ''
            },
            maxSize: {
                type: Number,
                default: 5
            },
            unit: {
                type: String,
                default: 'MB'
            },
            fkid: {
                type: String,
                required: true
            },
            isDisabled:{
                type:Boolean,
                default:false
            },
            plFileType: {// 逗号分隔的文件类型，.doc,.jpg。。
                type: String,
                default: ""
            },
            onUploadSuccess:{
                type:Function,
                default:null
            },
            beforeUploadMethod:{
                type:Function,
                default:null
            }
        },
        data() {
            return {
                imageUrl: '',
                actionUrl: this.api.upload.uploadFile,
                defaultImg:'this.src="'+require('./images/emipty.png')+'"',
                acceptFileType: "", // 允许上传的文件类型
            };
        },
        computed: {
            imgStyls(){
                return {
                    width: this.imgWidth+'px',
                    height: this.imgHeight+'px'
                }
            }
        },

        watch:{
            fkid(){
                this.initImageData();
            }
        },

        created(){
            // console.log(this.isDisabled);
            this.initImageData();
        },
        methods: {
            initImageData(){
                const vm = this;
                vm.imageUrl =  '';
                vm.acceptFileType = ""; // 允许上传的文件类型
                vm.initSetting();

                operate.getImgInfo(this).then(data => {
                    if(data.length > 0){
                        vm.imageUrl = vm.api.baseUploadUrl+'downloadFile?id='+data[0].id;
                    }
                });
            },
            initSetting(){
                if(!this.plFileType || this.plFileType == 'all'){
                    this.acceptFileType = ".jpg,.png,.gif";
                }else if(this.plFileType.indexOf(".") != 0){
                    this.acceptFileType = "." + this.plFileType;
                }else{
                    this.acceptFileType = this.plFileType;
                }
            },

            beforeUpload(type, size, file) {
                const vm = this;
                if (this.acceptFileType) { // 判断上传类型
                    let fileSuffix = file.name.substring(file.name.lastIndexOf("."), file.name.length);
                    if (this.acceptFileType.indexOf(fileSuffix) == -1) {
                        this.$message.error('不支持' + fileSuffix + '文件类型！');
                        this.fileTypeValid = false;
                        return false;
                    }
                }

                const isLt = operate.isLtSize(size, vm.maxSize, vm.unit);

                if (!isLt){
                    vm.$message.error('上传图片大小不能超过 ' + vm.maxSize + vm.unit + '!');
                    return false;
                }

                /*
                    ** 删除之前上传的图片
                    */
                operate.getImgInfo(this).then(data => {
                    if(data.length > 0){
                        let ids = [];
                        data.forEach(item => {
                            ids.push(item.id)
                        });
                        vm.spcpFormAxios.defaults.headers={
                            'Content-Type': 'application/x-www-form-urlencoded',
                            common: {
                                Authorization: (this.CACHE_GLOBAL.getLoginToken() || ""),
                                a:1,
                                b:2,
                                abc:123
                            }
                        };
                        vm.spcpFormAxios.post(vm.api.upload.deleteFilesById, {ids: ids.join(',')});
                    }
                });

                return true;
            },
            onUpload(item){
                const file = item.file;
                const action = item.action;
                const vm = this;
                let value = this.beforeFileUpload(file);
                if(!value){
                    return;
                }
                if(this.beforeUpload(file.type, file.size,file)){
                    //组装参数
                    let formData = new FormData();
                    formData.append('file', file);
                    formData.append('fkId', vm.fkid);

                    //创建axios实例
                    vm.spcpFormAxios.defaults.headers=null;
                    const axiosInstance = axios.create({
                        baseURL: vm.spcpFormAxios.defaults.baseURL,
                        timeout: 60000,
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            Authorization: (this.CACHE_GLOBAL.getLoginToken() || "")
                        },
                        transformRequest: [
                            function (data) {
                                return data;
                            }
                        ],
                        maxContentLength: 10000
                    });

                    //上传文件
                    axiosInstance.post(action, formData).then((res) =>{
                      // console.log(localStorage["Authorization" + (window.projectSuffix || "")] || "")
                        vm.spcpFormAxios.defaults.headers={
                            'Content-Type': 'application/x-www-form-urlencoded',
                            common: {
                                Authorization: (localStorage["Authorization" + (window.projectSuffix || "")] || ""),
                                a:1,
                                b:2,
                                abc:123
                            }
                        };
                        if(res&&res.data&&res.data.upload){
                            // 上传成功回调
                            vm.onUploadSuccess && vm.onUploadSuccess(file);
                            this.imageUrl = this.api.baseUploadUrl + "downloadFile?id=" + res.data.upload.id;
                        }
                    }).catch(() => {
                         vm.spcpFormAxios.defaults.headers={
                            'Content-Type': 'application/x-www-form-urlencoded',
                            common: {
                                Authorization: (localStorage["Authorization" + (window.projectSuffix || "")] || ""),
                                a:1,
                                b:2,
                                abc:123
                            }
                        };
                        vm.$message.error('上传失败!');
                    });
                }
            },
            beforeFileUpload(file){
                if(this.beforeUploadMethod){
                    return this.beforeUploadMethod(file);
                }
                return true;
            }
        }
    }
</script>

<style lang="scss">
    .avatar-uploader-container{
        display: inline-block;

        .avater-uploader-title{
            padding: 5px 0 2px 0;
            text-align: center;
        }

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

            &:hover{
                border-color: #409EFF;
            }

            .avatar {
                display: block;
            }

            .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 80px;
                height: 80px;
                line-height: 80px;
                text-align: center;
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                margin: auto;
            }
        }
    }
    .table-pic-view-class .el-upload{
        cursor: default!important;
    }
    .table-pic-view-class .avatar-uploader{
        cursor: default!important;
    }
</style>
