<template>
    <el-upload 
        name="photoFile"
        :action="uploadUrl" 
        list-type="picture-card"
        :show-file-list="true"
        :file-list="fileList"
        :headers="headers" 
        :data="uploadData" 
        :on-success="handleAvatarSuccess" 
        :before-upload="beforeAvatarUpload"
        :on-remove="handleRemove"
        accept="image/png,image/jpeg">
        <i class="el-icon-plus"></i>
    </el-upload>
</template>
<script>
import Constant from "@/constant";
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
    props: {
        value: {
            type: String,
            default: () => {
                return null;
            }
        },
        subFolder: {
            type: String,
            default: () => {
                return "sub";
            }
        },
        size: {
            type: Number,
            default: () => {
                return 64;
            }
        }
    },
    data() {
        return {
            uploadUrl: Constant.chargingServerUrl + "/uploadPicture",
            uploadData: {
                subFolder: "",
            },
            headers: {
                Authorization: getToken(),
            },
            fileList: []
        }
    },
    watch: {
        value(newVal, oldVal) {
            console.log("newVal=" + newVal);

            if (newVal != null && newVal.length > 0) {
                var arr = newVal.split(",");

                this.fileList = arr.map(str => {
                    return {
                        name: str.substr(str.lastIndexOf("/") + 1),
                        url: str + `?x-oss-process=image/resize,m_lfit,h_${this.size},w_${this.size}`,
                        rawUrl: str
                    }
                });
            }
        }
    },
    methods: {
        handleAvatarSuccess(res, file, fileList) {
            fileList[fileList.length-1].rawUrl = res.data;

            var returnValue = fileList.map(item=>item.rawUrl).join(",");
            this.$emit("input", returnValue);
        },
        beforeAvatarUpload(file) {
            this.loading = true;
            // const isJPG = file.type === "image/jpeg";
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过10MB!");
            }

            return isLt10M;
        },
        handleRemove(file,fileList) {
            var returnValue = fileList.map(item=>item.rawUrl).join(",");
            this.$emit("input", returnValue);
        }
    },
    mounted() {
        this.uploadData.subFolder = (this.subFolder.substr(0,1)!="/" ? "/" : "") + this.subFolder;
    }
}
</script>
<style scoped>
.avatar {
    object-fit: contain;
}
</style>