<template>
	<view>
		<u-popup v-model="allShow" mode="bottom" border-radius="20" @close="cancel">
			<view class="main text-center font-30 color-11 text-bold">
				<view v-for="(item,index) in list" :key="index" class="select-item"
					:class="[index+1!=list.length?'border':'']" @tap="sheetClick(item.type)">
					{{item.text}}
				</view>
				<view class="cancel-item" @tap="cancel">取 消</view>
			</view>
		</u-popup>

		<u-modal v-model="showS" :show-title="false" :show-cancel-button="true" confirm-color='#fc6035'
			confirm-text="设置" cancel-text="取消" :content="contentS" @confirm="seting"></u-modal>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import permision from "@/js_sdk/wa-permission/permission.js"; //app设置权限
	export default {
		data() {
			return {
				list: [
					//选项数组
					{
						text: "图片",
						type: "image"
					},
					{
						text: "视频",
						type: "video"
					},
				],
				last: false, //是否是最后一次选择
				crop: {}, //剪裁
				uploadFileType: "", //上传类型
				sourceType: "", //拍摄/相册
				popupShow: true,
				allShow: false,
                fileObj: {},
                expire: 0,

				showS: false,
				contentS: "",
			};
		},
		props: {
			maxLength: {
				type: Number,
				default: 9,
			},
			Arr: {
				type: Array,
				default: () => {
					return []
				}
			},
			//是否显示
			show: {
				type: Boolean,
				default: false,
			},
			//是否剪裁
			isCrop: {
				type: Boolean,
				default: false,
			},
			//是否头像
			isHeader: {
				type: Boolean,
				default: false,
			},
			//上传数量
			length: {
				type: Number,
				default: 9,
			},
			chooseUploadFileType: {
				type: String,
				default: "",
			},
			//是否只能拍照
			isCamera: {
				type: Boolean,
				default: false,
			},
            //是否限制时长
            isDuration: {
                type: Boolean,
                default: false,
            },
		
		
			PermissionsTime: ''
		},
		watch: {
			popupShow() {
				this.allShow = this.popupShow && this.show && !this.isCamera;
			},
			show() {
				this.allShow = this.popupShow && this.show && !this.isCamera;
			},
			isCamera() {
				this.allShow = this.popupShow && this.show && !this.isCamera;
				if (this.isCamera) {
					this.sourceType = "camera";
					this.uploadFileAll();
				}
			},
		},
		created() {
			
			if (this.chooseUploadFileType != "") {
				this.uploadFileType = this.chooseUploadFileType;
				this.last = true;
				this.list = [{
						text: "从手机相册选择",
						type: "album"
					},
					{
						text: "拍摄",
						type: "camera"
					},
				];
			}
				
		},
		mounted() {
		
		},
		methods: {
			getHPermissions() {
				// uni.showToast({
				// 	title:uni.getStorageSync('cameraPermissionsTime'),
				// 	icon:'none',
				// 	duration:3000
				// })
				let that = this
				if (that.sourceType == "camera") {
					OpenCamera.postMessage('123');
					if (uni.getStorageSync('cameraPermissionsTime') === 0) {
						// this.PermissionsTime = 1
						uni.setStorageSync('cameraPermissionsTime', 1)
					} else {
						window.cameraResult = function(res) { //res 原生APP给的数据
							// this.$api.msg(res)
							if (res != 4) {
								that.contentS = "需要访问相机，请到设置里开启。";
								that.showS = true;
							} else {
								that.uploadFileAll();
							}
						}
					}


				} else {
					that.uploadFileAll();
				}

			},
			getPermissionsState() {
				this.uploadFileAll();
			},
			seting() {

				// #ifdef H5
				OpenCamera.postMessage('setting');
				window.cameraPermission = function(res) { //res 原生APP给的数据
				}
				// #endif

				// #ifdef APP-PLUS
				permision.gotoAppPermissionSetting();
				// #endif

			},
			cancel() {
				if (this.chooseUploadFileType == "") {
					this.last = false;
					this.list = [{
							text: "图片",
							type: "image"
						},
						{
							text: "视频",
							type: "video"
						},
					];
				}
				this.$emit("cancelSheet");
			},
			sheetClick(type) {
				if (this.last) {
					this.sourceType = type;
					// #ifdef H5
					this.getHPermissions()
					// #endif

					// #ifdef APP-PLUS
					this.getPermissionsState(); //判断权限
					// #endif
				} else if (!this.last) {
					this.uploadFileType = type;
				}
				this.last = true;
				this.list = [{
						text: "从手机相册选择",
						type: "album"
					},
					{
						text: "拍摄",
						type: "camera"
					},
				];
			},
			//上传文件
			uploadFileAll() {
				if (this.uploadFileType == "image") {
					this.chooseImages();
				} else if (this.uploadFileType == "video") {
					if (this.Arr.length > 0) {
						this.Arr.forEach(item => {
							if (item.type == '002') {
								this.$api.msg('最多只能上传一个视频')
							} else {
								this.chooseVideo();
							}
						});
					} else {
						this.chooseVideo();
					}
				}
			},
			//上传图片
			chooseImages() {
				let _this = this;
				if (
					_this.sourceType == "camera" &&
					_this.isCrop &&
					!_this.isHeader
				) {
					_this.crop = {
						width: 750,
						height: 550
					};
				} else if (_this.isCrop && _this.length == 1) {
					if (_this.isHeader) {
						_this.crop = {
							width: 140,
							height: 140
						};
					}
				} else {
					_this.crop = {};
				}

				uni.chooseImage({
					count: _this.length, //默认9
					sourceType: [_this.sourceType], //从相册选择/拍摄
					crop: _this.crop,
					success: (res) => {
						// console.log(this.Arr, res)
						if (this.Arr.length + res.tempFiles.length > this.maxLength) {
							_this.$refs.uToast.show({
								title: `最多上传${this.maxLength}张`,
								duration: 1500,
							})

							return
						} else {
							let igmFile = res.tempFiles;
							igmFile.map((item) => {
								// _this.uploadFile(item);
                        
                                let fileName = ""
                                let date = new Date()
                                let time = date.getTime()
                                
                                // 获取图片类型，拼接时间戳作为文件名称（H5直接获取，app另外获取）
                                // #ifdef H5
                                // console.log("h5");
                                fileName = _this.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+item.type.substring(item.type.lastIndexOf('/')+1) || 'jpg'
                                // #endif

                                // #ifdef APP-PLUS
                                // console.log("App");
                                uni.getImageInfo({
                                    src: item.path,
                                    success: function (image) {
                                        //    console.log( image.type,'image.typeimage.type')
                                        fileName = _this.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+image.type
                                    }
                                });
                                // #endif

                                // console.log(fileName)

                                _this.getAliOssInfo(item.path,fileName)
							});
							_this.cancel();
						}

					},
					fail(err) {
						if (_this.isCamera) {
							_this.$emit("cancelSheet");
						}
						// console.log('选择图片文件失败或取消')
						// _this.cancel();
						// console.log(JSON.stringify(err))
						// _this.$refs.uToast.show({
						// 	title: err,
						// 	duration: 1500,
						// })
					},
				});
			},

			//上传视频
			async chooseVideo() {
				let _this = this;
				uni.chooseVideo({
					maxDuration: 15,
					count: 1,
					sourceType: [_this.sourceType],
					duration: 15,
					compressed: true,
					success: (res) => {
						console.log(res, 'responentresponentresponent')
						// uni.showModal({
						// 	content: res.duration,
						// 	showCancel: false
						// });
					
                        let flag = true
                        if(!_this.isDuration||(_this.isDuration&&res.duration <= 16)) {
                            flag = true
                        } else {
                            flag = false
                            _this.$refs.uToast.show({
                                title: "视频最多时长15s",
                                duration: 1500,
                            })
                            return
                        }
                        if (res.size <= 52428800) {
                            flag = true
                        } else {
                            flag = false
                            _this.$refs.uToast.show({
                                title: "视频最多50MB",
                                duration: 1500,
                            })
                            return
                        }
                        if(flag) {
                            // console.log(res)
                            // console.log(res.tempFile.type)
                            let fileName = ""
                            let date = new Date()
                            let time = date.getTime()
                            
                            // 获取视频类型，拼接时间戳作为文件名称（H5直接获取，app另外获取）
                            // #ifdef H5
                            // console.log("h5");
                            fileName = _this.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+res.tempFile.type.substring(res.tempFile.type.lastIndexOf('/')+1) || 'mp4'
                            // #endif

                            // #ifdef APP-PLUS
                            // console.log("App");
                            uni.getVideoInfo({
                                src: res.tempFile,
                                success: function (video) {
                                    //    console.log( image.type,'image.typeimage.type')
                                    fileName = _this.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+video.type
                                }
                            });
                            // #endif
                            // console.log(fileName)
                            _this.cancel();
                            _this.getAliOssInfo(res.tempFilePath,fileName)
                        }
					},
					fail(err) {
						// _this.$refs.uToast.show({
						// 	title: err,
						// 	duration: 1500,
						// })

					},
				});
			},

            //获取oss信息
            async getAliOssInfo(path,fileName,type) {
            // console.log(fileName,'fileName')
            let that = this
            let time = new Date().getTime()
            let resultUrl = ""
            let zip = "";
            try {
                if(time > Number(that.expire)) {
                    const res = await that.$u.api.ossInfo()
                    // console.log(res)
                    if(res.code==200) {
                        that.fileObj.dir = res.data.dir
                        that.fileObj.host = res.data.host
                        // that.fileObj.host = 'https://fresh-life.oss-cn-shanghai.aliyuncs.com'
                        that.fileObj.policy = res.data.policy
                        that.fileObj.signature = res.data.signature
                        that.fileObj.accessid = res.data.accessid
                        that.expire = res.data.expire * 1000
                        // console.log(that.$timefilter('YY-MM-DD HH:MM:SS',that.expire))
                        // console.log(that.fileObj,'pppoooo')
                    } else {
                        that.$api.msg('获取上传信息失败')
                    }
                }

                if (that.uploadFileType == "image") {
                    // #ifdef APP-PLUS
                    // console.log("App压缩");
                    zip = await that.compress(path);
                    // #endif
                } else if (that.uploadFileType == "video") {
                    // #ifdef APP-PLUS
                    // console.log("App压缩");
                    zip = await that.videoCompress(path); // await--上传图片之前先压缩，否则上传会比压缩先执行
                    // #endif
                }

                let filePath = "";
                // #ifdef H5
                // console.log("h5");
                filePath = path;
                // #endif

                // #ifdef APP-PLUS
                // console.log("App");
                filePath = zip;

                // #endif

                uni.showLoading({
                    mask: true,
                    title: "上传中...",
                });
                resultUrl = await that.uploadOss(filePath,fileName);
                // console.log(resultUrl,'resultUrl=resultUrl=resultUrl')
                if(that.uploadFileType=='image') {
                    const obj = {
                        kind: "image",
                        url: resultUrl,
                        type: '001'
                    }
                    that.$emit("addProperties", obj);
                } else if(that.uploadFileType=='video') {
                    const obj = {
                        kind: "video",
                        url: resultUrl,
                        faceImg: resultUrl+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto',
                        type: '002'
                    }
                    that.$emit("addProperties", obj);
                }
                uni.hideLoading();
            } catch (error) {
                uni.hideLoading();
                that.$refs.uToast.show({
                    title: "上传失败",
                    duration: 1000,
                })
            }
            
        },

        //直接上传oss
        async uploadOss(filePath,fileName) {
            let that = this
            let claims = uni.getStorageSync("claims");
            // console.log(that.fileObj,'mmmmmmm')
            // console.log(fileName,'+fileName')
            let [err, result] = await uni.uploadFile({
                url: that.fileObj.host, //阿里云的存储地址，可以后端返回给你，也可以前端自己写上
                filePath:filePath, //要上传的临时文件路径
                name: 'file',
                header:{
                    Authorization: claims
                },
                formData: {
                    key: that.fileObj.dir+'/'+fileName, //文件名
                    policy: that.fileObj.policy, //后台获取超时时间
                    OSSAccessKeyId: that.fileObj.accessid, //后台获取临时ID
                    success_action_status: '200', //让服务端返回200,不然，默认会返回204
                    signature: that.fileObj.signature //后台获取签名
                },
            })
            if (err) {
                //  上传错误了。。。可以做点什么
            } else {
                let url = that.fileObj.host+'/'+that.fileObj.dir+'/'+fileName
                // console.log(url)
                return url //上传成功后，将我们所自定义的key（文件路径名）返回出去
            }
        },


			//压缩后上传
			// async uploadFile(upfile) {
			// 	let _this = this;
			// 	let zip = "";
			// 	let uploadUrl = "";
			// 	uni.showLoading({
			// 		mask: true,
			// 		title: "上传中...",
			// 	});

			// 	if (this.uploadFileType == "image") {
			// 		uploadUrl = `${this.$u.http.config.ossUrl}/common/uploadImage`;

			// 	} else if (this.uploadFileType == "video") {
			// 		uploadUrl = `${this.$u.http.config.ossUrl}/common/uploadVideo`;

			// 	}

			// 	let filePath = "";

			// 	filePath = upfile

			// 	// let 
			// 	// console.log(zip)
			// 	// console.log(upfile)
			// 	//开始上传，此处可先注释看压缩效果
			// 	uni.uploadFile({
			// 		// 需要上传的地址
			// 		url: uploadUrl,
			// 		filePath: filePath,
			// 		name: "file",
			// 		onUploadProgress: (res) => {

			// 		},
			// 		success: (res) => {
			// 			// console.log(res)
			// 			let Urls = JSON.parse(res.data);
			// 			// console.log(Urls);
			// 			if (Urls.code == 200) {
			// 				console.log(Urls, '子组件的东西');
			// 				if (this.uploadFileType == "image") {
			// 					const obj = {
			// 						kind: "image",
			// 						url: Urls.url,
			// 						type: '001'
			// 					}
			// 					this.$emit("addProperties", obj);
			// 				} else if (this.uploadFileType == "video") {
			// 					const obj = {
			// 						kind: "video",
			// 						url: Urls.data.videoUrl,
			// 						faceImg: Urls.data.signedUrl,
			// 						type: '002'
			// 					}
			// 					this.$emit("addProperties", obj);
			// 				}
			// 				uni.hideLoading();
			// 			} else {
			// 				uni.hideLoading();
			// 				_this.$refs.uToast.show({
			// 					title: Urls.msg,
			// 					duration: 1000,
			// 				})
			// 			}
			// 		},
			// 		fail: (err) => {
			// 			uni.hideLoading();
			// 			_this.$refs.uToast.show({
			// 				title: "上传失败",
			// 				duration: 1000,
			// 			})
			// 		},
			// 	});
			// },

			//压缩图片
			compress(img) {
				// console.log('开始压缩图片');
				let that = this;
				return new Promise((res) => {
					plus.io.resolveLocalFileSystemURL(
						img,
						(entry) => {
							//通过URL参数获取目录对象或文件对象
							entry.file((file) => {
								// 可通过entry对象操作图片
								// console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
								if (file.size > 521000) {
									plus.zip.compressImage({
											src: img, //src: 压缩原始图片的路径
											dst: img
												.replace(".png", "fl.png")
												.replace(".PNG", "fl.PNG")
												.replace(".jpg", "fl.jpg")
												.replace(".JPG", "fl.JPG"),
											// width: '50%',      //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个区分一下
											// height: '50%',     //width,height: (String 类型 )缩放图片的宽度,高度
											quality: 30, //quality: (Number 类型 )压缩图片的质量
											overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
											format: "jpg", //format: (String 类型 )压缩转换后的图片格式
										},
										(event) => {
											// console.log('压缩后图片信息:' + JSON.stringify(event));// 压缩后图片信息
											this.imageInfo = event;
											let newImg = event.target;
											if (event.size < 1048576) {
												res(newImg);
											} else {
												//如果大于1mb
												uni.hideLoading();
												that.$refs.uToast.show({
													title: "图片过大",
													duration: 1000,
												})
											}
											//返回新的图片地址，在uploadFile之前接收
										},
										function(err) {
											// console.log('Resolve file URL failed: ' + err.message);
											uni.hideLoading();
											that.$refs.uToast.show({
												title: err.message,
												duration: 1000,
											})
											// that.cancel();
										}
									);
								} else {
									res(img);
									uni.hideLoading();
								}
							});
						},
						(e) => {
							// 返回错误信息
							// console.log('Resolve file URL failed: ' + e.message);
							that.$refs.uToast.show({
								title: e.message,
								duration: 1000,
							})
							uni.hideLoading();
							// that.cancel();
						}
					);
				});
			},

			//压缩视频
			videoCompress(video) {
				// console.log('开始压缩视频');
				let that = this;
				return new Promise((res) => {
					plus.io.resolveLocalFileSystemURL(
						video,
						(entry) => {
							entry.file((file) => {
								// console.log('压缩前视频信息:' + JSON.stringify(file));
								if (file.size > 1048576) { //h5+ (app)压缩
									plus.zip.compressVideo({
										src: video,
										overwrite: true,
										filename: '_doc/'
									}, (event) => {
										// console.log('压缩后视频信息:' + JSON.stringify(event));
										let newVideo = event.tempFilePath;
										res(newVideo);
										uni.hideLoading();

									}, function(err) {
										uni.hideLoading();
										that.$refs.uToast.show({
											title: "压缩视频失败",
											duration: 1000,
										})
										// console.log('压缩视频失败',err)
										that.cancel();
									});
								} else {
									// console.log('不用压缩')
									res(video);
									uni.hideLoading();
								}
							});
						},
						(e) => {
							// 返回错误信息
							// console.log("Resolve file URL failed: " + e.message);
							uni.hideLoading();
							that.$refs.uToast.show({
								title: e.message,
								duration: 1000,
							})
						}
					);
				});
			},
		},
	};
</script>

<style lang="less" scoped>
	/deep/ .u-drawer__scroll-view {
		padding-bottom: 28rpx;
	}

	.select-item {
		height: 120rpx;
		line-height: 120rpx;
	}

	.cancel-item {
		height: 98rpx;
		line-height: 98rpx;
		width: 640rpx;
		margin-left: 55rpx;
		background: #f4f4f4;
		border-radius: 50rpx;
	}

	.border {
		border-bottom: 2rpx solid #f4f4f4;
	}
</style>