<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: {}, //oss上传参数
                expire: 0, //oss上传过期时间

				showS: false,
				contentS: "",
			};
		},
		props: {
            // 最大上传总数量
			maxLength: {
				type: Number,
				default: 9,
			},
            //最多上传视频总数量
            maxVideoLength: {
                type: Number,
				default: 1,
            },
            // 已上传的数组（用来判断最大上传数量限制）
			arr: {
				type: Array,
				default: () => {
					return []
				}
			},
            //已上传数量
            arrLength: {
                type: Number,
				default: 0,
            },
			//是否显示
			show: {
				type: Boolean,
				default: false,
			},
			//是否剪裁（仅支持APP）
			isCrop: {
				type: Boolean,
				default: false,
			},
            // 剪裁尺寸
			cropSize: {
				type: Object,
				default:()=>({width:750,height:550})
			},
			//是否压缩（仅支持APP）
			isZip: {
				type: Boolean,
				default: false,
			},
            // 默认上传类型（图片、视频）
			chooseUploadFileType: {
				type: String,
				default: "",
			},
			//是否只能拍照
			isCamera: {
				type: Boolean,
				default: false,
			},
            //是否限制时长
            isDuration: {
                type: Boolean,
                default: false,
            },
            // 最大视频时长
            maxDuration: {
                type: Number,
				default: 15,
            },
            // 是否限制上传大小
            isMaxSize: {
                type: Boolean,
                default: false,
            },
            // 最大上传视频大小 （单位MB）
            maxVideoSize: {
                type: Number,
				default: 50,
            },
            // 最大上传视频大小 （单位MB）
            maxImageSize: {
                type: Number,
				default: 5,
            },
            // 是否直传oss
            isOss: {
                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: {
            //获取权限，APP嵌入H5时使用，由App返回权限回来
			getHPermissions() {
                this.uploadFileAll();
				// 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();
				// }
			},
            // 判断权限 （仅支持APP）
			async getPermissionsState() {
				// this.uploadFileAll();
                console.log("App");
                // const checkPermission = uni.requireNativePlugin("CL-Permission"); //付费权限判断
                let that = this;
                if (that.sourceType == "camera") {
                    //检测相机权限;
                    // checkPermission.checkCamera((result) => {
                    //     // console.log(result)
                    //     if (result.code == 1) {
                    //         that.cameraState = true;
                    //     } else {
                    //         that.cameraState = false;
                    //     }

                    //     if (that.cameraState) {
                    //         that.uploadFileAll();
                    //     } else {
                    //         that.contentS = "需要访问相机，请到设置里开启";
                    //         that.showS = true;
                    //     }
                    // });

                    if (plus.os.name == "Android") {
                        let cameraGetResult = await permision.requestAndroidPermission("android.permission.CAMERA"); //摄像头权限
                        if (cameraGetResult == 1) {
                            // "已获得授权";
                            that.cameraState = true;
                        } else {
                            // "未获得授权";
                            that.cameraState = false;
                        }
                        if (that.cameraState) {
                            that.uploadFileAll();
                        } else {
                            that.contentS = "需要访问相机，请到设置里开启";
                            that.showS = true;
                        }
                    } else if (plus.os.name == "iOS") {
                        that.cameraState = await permision.judgeIosPermission("camera")
                        if (that.cameraState) {
                            that.uploadFileAll();
                        } else {
                            that.contentS = "需要访问相机，请到设置里开启";
                            that.showS = true;
                        }
                    }
                } else {
                    if (plus.os.name == "Android") {
                        let photoLibraryGetResult = await permision.requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE"); //相册读取权限
                        if (photoLibraryGetResult == 1) {
                            // "已获得授权";
                            that.photoLibraryGetState = true;
                        } else {
                            // "未获得授权";
                            that.photoLibraryGetState = false;
                        }
                        if (that.photoLibraryGetState) {
                            that.uploadFileAll();
                        } else {
                            that.contentS = "需要访问存储权限，请到设置里开启";
                            that.showS = true;
                        }
                    } else if (plus.os.name == "iOS") {
                        that.photoLibraryGetState = await permision.judgeIosPermission("photoLibrary")
                        if (that.photoLibraryGetState) {
                            that.uploadFileAll();
                        } else {
                            that.contentS = "需要访问存储权限，请到设置里开启";
                            that.showS = true;
                        }
                        // checkPermission.checkPhotos((result) => {
                        //     // console.log(result)
                        //     if (result.code == 1) {
                        //         that.photoLibraryGetState = true;
                        //     } else {
                        //         that.photoLibraryGetState = false;
                        //     }
                        //     if (that.photoLibraryGetState) {
                        //         that.uploadFileAll();
                        //     } else {
                        //         that.contentS = "需要访问存储权限，请到设置里开启";
                        //         that.showS = true;
                        //     }
                        // });
                    }
                }


			},
            // 去设置页面设置权限
			seting() {
				// #ifdef H5
                // APP嵌入H5时使用，通知app跳转设置页面
				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") {
                    // 选择视频时，图片和视频存在同一个数组Arr里，判断是否已经上传过视频，是否最多只能上传一个视频
                    if(this.arr.length>0) {
                        let num = 0
                        this.arr.forEach(item => {
                            if (item.type == '002') {
                                num+=1
                            }
                        });
                        
                        if(this.maxVideoLength>1) {
                            if(num>=this.maxVideoLength) {
                                this.$refs.uToast.show({
                                    title: `最多只能上传${this.maxVideoLength}个视频`,
                                    duration: 1500,
                                })
                            } else {
                                this.chooseVideo();
                            }
                        } else {
                            if(num!=0) {
                                this.$refs.uToast.show({
                                    title: "最多只能上传1个视频",
                                    duration: 1500,
                                })
                            } else {
                                this.chooseVideo();
                            }
                        }
                    } else {
                        this.chooseVideo();
                    }
				}
			},
			//上传图片
			chooseImages() {
				let that = this;
				if (that.sourceType == "camera" &&that.isCrop) {
					that.crop =that.cropSize;
				} else {
					that.crop = {};
				}

                let count = that.maxLength - that.arrLength
				uni.chooseImage({
					count: count, //默认9
					sourceType: [that.sourceType], //从相册选择/拍摄
					crop: that.crop,
					success: (res) => {
						// console.log(this.Arr, res)
						if (this.arrLength + res.tempFiles.length > this.maxLength) {
							that.$refs.uToast.show({
								title: `最多上传${this.maxLength}张图片`,
								duration: 1500,
							})
							return
						} else if(res.size <= (that.maxImageSize* 1048576)) {
                            that.$refs.uToast.show({
								title: `图片最大${this.maxImageSize}MB`,
								duration: 1500,
							})
							return
                        } else {
							let igmFile = res.tempFiles;
                            if(that.isOss) {
                                igmFile.map((item) => {
                                    // that.uploadFile(item);
                                    let fileName = ""
                                    let date = new Date()
                                    let time = date.getTime()
                                    
                                    // 获取图片类型，拼接时间戳作为文件名称（H5直接获取，app另外获取）
                                    // #ifdef H5
                                    // console.log("h5");
                                    fileName = that.$timefilter(date,'YY/MM/DD') +'/'+ 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 = that.$timefilter(date,'YY/MM/DD') +'/'+ time+'.'+image.type
                                        }
                                    });
                                    // #endif

                                    // console.log(fileName)
                                    that.getAliOssInfo(item.path,fileName)

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

			//上传视频
			async chooseVideo() {
				let that = this;
				uni.chooseVideo({
					maxDuration: that.maxDuration,
					count: 1,
					sourceType: [that.sourceType],
					duration: that.maxDuration,
					compressed: true,
					success: (res) => {
						// uni.showModal({
						// 	content: res.duration,
						// 	showCancel: false
						// });
                        console.log(res)
                        if(that.isDuration&&(res.duration >= (that.maxDuration+1))) {
                           that.$refs.uToast.show({
                                title: `视频最多时长${that.maxDuration}s`,
                                duration: 1500,
                            })
                            return
                        } else if(res.size > (that.maxVideoSize* 1048576)) {
                            that.$refs.uToast.show({
                                title: `视频最大${maxVideoSize}MB`,
                                duration: 1500,
                            })
                        } else {
                            if(that.isOss) {
                                // 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 = that.$timefilter(date,'YY/MM/DD') +'/'+ 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 = that.$timefilter(date,'YY/MM/DD') +'/'+ time+'.'+video.type
                                    }
                                });
                                // #endif
                                // console.log(fileName)
                                that.cancel();
                                that.getAliOssInfo(res.tempFilePath,fileName)
                            } else {
                                // console.log(res)
                                // console.log(res.tempFile.type)
                                that.cancel();
                                that.uploadFile(res.tempFilePath);
                            }
                        }
					},
					fail(err) {
						// that.$refs.uToast.show({
						// 	title: err,
						// 	duration: 1500,
						// })

					},
				});
			},

            //获取oss信息
            async getAliOssInfo(upfile,fileName) {
                // 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.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('获取上传信息失败')
                        }
                    }

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

                    // #ifdef APP-PLUS
                    // console.log("App压缩");
                    if(that.isZip) {
                        if (that.uploadFileType == "image") {
                            zip = await that.compress(upfile);
                        } else if (that.uploadFileType == "video") {
                            zip = await that.videoCompress(upfile); // await--上传图片之前先压缩，否则上传会比压缩先执行
                        }
                        filePath = zip;
                    } else {
                        filePath = upfile;
                    }
                    // #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 that = 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 = "";
                // #ifdef H5
                // console.log("h5");
                filePath = upfile;
                // #endif

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

                if (that.uploadFileType == "image") {
                    const obj = {
                        kind: "image",
                        url: filePath,
                        type: '001'
                    }
                    that.$emit("addProperties", obj);
                } else if (that.uploadFileType == "video") {
                    const obj = {
                        kind: "video",
                        url: filePath,
                        faceImg: filePath+'?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();

                

				// console.log(filePath)
				// 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) {
				// 			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: resultUrl,
                //                     faceImg: resultUrl+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto',
                //                     type: '002'
                //                 }
				// 				this.$emit("addProperties", obj);
				// 			}
				// 			uni.hideLoading();
				// 		} else {
				// 			uni.hideLoading();
				// 			that.$refs.uToast.show({
				// 				title: Urls.msg,
				// 				duration: 1000,
				// 			})
				// 		}
				// 	},
				// 	fail: (err) => {
				// 		uni.hideLoading();
				// 		that.$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>