<template>
	<view class="_vphoto" :class="{left}">
		qrcode，上面扫码，和上一次相同，忽略，不同event
		<input type="hidden" :maxlength="-1" :name="name" :value="tvalue.value" style="display:none;" />
		<view class="_btn" @tap="photo_select" v-if="tvalue.imgs.length < num">
			<view class="_icon _photo"></view>
		</view>
		<view class="_pimg" v-for="(item,index) in tvalue.imgs" :key="index" :style="{'width':showwh}">
			<view class="_del" :data-idx="index" @tap="photo_delone"></view>
			<image v-if="isimg(item)" :src="file_stor(item, '?50')" @tap="preview(index)" mode="widthFix"></image>
			<view class="_video" v-else-if="isvideo(item)">AV</view>
			<view class="_file" v-else>{{file_ext(item)}}</view>
		</view>
		<view class="_tip">{{tip}}</view>
		<canvas type="2d" id="canvas" :style="{'width':cvwidth+'px','height':cvheight+'px','top':-cvheight+'px'}" style="position:fixed;z-index:-999;left:100vw;"></canvas>
	</view>
</template>

<script>
	export default {
		behaviors: ['uni://form-field-group'],
		emits: ['change', 'update:modelValue'],
		props: {
			name: {
				type: String
			},
			modelValue: {
				type: String,
				default: ''
			},
			value: {
				type: String,
				default: ''
			},
			initevent: {
				type: Boolean,
				default: false
			},
			left: {
				type: Boolean,
				default: false
			},
			action: { //设置 work.t   work   httpxxx
				type: String,
				default: ''
			},
			sourcetype: {
				type: String,
				default: 'camera,album,message'
			},
			filetype: {
				type: String,
				default: 'image' //all   image    video
			},
			ext: {
				type: String,
				default: ''
			},
			num: {
				type: [String, Number],
				default: 1
			},
			stor: {
				type: String,
				default: '/'
			},
			imgwidth: {
				type: [String, Number],
				default: 0
			},
			imgheight: {
				type: [String, Number],
				default: 0
			},
			maxkb: {
				type: [String, Number],
				default: 0
			},
			zipjpg: {
				type: [String, Number],
				default: 0
			},
			waterfont: {
				type: String,
				default: '28px Arial'
			},
			watertext: {
				type: String,
				default: ''
			},
			showwh: {
				type: String,
				default: '4em'
			},
			path: {
				type: String,
				default: 'nopath'
			},
			saas: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				tip: '',
				updatevalue: false,
				val: '',
				cvwidth: 0,
				cvheight: 0
			};
		},
		watch: {
			value: {
				async handler(newD, oldD) {
					this.val = newD;
				},
				immediate: true
			},
			modelValue: {
				async handler(newD, oldD) {
					if (this.updatevalue) {
						this.updatevalue = false;
						return;
					}
					this.val = newD;
				},
				immediate: true
			},
		},
		computed: {
			tvalue() {
				var v = this.val;
				var ret = {};
				ret.value = v;
				var pimgs = v.split('~');
				ret.imgs = [];
				for (var i in pimgs) {
					if (!pimgs[i])
						continue;
					ret.imgs.push(pimgs[i]);
				}
				return ret;
			}
		},
		mounted() {
			if (this.initevent) {
				this.$emit('change', {
					name: this.name,
					from: 'init',
					value: this.tvalue.value
				});
			}
		},
		methods: {
			preview(idx) {
				var imgs = [...this.tvalue.imgs];
				for (var i in imgs) {
					imgs[i] = this.file_stor(imgs[i]);
				}
				uni.previewImage({
					current: idx,
					indicator: 'default',
					urls: imgs
				});
			},
			async photo_select(b) {
				if (this.tip)
					return this.toast(this.lang('upload.uploadingmsg'));

				var items = [];
				var sourcetypes = this.sourcetype.split(',');
				if (sourcetypes.includes('camera')) {
					items.push({
						url: 'camera',
						name: this.lang('upload.menu_camera')
					});
				}
				if (sourcetypes.includes('album')) {
					items.push({
						url: 'album',
						name: this.lang('upload.menu_album')
					});
				}
				if (sourcetypes.includes('message')) {
					items.push({
						url: 'message',
						name: this.lang('upload.menu_message')
					});
				}
				var item = await this.popmenu({
					items,
					one: true
				});
				if (item.url == 'camera')
					this.vcamera();
				if (item.url == 'album')
					this.valbum();
				if (item.url == 'message')
					this.vmessage();
			},
			photo_delone(b) {
				if (this.tip)
					return this.toast(this.lang('upload.uploading'));
				var imgs = [...this.tvalue.imgs];
				imgs.splice(b.currentTarget.dataset.idx, 1);
				this.val = imgs.join('~');
				this.updatevalue = true;
				this.$emit('update:modelValue', this.val);
				this.$emit('change', {
					name: this.name,
					from: 'del',
					value: this.val
				});
			},
			addfile(url, from) {
				var imgs = [url, ...this.tvalue.imgs];
				this.val = imgs.join('~');
				if (!from)
					return;
				this.updatevalue = true;
				this.$emit('update:modelValue', this.val);
				this.$emit('change', {
					name: this.name,
					from: from,
					value: this.val
				});
			},
			async vcamera(b) {
				if (!uni.chooseMedia) {
					return this.vh5();
				}
				var count = this.toint(this.num) - this.tvalue.imgs.length;
				if (count <= 0)
					return this.toast(this.lang('upload.maxmsg').replace('{n}', this.num));
				var opt = {};
				opt.count = 1;
				if (this.filetype == 'all') {
					opt.mediaType = ['mix'];
				}
				if (this.filetype == 'image') {
					opt.mediaType = ['image'];
				}
				if (this.filetype == 'video') {
					opt.mediaType = ['video'];
				}
				opt.sizeType = ['original', 'compressed'];
				opt.sourceType = ['camera'];
				opt.maxDuration = 60;
				var [err, retchoose] = await this.go(uni.chooseMedia(opt));
				if (err)
					return console.warn('chooseMedia', err);
				this.upfiles(retchoose.tempFiles, 'camera');
			},
			async valbum(b) {
				if (!uni.chooseMedia) {
					return this.vh5();
				}
				var count = this.toint(this.num) - this.tvalue.imgs.length;
				if (count <= 0)
					return this.toast(this.lang('upload.maxmsg').replace('{n}', this.num));
				var opt = {};
				opt.count = count;
				if (this.filetype == 'all') {
					opt.mediaType = ['mix'];
				}
				if (this.filetype == 'image') {
					opt.mediaType = ['image'];
				}
				if (this.filetype == 'video') {
					opt.mediaType = ['video'];
				}
				opt.sizeType = ['original', 'compressed'];
				opt.sourceType = ['album'];
				var [err, retchoose] = await this.go(uni.chooseMedia(opt));
				if (err)
					return console.warn('chooseMedia', err);
				this.upfiles(retchoose.tempFiles, 'album');
			},
			async vmessage(b) {
				if (!uni.chooseMessageFile) {
					return this.vh5();
				}
				var count = this.toint(this.num) - this.tvalue.imgs.length;
				if (count <= 0)
					return this.toast(this.lang('upload.maxmsg').replace('{n}', this.num));
				var opt = {};
				opt.count = count;
				if (this.filetype == 'all') {
					if (this.ext) {
						opt.type = 'file';
						opt.extension = this.ext.split(',');
					} else {
						opt.type = 'all';
					}
				}
				if (this.filetype == 'image') {
					opt.type = 'image';
				}
				if (this.filetype == 'video') {
					opt.type = 'video';
				}
				var [err, retchoose] = await this.go(uni.chooseMessageFile(opt));
				if (err)
					return console.warn('chooseMessageFile', err);
				this.upfiles(retchoose.tempFiles, 'message');
			},
			async vh5(b) {
				var count = this.toint(this.num) - this.tvalue.imgs.length;
				if (count <= 0)
					return this.toast(this.lang('upload.maxmsg').replace('{n}', this.num));
				var opt = {};
				opt.count = count;
				opt.sizeType = ['original', 'compressed'];
				opt.sourceType = ['camera', 'album'];
				var [err, retchoose] = await this.go(uni.chooseImage(opt));
				if (err)
					return console.warn('chooseImage', err);
				await this.upfiles(retchoose.tempFiles, 'h5');
			},
			async upfiles(temps, from) {
				var thos = this;
				var app = getApp();
				this.upcount = temps.length;
				this.tip = this.lang('upload.tip') + ' 0/' + this.upcount;
				this.upidx = 0;
				var now = new Date();
				var path = now.getFullYear() + '/' + ('0' + (now.getMonth() + 1)).slice(-2) + ('0' + now.getDate()).slice(-2) + '/' + this.path;
				if (this.saas) {
					var saasid = this.toint(this.saas.substring(1));
					path = this.saas.substring(0, 1) + this.toint(saasid / 1000) + '/' + saasid + '/' + path;
				}
				var opn = {};
				opn.canvasid = 'canvas';
				opn.post = {
					from: from
				};
				opn.path = path;
				opn.stor = this.stor;
				opn.action = this.action;
				if (opn.action.substring(0, 4) != 'http') {
					var uus = opn.action.split('.');
					if (uus.length == 1)
						uus[1] = this.srv;
					opn.action = app.globalData.jsnurl[uus[1]] + 'z/?func=' + uus[0] + '/upload.';
				}
				opn.maxkb = this.toint(this.maxkb);
				opn.imgwidth = this.toint(this.imgwidth);
				opn.imgheight = this.toint(this.imgheight);
				opn.zipjpg = this.tofloat(this.zipjpg);
				opn.watertext = this.watertext;
				await this.file_uploads(temps, opn, {
					success(url, file) {
						thos.upidx++;
						thos.tip = thos.lang('upload.tip') + ' ' + thos.upidx + '/' + thos.upcount;
						if (thos.upidx == thos.upcount) {
							thos.tip = '';
							thos.addfile(url, from);
						} else {
							thos.addfile(url);
						}
					},
					fail(err, gf, al) {
						console.warn(err, gf, al);
						thos.upidx++;
						thos.tip = '';
						return thos.alert('Upload Fail:' + err);
					}
				});
			}
		}
	}
