<template>
	<view class="xfx-image-upload-list">
		<!-- 上传按钮 -->
		<view class="xfx-image-upload-Item xfx-image-upload-Item-add" v-if="uploadLists.length<max && add"
			@click="show=true">
			<!-- <uni-icons type='camera' style="font-size:60rpx"> </uni-icons> -->
			<view class="imgAdd" v-if="uploadType === '0'"></view>
			<image class="camera-img" src="../../static/images/car/camera.png" mode="widthFix" v-if="uploadType==='1'">
			</image>
			<image class="camera-img" src="../../static/images/car/vedio.png" mode="widthFix" v-if="uploadType==='2'">
			</image>
			<!-- <u-icon name='camera-fill' size='45'></u-icon> -->
			<text class="text-upload">{{uploadTitle}}</text>
		</view>
		<view class="xfx-image-upload-Item" v-for="(item,index) in uploadLists" :key="index">
			<view class="xfx-image-upload-Item-video" v-if="(!/.(gif|jpg|jpeg|png|gif|jpg|png)$/i.test(item))">
				<!-- <image :disabled="false" :controls="false" :src="item+'?x-oss-process=video/snapshot,t_0,f_jpg'"mode=""> -->
				<image :src="item.cover">
					<!-- <image :disabled="false" :controls="false" :src="item.cover" mode=""> -->
					<view class="xfx-image-upload-Item-video-fixed" @click="previewVideo(item.url)">
						<!-- <uni-icons type='videocam' style="font-size:60rpx"> </uni-icons> -->
						<u-icon size='80' name='play-right-fill' color="#ffffff"></u-icon>
					</view>

					<view class="xfx-image-upload-Item-del-cover" v-if="remove && previewVideoSrc==''"
						@click="imgDel(index)">
						<image src="../../static/images/user/redClose.png" mode="widthFix"></image>
					</view>

				</image>

			</view>

			<image v-else :src="item" @click="imgPreview(item)" mode="aspectFill"></image>

			<view class="xfx-image-upload-Item-del" v-if="remove" @click="imgDel(index)">
				<image src="../../static/images/user/redClose.png" mode="widthFix"></image>
			</view>
		</view>
		<!-- flex布局 起占位作用 -->
		<!-- <view class="xfx-image-upload-Item" v-if="uploadLists.length<max-1">
		</view> -->
		<!-- <view id="canvas" class="canvas" :prop="newVal" :change:prop="canvas.create"></view> -->
		<view class="preview-full" v-if="previewVideoSrc!=''">
			<video :autoplay="true" :src="previewVideoSrc" :show-fullscreen-btn="false">
				<cover-view class="preview-full-close" @click="previewVideoClose"> ×
				</cover-view>
			</video>
		</view>


		<!-- 自定义弹出框 -->
		<u-popup :show="show" class='boxUplod' mode="bottom" @close="show = false">
			<view class="time-top">
				<text class="ml36 fontClass colorWhite" @tap="show = false">取消</text>
				<text class="mr36 fontClass colorOrange" @tap="chooseFile">确认</text>
			</view>
			<view class="bottomOfupload">
				<view class="chooseBtnStyle mt40" @tap="handlerCamera" :class="isActive===1?'activeStyle':''">
					拍摄
				</view>
				<view class="chooseBtnStyle" @tap="handlerPic" :class="isActive===2?'activeStyle':''">
					上传{{uploadType==='2'?'视频':'图片'}}
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	//请求头token
	import {
		getToken
	} from '@/utils/auth'
	// import UniIcons from '@/components/uni-icons/uni-icons.vue'
	import config from '@/config.js'
	export default {
		name: 'xfx-image-upload',
		props: {
			uploadTitle: {
				type: String,
				default: '点击上传'
			},
			// 展示的图片
			uploadType: {
				type: String,
				default: '0'
			},
			max: { //展示图片最大值
				type: Number,
				default: 6,
			},
			chooseNum: { //选择图片数
				type: Number,
				default: 6,
			},
			name: { //发到后台的文件参数名
				type: String,
				default: 'file',
			},
			remove: { //是否展示删除按钮
				type: Boolean,
				default: true,
			},
			add: { //是否展示添加按钮
				type: Boolean,
				default: true,
			},
			disabled: { //是否禁用
				type: Boolean,
				default: false,
			},
			sourceType: { //选择照片来源 【ps：H5就别费劲了，设置了也没用。不是我说的，官方文档就这样！！！】
				type: Array,
				default: () => ['album', 'camera'],
			},
			action: { //上传地址
				type: String,
				default: config.baseUrl + '/file/upload',
			},
			headers: { //上传的请求头部
				type: Object,
				default: () => {
					return {
						Authorization: getToken()
					}
				},
			},
			formData: { //HTTP 请求中其他额外的 form data
				type: Object,
				default: () => {},
			},
			compress: { //是否需要压缩
				type: Boolean,
				default: false,
			},
			quality: { //压缩质量，范围0～100
				type: Number,
				default: 80,
			},
			value: { //受控图片列表
				type: Array,
				default: () => [],
			},
			uploadSuccess: {
				default: (res) => {
					return {
						success: false,
						url: ''
					}
				},
			},
			mediaType: { //文件类型 image/video/all
				type: String,
				default: 'image',
			},
			maxDuration: { //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。 (只针对拍摄视频有用)
				type: Number,
				default: 60,
			},
			camera: { //'front'、'back'，默认'back'(只针对拍摄视频有用)
				type: String,
				default: 'back',
			},
		},
		// components: {
		// 	UniIcons
		// },
		data() {
			return {
				uploadLists: [],
				mediaTypeData: ['image', 'video', 'all'],
				previewVideoSrc: '',
				newVal: null,
				show: false,
				// 选中属性 1是拍摄，2是从相册中选择
				isActive: null,
			}
		},

		mounted: function() {

			this.headers.Authorization = getToken()
			// this.headers.Authorization =
			// 	'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxMDE3Nzg4OTcxNTcxMjM2ODY3LCJ1c2VyX2tleSI6ImQyZWMwNzcwLTU4ZDEtNDFlNS1hNjJhLTAyY2MxODg1MTM4NiIsInVzZXJuYW1lIjoiZ3VhbmxpeXVhbiJ9.wPdKlBle01eXd2Um-5EFs6TeqxMNhWFahODJP2DB1_a6D5ryxgidYavhEqEi49gx4wA7MGswB30T1UaiJmoIzA'
			// // console.log(this.headers)
			this.$nextTick(function() {
				this.uploadLists = this.value;
				if (this.mediaTypeData.indexOf(this.mediaType) == -1) {
					uni.showModal({
						title: '提示',
						content: 'mediaType参数不正确',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								//console.log('用户点击确定');
							} else if (res.cancel) {
								//console.log('用户点击取消');
							}
						}
					});
				}
			});
		},
		watch: {
			value(val, oldVal) {
				this.uploadLists = [];
				this.uploadLists = val;
			},
		},
		methods: {
			// 点击拍摄事件
			handlerCamera() {
				this.isActive = 1
			},
			// 点击选择上传图片
			handlerPic() {
				this.isActive = 2
			},
			previewVideo(src) {
				this.previewVideoSrc = src;
				// this.previewVideoSrc =
				// 	'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-fbd63a76-dc76-485c-b711-f79f2986daeb/ba804d82-860b-4d1a-a706-5a4c8ce137c3.mp4'
			},
			previewVideoClose() {
				this.previewVideoSrc = ''
			},
			imgDel(index) {
				// uni.showModal({
				// 	title: '提示',
				// 	content: '您确定要删除么?',
				// 	success: (res) => {
				// 		if (res.confirm) {
				// this.uploadLists.splice(index, 1)
				// this.$emit("input", this.uploadLists);
				// this.$emit("imgDelete", this.uploadLists);
				let delUrl = this.uploadLists[index]
				this.uploadLists.splice(index, 1)
				this.$emit("input", this.uploadLists);
				this.$emit("imgDelete", {
					del: delUrl,
					tempFilePaths: this.uploadLists,
				});
				// 		} else if (res.cancel) {}
				// 	}
				// });
			},
			imgPreview(index) {
				var imgData = this.uploadLists.filter(item => /.(gif|jpg|jpeg|png|gif|jpg|png)$/i.test(item)) //只预览图片的
				uni.previewImage({
					urls: imgData,
					current: index,
					loop: true,
				});


			},
			chooseFile() {
				this.show = false
				if (this.disabled) {
					return false;
				}
				switch (this.mediaTypeData.indexOf(this.mediaType)) {
					case 1: //视频
						this.videoAdd();
						break;
					case 2: //全部
						// uni.showActionSheet({
						// 	itemList: ['相册', '视频'],
						// 	success: (res) => {
						// 		if (res.tapIndex == 1) {
						// 			this.videoAdd();
						// 		} else if (res.tapIndex == 0) {
						// 			this.imgAdd();
						// 		}
						// 	},
						// 	fail: (res) => {
						// 		console.log(res.errMsg);
						// 	}
						// });
						break;
					default: //图片
						this.imgAdd();
						break;
				}


				//if(this.mediaType=='image'){


			},
			videoAdd() {
				console.log(this.sourceType, '<-------我是类型')
				let nowNum = Math.abs(this.uploadLists.length - this.max);
				let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
				uni.chooseVideo({
					compressed: this.compress,
					// sourceType: this.sourceType,
					sourceType: this.isActive === 1 ? ['camera'] : ['album'],
					camera: this.camera,
					maxDuration: this.maxDuration,
					success: (res) => {
						console.log(res);
						// 图片限制100MB
						if (res.size >= 104857600) {
							console.log('超过了100mb');
							uni.showToast({
								title: '视频大小不能超过100MB',
								duration: 2000,
								icon: 'none'
							})
						} else {
							console.log('视频大小小于100mb,可以上传');
							this.$emit('getVedioName', res.tempFilePath.slice(77))
							this.chooseSuccessMethod([res.tempFilePath], 1)
						}
						//this.imgUpload([res.tempFilePath]);
						// if (this.action == '') { //未配置上传路径
						// 	this.$emit("chooseSuccess", res.tempFilePaths);
						// } else {
						// 	if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M，进行压缩上传
						// 		this.imgCompress(res.tempFilePaths);
						// 	} else {
						// 		this.imgUpload(res.tempFilePaths);
						// 	}
						// }
					},
					complete: (res) => {
						this.show = false
						this.isActive = null
					}
				});
			},
			imgAdd() {
				let nowNum = Math.abs(this.uploadLists.length - this.max);
				let thisNum = (this.chooseNum > nowNum ? nowNum : this.chooseNum) //可选数量
				console.log('进入上传图片了');
				// #ifdef APP-PLUS
				if (this.sourceType.length > 1) {
					// uni.showActionSheet({
					// 	itemList: ['拍摄', '从手机相册选择'],
					// 	success: (res) => {
					// 		if (res.tapIndex == 1) {
					// 			this.appGallery(thisNum);
					// 		} else if (res.tapIndex == 0) {
					// 			this.appCamera();
					// 		}
					// 	},
					// 	fail: (res) => {
					// 		console.log(res.errMsg);
					// 	}
					// });
					if (this.isActive === 1) {
						this.appCamera()
					} else if (this.isActive === 2) {
						this.appGallery(thisNum)
					}
				}
				if (this.sourceType.length == 1 && this.sourceType.indexOf('album') > -1) {
					this.appGallery(thisNum);
				}

				if (this.sourceType.length == 1 && this.sourceType.indexOf('camera') > -1) {
					this.appCamera();
				}
				// #endif
				// #ifndef APP-PLUS
				console.log(this.sourceType, '<--------我是照片')
				uni.chooseImage({
					count: thisNum,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					// sourceType: this.sourceType,
					sourceType: this.isActive === 1 ? ['camera'] : ['album'],
					success: (res) => {
						console.log(11111111);
						if (res.size >= 5242880) {
							uni.showToast({
								title: '图片大小不能超过5MB',
								duration: 2000,
								icon: 'none'
							})
						} else {
							this.$emit('getImgName', res.tempFiles[0].name)
							this.chooseSuccessMethod(res.tempFilePaths, 0, res.tempFiles[0].name)
						}
						// if (this.action == '') { //未配置上传路径
						// 	this.$emit("chooseSuccess", res.tempFilePaths);
						// } else {
						// 	if (this.compress && (res.tempFiles[0].size / 1024 > 1025)) { //设置了需要压缩 并且 文件大于1M，进行压缩上传
						// 		this.imgCompress(res.tempFilePaths);
						// 	} else {
						// 		this.imgUpload(res.tempFilePaths);
						// 	}
						// }
					}
				});
				// #endif
			},
			appCamera() {
				var cmr = plus.camera.getCamera();
				var res = cmr.supportedImageResolutions[0];
				var fmt = cmr.supportedImageFormats[0];
				cmr.captureImage((path) => {
						//alert("Capture image success: " + path);
						this.chooseSuccessMethod([path], 0)
					},
					(error) => {
						//alert("Capture image failed: " + error.message);
						console.log("Capture image failed: " + error.message)
					}, {
						resolution: res,
						format: fmt
					}
				);
				this.show = false
				this.isActive = null
			},
			appGallery(maxNum) {
				plus.gallery.pick((res) => {
					console.log('相册选择---------', res);
					res.files.forEach(item => {
						uni.getFileInfo({
							filePath: item,
							success: imgInfo => {
								console.log(imgInfo.size);
								if (imgInfo.size >= 5242880) {
									uni.showToast({
										title: '图片大小不能超过5MB',
										duration: 2000,
										icon: 'none'
									})
								} else {
									console.log(8888888);
									this.chooseSuccessMethod([item], 0)
								}
							}
						})
					})
					// this.chooseSuccessMethod(res.files, 0)
				}, function(e) {
					//console.log("取消选择图片");
				}, {
					filter: "image",
					multiple: true,
					maximum: maxNum
				});
				this.show = false
				this.isActive = null
			},
			chooseSuccessMethod(filePaths, type, name) {
				if (this.action == '') { //未配置上传路径
					// this.value.push({url:filePaths[0]})
					// this.uploadLists.push({url:filePaths[0]})
					this.$emit("chooseSuccess", filePaths, type, name); //filePaths 路径 type 0 为图片 1为视频
				} else {
					if (type == 1) {
						this.imgUpload(filePaths, name);
					} else {
						if (this.compress) { //设置了需要压缩
							this.imgCompress(filePaths);
						} else {
							this.imgUpload(filePaths, name);
						}
					}

				}
			},
			imgCompress(tempFilePaths) {
				uni.showLoading({
					title: '压缩中...'
				});

				let compressImgs = [];
				let results = [];
				tempFilePaths.forEach((item, index) => {
					compressImgs.push(new Promise((resolve, reject) => {
						// #ifndef H5
						uni.compressImage({
							src: item,
							quality: this.quality,
							success: res => {
								results.push(res.tempFilePath);
								resolve(res.tempFilePath);
							},
							fail: (err) => {
								reject(err);
							},
							complete: () => {
								//uni.hideLoading();
							}
						})
						// #endif
						// #ifdef H5
						this.canvasDataURL(item, {
							quality: this.quality / 100
						}, (base64Codes) => {
							//this.imgUpload(base64Codes);
							results.push(base64Codes);
							resolve(base64Codes);
						})
						// #endif
					}))
				})
				Promise.all(compressImgs) //执行所有需请求的接口
					.then((results) => {
						uni.hideLoading();
						this.imgUpload(results);
					})
					.catch((res, object) => {
						uni.hideLoading();
					});
			},
			imgUpload(tempFilePaths, name) {
				// if (this.action == '') {
				// 	uni.showToast({
				// 		title: '未配置上传地址',
				// 		icon: 'none',
				// 		duration: 2000
				// 	});
				// 	return false;
				// }
				uni.showLoading({
					title: '上传中'
				});
				let uploadImgs = [];
				tempFilePaths.forEach((item, index) => {
					uploadImgs.push(new Promise((resolve, reject) => {
						const uploadTask = uni.uploadFile({
							url: this.action, //仅为示例，非真实的接口地址
							filePath: item,
							name: this.name,
							fileType: 'image',
							formData: this.formData,
							header: this.headers,
							success: (uploadFileRes) => {
								console.log('uploadFileRes', uploadFileRes);
								//uni.hideLoading();
								if (typeof this.uploadSuccess == 'function') {
									if (this.uploadSuccess(uploadFileRes).success) {
										this.value.push(this.uploadSuccess(uploadFileRes)
											.url)
										this.$emit("input", this.uploadLists);
									}
								}
								let videoCover = '';
								//如果上传的是视频的话需要截取到封面图
								if (this.mediaType == 'video') {
									uni.requireNativePlugin('TX-VideoTool')
										.getVideoThumbnailImage({
											"videoPath": plus.io
												.convertLocalFileSystemURL(item),
											"saveImagePath": plus.io
												.convertLocalFileSystemURL(
													"_doc/TXVideoTool/"),
											"saveImageName": "testLocal" + new Date()
												.getTime() + ".png",
											"second": 0
										}, result => {
											this.$emit("uploadSuccess", uploadFileRes,
												result.imagePath);
											resolve(uploadFileRes);
										});
								} else {
									this.$emit("uploadSuccess", uploadFileRes);
									resolve(uploadFileRes);
								}


							},
							fail: (err) => {
								reject(err);
								this.$emit("uploadFail", err);
							},
							complete: () => {
								//uni.hideLoading();
							}
						});
					}))
				})
				Promise.all(uploadImgs) //执行所有需请求的接口
					.then((results) => {
						uni.hideLoading();
					})
					.catch((res, object) => {
						uni.hideLoading();
						this.$emit("uploadFail", res);
					});
				// uploadTask.onProgressUpdate((res) => {
				// 	//console.log('',)
				// 	uni.showLoading({
				// 		title: '上传中' + res.progress + '%'
				// 	});
				// 	if (res.progress == 100) {
				// 		uni.hideLoading();
				// 	}
				// });
			},
			canvasDataURL(path, obj, callback) {
				var img = new Image();
				img.src = path;
				img.onload = function() {
					var that = this;
					// 默认按比例压缩
					var w = that.width,
						h = that.height,
						scale = w / h;
					w = obj.width || w;
					h = obj.height || (w / scale);
					var quality = 0.8; // 默认图片质量为0.8
					//生成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);
					// 图像质量
					if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
						quality = obj.quality;
					}
					// quality值越小，所绘制出的图像越模糊
					var base64 = canvas.toDataURL('image/jpeg', quality);
					// 回调函数返回base64的值
					callback(base64);
				}
			},
		}
	}
