<template>
	<div>
		<el-upload
			ref="fileUpload"
			:show-file-list="true"
			:file-list="fileList"
			:limit="limit"
			:headers="upload.headers"
			:action="upload.url"
			:before-upload="handleBeforeUpload"
			:on-error="handleUploadError"
			:on-exceed="handleExceed"
			:on-success="handleUploadSuccess"
			:on-progress="handleFileUploadProgress"
			:on-remove="handleDelete"
			accept=".apk, .ipa"
		>
			<el-button icon="el-icon-upload" :loading="upload.isUploading" :disabled="upload.isUploading">{{ name }}</el-button>
			<div class="el-upload__tip" style="margin-top: 0px; margin-bottom: -10px" slot="tip">只能上传.apk, .ipa文件，且不超过200M</div>
		</el-upload>
	</div>
</template>

<script>
import { getToken } from '@/utils/auth';
export default {
	props: {
		value: {
			type: Object
		},
		limit: {
			type: Number,
			default: 1
		},
		name: {
			type: String,
			default: '上传安装包'
		}
	},
	data() {
		return {
			baseUrl: process.env.VUE_APP_BASE_API,
			open: false,
			fileList: [],
			upload: {
				headers: { Authorization: 'Bearer ' + getToken() },
				url: process.env.VUE_APP_BASE_API + '/work/upgrade/upload',
				isUploading: false
			}
		};
	},
	methods: {
		// 上传前校检格式和大小
		handleBeforeUpload(file) {
			this.upload.isUploading = true;
			return true;
		},
		// 文件个数超出
		handleExceed() {
			this.$modal.msgError('上传文件数量不能超过' + this.limit + '个');
		},
		// 上传失败
		handleUploadError(err) {
			this.$modal.msgError('上传失败，请重试');
			this.upload.isUploading = false;
		},
		// 上传成功回调
		handleUploadSuccess(res, file) {
			this.upload.isUploading = false;
			if (res.code === 200) {
				this.$emit('input', res.data);
				this.$modal.msgSuccess('上传成功');
			} else {
				this.$modal.msgError(res.msg);
				this.$refs.fileUpload.handleRemove(file);
			}
		},
		// 文件上传中处理
		handleFileUploadProgress(event, file, fileList) {
			this.upload.isUploading = true;
		},
		// 删除文件
		handleDelete(file, fileList) {
			this.$emit('input', fileList);
		}
	}
};
</script>
