<template>
    <u-upload @afterRead="afterRead" :maxCount="maxCount" :accept="accept" multiple>
        <view v-if="showLoading">
            <u-loading-icon v-if="loading" />
            <slot v-else />
        </view>
        <slot v-else />
    </u-upload>
</template>
<script>
export default {
    name: "MyUpload",
    props: {
        accept: { //接受的文件类型，file只支持H5（只有微信小程序才支持把accept配置为all、media）
            type: String,
            default: "image"
        },
        maxCount: {
            type: String,
            default: "99"
        },
        parentid: { //上传文件夹ID
            type: [String, Number],
            default: uni.getStorageSync('siteP').appfolderid
        },
        uploadCallback: { //上传回调
            type: Function
        },
        showLoading: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            loading: false
        }
    },
    methods: {
        afterRead({ file }) {
            const that = this;
            file.forEach(v => {
                // #ifdef H5
                this.getArrayBuffer(v).then(data => that.handleUploadFile(this.requestType(v), data))
                // #endif
                // #ifndef H5
                uni.getFileSystemManager().readFile({
                    filePath: v.url,
                    success: data => that.handleUploadFile(this.requestType(v), data.data),
                    fail: console.error
                })
                // #endif
            });
        },
        /* 请求类型 */
        requestType(file) {
            // #ifdef H5
            var ext = file.name.substr(file.name.lastIndexOf(".") + 1);
            // #endif
            // #ifndef H5
            var ext = file.type.split("/")[1] || file.url.substr(file.url.lastIndexOf(".") + 1) || file.name.substr(file.name.lastIndexOf(".") + 1);
            // #endif
            //文件名称
            return {
                "classname": "system.attachment.huawei.OBS",
                "method": "getFileName",
                "content": {
                    "filename": `${Date.now() + file.size}.${ext}`,
                    "filetype": ext,
                    "parentid": this.parentid
                }
            }
        },
        handleUploadFile(file, data) {
            this.loading = true;
            this.$Http.basic(file).then(res => {
                if (res.msg == "成功") {
                    this.uploadFile(res.data, data)
                } else {
                    uni.showToast({
                        title: `${data.filename}.${data.serialfilename}`,
                        icon: "none"
                    })
                }
            })
        },
        getArrayBuffer(file) {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest()
                xhr.open('GET', file.url, true)
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        let myBlob = this.response
                        let files = new window.File([myBlob], file.name, { type: file.url.substr(file.url.lastIndexOf(".") + 1) }) // myBlob.type 自定义文件名
                        const reader = new FileReader();
                        reader.readAsArrayBuffer(files);
                        reader.onload = () => resolve(reader.result);
                        reader.onerror = (error) => reject(error);
                    } else {
                        reject(false)
                    }
                }
                xhr.send()
            })
        },
        /* 上传成功反馈 */
        uploadFile(res, data) {
            var that = this;
            uni.request({
                url: res.uploadurl,
                method: "PUT",
                data,
                header: {
                    'content-type': 'application/octet-stream'
                },
                success() {
                    that.$Http.basic({
                        "classname": "system.attachment.huawei.OBS",
                        "method": "uploadSuccess",
                        "content": {
                            "serialfilename": res.serialfilename
                        }
                    }).then(s => {
                        console.log("文件上传反馈", s)
                        that.loading = false;
                        if (!that.cutoff(s.msg)) that.$emit("uploadCallback", s.data.attachmentids);
                    }).catch(err => {
                        that.loading = false;
                        console.error(err)
                    })
                },
                fail(err) {
                    that.loading = false;
                    console.log(err)
                }
            })
        }
    },
}
</script>