</script>

<style>
	/* 自定义弹出框的样式 */
	.activeStyle {
		background: rgba(127, 181, 255, 0.6);
		font-weight: bold !important;
	}

	.mt40 {
		margin-top: 40rpx !important;
	}

	.chooseBtnStyle {
		width: 602rpx;
		height: 86rpx;
		text-align: center;
		line-height: 86rpx;
		border-radius: 28rpx;
		margin: 0 auto;
		font-size: 34rpx;
		color: #333333;
		font-weight: 400;
	}

	.bottomOfupload {
		height: 250rpx;

	}

	.colorOrange {
		color: #FFD233;
	}

	.colorWhite {
		color: #ffffff;
	}

	.fontClass {
		font-size: 30rpx;
		font-weight: bold;
	}

	.ml36 {
		margin-left: 36rpx;
	}

	.mr36 {
		margin-right: 36rpx;
	}

	/deep/.u-popup__content {
		background: rgba(255, 255, 255, 0.7);
		border-radius: 33rpx 33rpx 0 0;
	}

	.time-top {
		height: 80rpx;
		background: #7FB5FF;
		border-radius: 33rpx 33rpx 0px 0px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	/*  */
	.camera-img {
		width: 61rpx !important;
		height: 61rpx !important;
		margin-bottom: 23rpx;
	}

	.imgAdd {
		width: 51rpx;
		height: 51rpx;
		background-image: url(../../static/images/user/add.png);
		background-size: 100% 100%;
	}

	.preview-full {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
		z-index: 1002;
	}

	.preview-full video {
		width: 100%;
		height: 100%;
		z-index: 1002;
	}

	.preview-full-close {
		position: fixed;
		right: 32rpx;
		top: 25rpx;
		width: 80rpx;
		height: 80rpx;
		line-height: 60rpx;
		text-align: center;
		z-index: 1003;
		/* 	background-color: #808080; */
		color: #fff;
		font-size: 65rpx;
		font-weight: bold;
		text-shadow: 1px 2px 5px rgb(0 0 0);
	}



	/* .preview-full-close-before,
	.preview-full-close-after {
		position: absolute;
		top: 50%;
		left: 50%;
		content: '';
		height: 60rpx;
		margin-top: -30rpx;
		width: 6rpx;
		margin-left: -3rpx;
		background-color: #FFFFFF;
		z-index: 20000;
	}

	.preview-full-close-before {
		transform: rotate(45deg);

	}

	.preview-full-close-after {
		transform: rotate(-45deg);

	} */

	.xfx-image-upload-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.xfx-image-upload-Item {
		width: 190rpx;
		height: 190rpx;
		margin-right: 25rpx;
		/* margin: 13rpx; */
		border-radius: 12rpx;
		position: relative;
		margin-bottom: 30rpx;
	}

	.xfx-image-upload-Item:nth-child(3n) {
		margin-right: 0;
	}

	.xfx-image-upload-Item image {
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
	}

	.xfx-image-upload-Item-video {
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
		position: relative;

	}

	.xfx-image-upload-Item-video-fixed {
		position: absolute;
		top: 0;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 50;
	}

	.xfx-image-upload-Item video {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;

	}

	.xfx-image-upload-Item-add {
		/* font-size: 105rpx; */
		/* line-height: 160rpx; */
		padding-top: 56rpx;
		box-sizing: border-box;
		text-align: center;
		background-color: #F6F7F8;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.text-upload {
		font-size: 28rpx;
		line-height: 33rpx;
		font-weight: 400;
		color: #495B93;
		display: block;
		margin-top: 29rpx;
	}

	.xfx-image-upload-Item-del {
		border-radius: 50%;
		/* background-color: #F13629; */
		font-size: 24rpx;
		position: absolute;
		width: 36rpx;
		height: 36rpx;
		line-height: 35rpx;
		text-align: center;
		top: -18rpx;
		right: -18rpx;
		z-index: 51;
		/* 		color: #fff; */
	}

	.xfx-image-upload-Item-del-cover {
		border-radius: 50%;
		/* background-color: #F13629; */
		font-size: 24rpx;
		position: absolute;
		width: 36rpx;
		height: 36rpx;
		text-align: center;
		top: -18rpx;
		right: -18rpx;
		/* color: #fff; */
		/* #ifdef APP-PLUS */
		line-height: 25rpx;
		/* #endif */
		/* #ifndef APP-PLUS */
		line-height: 35rpx;
		/* #endif */
		z-index: 51;

	}
</style>
