<template>
	<div>
		<el-upload
			:action="action"
			list-type="picture-card"
			:http-request="httpRequest"
			:limit="limit"
			:file-list="fileList"
			:disabled="disabled"
			:on-exceed="exceed"
			:on-success="success"
			:headers="{ token: token }"
			:multiple="multiple"
			:on-preview="handlePictureCardPreview"
			:on-remove="handleRemove"
			:before-upload="beforeUpload"
		>
			<i class="el-icon-plus"></i>
		</el-upload>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="" />
		</el-dialog>
	</div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
	name: 'elx-upload',
	props: {
		limit: null,
		multiple: {
			type: Boolean,
			default: true
		},
		fileList: {
			type: Array,
			default: []
		},
		value: [Array, String],
		beforeUpload: Function,
		disabled: Boolean,
		category: Array
	},

	data() {
		const upload = this.$service.common.upload();

		return {
			action: upload.url,
			list: [],
			index: 0,
			// 图片展示
			dialogImageUrl: '',
			dialogVisible: false
		};
	},
	computed: {
		...mapGetters(['token'])
	},
	mounted() {
		this.init();
	},
	methods: {
		init() {},
		httpRequest(params) {
			const file = params.file;
			this.getBase64(file).then(res => {
				this.$service.common
					.uploadImg({ content: res, categoryId: this.category })
					.then(subRes => {
						params.onSuccess(subRes);
					});
			});
		},
		handleRemove(file, fileList) {
			this.$emit('handleRemove', { file, fileList });
		},
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.showBBGG || file.url;
			this.dialogVisible = true;
		},
		exceed() {
			this.$message.warning(`最多只能上传${this.limit}张图片`);
		},
		success(response, file, fileList) {
			this.$emit('update:fileList', fileList);
			this.$emit('success', { response, file, fileList });
		},
		getBase64(file) {
			return new Promise(function(resolve, reject) {
				let reader = new FileReader();
				let imgResult = '';
				reader.readAsDataURL(file);
				reader.onload = function() {
					imgResult = reader.result;
				};
				reader.onerror = function(error) {
					reject(error);
				};
				reader.onloadend = function() {
					resolve(imgResult);
				};
			});
		}
	}
};
</script>

<style scoped></style>
