clarms-plugins-upload.js 7.13 KB
import api from '@/api/api'
import {
	httpGet,
	httpPost,
	formdata
} from '@/api/fetch-api.js'

import Vue from 'vue';
import {
	Loading
} from 'vant';
Vue.use(Loading);

export default {

	props: {
		// 是否显示组件
		options: {
			type: Object,
			default() {
				return {
					// 名称
					name: "",
					// 图标编号
					icon: "",
					// 主单证类型
					imageMainTypeID: "",
					// 副单证类型
					imageTypeID: "",
					// toast消息
					toast: "",
				};
			}
		},
		icon: {
			type: String,
			default: ""
		}
	},
	data() {
		return {
			uploadFiles: 0,
			images: [],
			tipsVisible: false,
		}
	},
	components: {},
	computed: {
		uploading() {
			let len = this.images.length;
			if (len < 0) {
				return false;
			}
			for (let index = 0; index < len; index++) {
				let d = this.images[index] || null;
				if (!d) {
					continue;
				}
				if (d.intervial) {
					return true;
				}
			}
			return false;
		},
		i18n() {
			return this.$i18n.messages && this.$i18n.locale ? this.$i18n.messages[this.$i18n.locale] : {};
		},
	},
	methods: {
		initData() {
			for (let index = 0; index < sessionStorage.length; index++) {
				let key = sessionStorage.key(index);
				if (key.indexOf("clarmImage." + this.options.imageTypeID) == 0) {
					let str = sessionStorage.getItem(key);
					sessionStorage.removeItem(key);
					try {
						let d = JSON.parse(str);
						this.images.push(d);
					} catch (e) {
						console.error(e);
					}
				}
			}
		},
		cacheData() {
			for (let index = 0; index < this.images.length; index++) {
				let tmp = this.images[index];
				if (tmp.showMask || !tmp.cacheKey) { continue; }

				let key = "clarmImage." + this.options.imageTypeID + "." + index;
				sessionStorage.setItem(key, JSON.stringify({
					fileName: tmp.fileName,
					data: tmp.data,
					cacheKey: tmp.cacheKey
				}));
			}
		},
		clearCache() {
			for (let index = 0; index < sessionStorage.length; index++) {
				let key = sessionStorage.key(index);
				if (key.indexOf("clarmImage." + this.options.imageTypeID) == 0) {
					sessionStorage.removeItem(key);
				}
			}
			this.uploadFiles = 0;
			this.images = [];
		},
		selectMutilFile() {
			if (this.uploading) {
				return;
			}
			this.$emit("beforeUpload", {
				type: this.options.imageTypeID
			});
			console.log("options:", this.options);
			let _this = this;
			let input = document.createElement("input");
			input.setAttribute("type", "file");
			input.setAttribute("multiple", "multiple");
			// input.setAttribute("accept", "image/*");
			input.setAttribute("accept", "image/png,image/jpeg");
			input.onchange = function (val) {
				let position = _this.images.length;
				for (let index = 0; index < input.files.length; index++) {
					setTimeout(function () {
						_this.initFileUpload(input.files[index], position + index);
					}, index * 50);
				};
			};
			input.click();
		},
		initFileUpload(file, index) {
			let _this = this;
			var reader = new FileReader();
			reader.onload = function (e) {
				_this.compressImage(reader.result, function (data) {
					let d = {
						fileName: "",
						file: file,
						data: data,
						cacheKey: "",
						showMask: false,
						key: _this.randomAesKey(),
						intervial: false,
						tips: "",
						err: ""
					};
					_this.$set(_this.images, index, d);
					_this.handleFileUpload(d, index);
				});
			}
			reader.readAsDataURL(file);
		},
		handleFileUpload(item, index) {
			item.intervial = setInterval(function () {
				item.tips = item.tips + ".";
				if (item.tips.length > 3) {
					item.tips = "";
				}
			}, 1000);
			this.$set(this, "images", this.images);
			let param = {
				file: item.file,
				key: item.key
			}
			formdata({
				url: api.uploadClarmsImage,
				data: param
			}).then(res => {
				if (res && res.content && res.content.id) {
					item.fileName = res.content.fileName;
					item.cacheKey = res.content.id;
					clearInterval(item.intervial);
					item.intervial = false;
					this.$set(this, "images", this.images);
					this.refreshUploadNumber();
				} else {
					clearInterval(item.intervial);
					item.intervial = false;
					item.err = "失败";
					this.$set(this, "images", this.images);
					this.refreshUploadNumber();
				}
			}).catch(err => {
				clearInterval(item.intervial);
				item.intervial = false;
				item.err = "失败";
				this.$set(this, "images", this.images);
				this.refreshUploadNumber();
			});
		},
		refreshUploadNumber() {
			let d = this.images.length;
			let number = 0;
			for (let index = 0; index < d; index++) {
				let v = this.images[index] || null;
				if (v && v.cacheKey) {
					number++;
				}
			}
			this.uploadFiles = number;
			this.emitResult();
		},
		onOverHandler(event, item, index) {
			item.showMask = true;
			event.preventDefault();
		},
		onOutHandler(event, item, index) {
			item.showMask = false;
			event.preventDefault();
		},
		removeItem(index) {
			let images = JSON.parse(JSON.stringify(this.images));
			images.splice(index, 1);
			this.$set(this, "images", images);
			this.refreshUploadNumber();
		},
		randomAesKey() {
			let chars = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".split(",");
			let res = "";
			for (let i = 0; i < 16; i++) {
				let id = Math.ceil(Math.random() * (chars.length - 1));
				res += chars[id];
			}
			return res;
		},
		emitResult() {
			if (this.images.length == 0) {
				let result = {
					type: this.options.imageTypeID,
					list: []
				};
				this.$emit("success", result);
				return;
			}
			if (this.uploading) {
				return;
			}
			let list = [];
			let len = this.images.length;
			if (len < 0) {
				return false;
			}
			for (let index = 0; index < len; index++) {
				let d = this.images[index] || null;
				if (!d || !d.cacheKey) {
					continue;
				}
				// 结果
				let res = {
					cloudStorageID: d.cacheKey,
					imageFileName: d.fileName,
					imageMainTypeID: this.options.imageMainTypeID,
					imageTypeID: this.options.imageTypeID
				}
				list.push(res);
			}
			let result = {
				type: this.options.imageTypeID,
				list: list
			};
			this.$emit("success", result);
		},
		onShowTipsOverHandler(event) {
			this.tipsVisible = true;
		},
		onShowTipsOutHandler(event) {
			this.tipsVisible = false;
		},
		compressImage(src, callback) {
			var img = new Image();
			img.src = src;
			img.onload = function () {
				var that = this;
				// 默认按比例压缩
				var w = img.width,
					h = img.height,
					scale = w / h;
				w = w < 50 ? w : 50;
				h = (w / scale);
				var quality = 0.7;  // 默认图片质量为0.7
				//生成canvas
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				// 创建属性节点
				var anw = document.createAttribute("width");
				anw.nodeValue = w;
				var anh = document.createAttribute("height");
				anh.nodeValue = h;
				canvas.setAttributeNode(anw);
				canvas.setAttributeNode(anh);
				ctx.drawImage(that, 0, 0, w, h);
				// quality值越小,所绘制出的图像越模糊
				var base64 = canvas.toDataURL('image/*', quality);
				// console.log(base64.length);
				// 回调函数返回base64的值
				callback(base64);
			}
		},
		datePickCompleteHandler() {

		}
	},
	watch: {

	},
	mounted() {
		this.initData();
	},
	created() { }
}