<template>
	<div>
        <!-- 只上传和删除文件 -->
        <el-upload
            action drag :show-file-list="false"
            class="upload"
            :accept="accept"
            :http-request="upload"
        >
            <slot></slot>
        </el-upload>
    </div>
</template>

<script>
import client from '@/assets/oss'
import defaultOssConfig from '@/assets/ossConfig.js'
import store from '@/store/index.js'
export default {
    name: 'UploadFile',
    props: {
        accept: {type: String, default: '*'}, // 接受的文件类型
        ossConfig: {type: Object, default: () => defaultOssConfig.bussinessFileBucket}, // 文件存储空间
        filePath: {type: String, default: `${store.state.shcoolCode}/TestUpload`} // 文件存储路径
    },
    data () {
        return {
            ossClient: {} // OSS 客户端
        }
    },
    mounted () {
        this.initOSS()
    },
    methods: {
        // 初始化 OSS
        initOSS () {
            // 获取 OSS 秘钥
            this.$api.aliOssApi.getToken().then(res => {
                if (res.data.Status) {
                    // 初始化 OSS 客户端
                    const data = res.data.Data
                    this.ossClient = client({
                        accessKeyId: data.AccessKeyId,
                        accessKeySecret: data.AccessKeySecret,
                        stsToken: data.SecurityToken,
                        endpoint: this.ossConfig.endpoint,
                        bucket: this.ossConfig.bucket,
                        region: this.ossConfig.region
                    })
                }
            })
        },
        // 格式化 OSS 上传参数
        formatParams (file) {
            const date = new Date()
            const add0 = n => n > 9 ? n : '0' + n
            const today = [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(add0).join('')
            const point = file.name.lastIndexOf('.')
            file.fileName = file.name.slice(0, point)
            file.suffix = file.name.slice(point)
            let randomNumber = ''
            for (var i = 0; i < 10; i++) randomNumber += Math.floor(Math.random() * 10)
            const storeAs = `${this.filePath}/${today}/pc_file_${randomNumber}_${date.getTime()}${file.suffix}`
            return {storeAs, file}
        },
        // 上传进度
        progress (percent) {
            this.$emit('progress', percent)
        },
        // 上传
        upload (res) {
            const {storeAs, file} = this.formatParams(res.file)
            this.ossClient.multipartUpload(storeAs, file, {progress: this.progress}).then(result => {
                if (result.res && result.res.status === 200) {
                    this.$emit('uploadSuccess', {
                        url: `${this.ossConfig.domain}/${result.name}`,
                        objectKey: result.name,
                        name: file.fileName,
                        suffix: file.suffix,
                        size: file.size
                    })
                }
            })
        },
        // 删除
        deleteFile (objectKey) {
            objectKey ? this.ossClient.delete(objectKey) : this.$message.error('objectKey 不能为空')
        }
    }
}
</script>

<style lang="less" scoped>
.upload {
    font-size: 0;
    /deep/ .el-upload{
        &:focus {
            color: inherit;
            border-color: inherit;
            .el-upload-dragger {
                border-color: inherit;
            }
        }
        .el-upload-dragger {
            width: auto;
            height: auto;
        }
    }
}
</style>