</script>

<style scoped>
	._vphoto ._photo {
		background-image: url("data:image/svg+xml;charset=utf-8;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyB2ZXJzaW9uPScxLjEnIHhtbG5zPSdodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2Zycgd2lkdGg9JzIwMCcgaGVpZ2h0PScyMDAnPjxwYXRoIGQ9J00xMjUuOTUyIDIzNC40OTZoMTY2LjkxMmMyMS41MDQgMCAyOS42OTYtNDguMTI4IDU0LjI3Mi03MS42OCA3LjE2OC03LjE2OCAyOC42NzItMTIuMjg4IDM2Ljg2NC0xMi4yODhoMjc4LjUyOGM4LjE5MiAwIDI5LjY5NiAxMS4yNjQgMzYuODY0IDI1LjYgMTMuMzEyIDI0LjU3NiAxMi4yODggNTguMzY4IDI1LjYgNTguMzY4aDE4MS4yNDhjNDYuMDggMCA4My45NjggMzcuODg4IDgzLjk2OCA4My45Njh2NDc0LjExMmMwIDQ2LjA4LTM3Ljg4OCA4My45NjgtODMuOTY4IDgzLjk2OEgxMjUuOTUyYy00Ni4wOCAwLTgzLjk2OC0zNy44ODgtODMuOTY4LTgzLjk2OFYzMTcuNDRjMS4wMjQtNDYuMDggMzcuODg4LTgyLjk0NCA4My45NjgtODIuOTQ0eicgZmlsbD0nIzNFQkRGRic+PC9wYXRoPjxwYXRoIGQ9J002MzQuODggMjc1LjQ1NmgxNC4zMzZjMTEuMjY0IDAgMjAuNDggOS4yMTYgMjAuNDggMjAuNDhzLTkuMjE2IDIwLjQ4LTIwLjQ4IDIwLjQ4SDYzNC44OGMtMTEuMjY0IDAtMjAuNDgtOS4yMTYtMjAuNDgtMjAuNDggMC0xMC4yNCA5LjIxNi0yMC40OCAyMC40OC0yMC40OHpNNzMyLjE2IDI3NS40NTZoMTY2LjkxMmMxMS4yNjQgMCAyMC40OCA5LjIxNiAyMC40OCAyMC40OHMtOS4yMTYgMjAuNDgtMjAuNDggMjAuNDhINzMyLjE2Yy0xMS4yNjQgMC0yMC40OC05LjIxNi0yMC40OC0yMC40OCAwLTEwLjI0IDkuMjE2LTIwLjQ4IDIwLjQ4LTIwLjQ4eicgZmlsbD0nI0ZGRkZGRic+PC9wYXRoPjxwYXRoIGQ9J001MzAuNDMyIDM1OS40MjRjMTIyLjg4IDAgMjIzLjIzMiA5OS4zMjggMjIzLjIzMiAyMjMuMjMyIDAgMTIyLjg4LTk5LjMyOCAyMjMuMjMyLTIyMy4yMzIgMjIzLjIzMi0xMjIuODggMC0yMjMuMjMyLTk5LjMyOC0yMjMuMjMyLTIyMy4yMzIgMC0xMjIuODggMTAwLjM1Mi0yMjMuMjMyIDIyMy4yMzItMjIzLjIzMnonIGZpbGw9JyNBMkRFRkQnPjwvcGF0aD48L3N2Zz4=");
	}

	._vphoto {
		margin: 0.5em auto 0 auto;
		padding: 0;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		justify-content: flex-end;
		position: relative;
	}

	._vphoto.left {
		justify-content: flex-start;
	}

	._vphoto ._tip {
		position: absolute;
		top: 0.1em;
		left: 0.2em;
		line-height: 1em;
		font-size: 0.7em;
		color: #999999;
	}

	._vphoto>._btn {
		padding: 0.5em;
		width: 3em;
		height: 3em;
		margin: 0 0.5em 0.5em 0;
		border: 1px solid #cccccc;
		display: inline-block;
		border-radius: 0.3em;
		background: #ffffff;
	}

	._vphoto ._icon {
		width: 100%;
		height: 100%;
		margin: 0 auto;
		background-size: cover;
	}

	._vphoto ._pimg {
		margin: 0 0.5em 0.5em 0;
		background: #ffffff;
		position: relative;
		border: 1px solid #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	._vphoto ._pimg ._video,
	._vphoto ._pimg ._file {
		margin: 1.2em 0;
	}

	._vphoto ._pimg image {
		width: 100%;
		height: 100%;
		border-radius: 0.3em;
	}

	._vphoto ._pimg ._del {
		background-image: url("data:image/svg+xml;charset=utf-8;base64,PHN2ZyB2aWV3Qm94PScwIDAgMTAyNCAxMDI0JyB2ZXJzaW9uPScxLjEnIHhtbG5zPSdodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2Zyc+PHBhdGggZD0nTTUxMiAzMC4xMTc2NDdhNDgxLjg4MjM1MyA0ODEuODgyMzUzIDAgMSAwIDQ4MS44ODIzNTMgNDgxLjg4MjM1MyA0ODEuODgyMzUzIDQ4MS44ODIzNTMgMCAwIDAtNDgxLjg4MjM1My00ODEuODgyMzUzeicgZmlsbD0nI0ZENDgzNyc+PC9wYXRoPjxwYXRoIGQ9J003MDUuMTc0NTg4IDY1Ny43MDkxNzZhMzMuOTcyNzA2IDMzLjk3MjcwNiAwIDEgMS00OC4xODgyMzUgNDcuODI2ODI0TDUxMiA1NjAuMDA3NTI5bC0xNDUuMjI3Mjk0IDE0NS44ODk4ODNhMzMuOTcyNzA2IDMzLjk3MjcwNiAwIDEgMS00OC4xODgyMzUtNDcuODI2ODI0bDE0NS40MDgtMTQ1Ljc2OTQxMkwzMTguNzY1MTc2IDM2Ni4yMzA1ODhhMzMuOTcyNzA2IDMzLjk3MjcwNiAwIDAgMSA0OC4xODgyMzYtNDcuODI2ODIzTDUxMiA0NjMuOTkyNDcxbDE0NS4yMjcyOTQtMTQ1LjcwOTE3N2EzMy45NzI3MDYgMzMuOTcyNzA2IDAgMSAxIDQ4LjE4ODIzNSA0Ny44MjY4MjRMNTU5Ljc2NjU4OCA1MTJ6JyBmaWxsPScjRkZGRkZGJz48L3BhdGg+PC9zdmc+");
		width: 1.2em;
		height: 1.2em;
		position: absolute;
		top: -0.3em;
		right: -0.3em;
		z-index: 10;
	}
</style>