<template>
	<div class="custom-upload" :class="clz">
		<!-- <div @click="checkUploadType" class="" v-if="!isWeb">
			<slot></slot>
		</div> -->
		<van-uploader 
			:multiple="multiple" 
			:capture="capture" 
			@delete="onDelete"
			:after-read="onRead"
			:before-read="beforeRead"
			v-model="fileList"
			v-bind="$attrs" 
			v-on="$listeners"
			:max-count="limit">
			<div @click="checkUploadType">
				<img src="@/assets/images/tianjiazhaopian_icon.png" alt="" >
			</div>
		</van-uploader>

		<van-action-sheet v-model="showActions" >
			<div class="action-list" @click="showActions=false">
				<div class="item tc" @click="chooseImg">图片</div>
				<div class="item" @click="onCapture">拍照</div>
				<div class="item cancel">取消</div>
			</div>
        </van-action-sheet>
	</div>

  	<!-- <div class="custom-upload" :class="clz">
		<van-uploader @delete="onDelete" :after-read="onRead" v-model="fileList" v-on="$listeners" v-bind="$attrs" />
	</div> -->
</template>

<script>
import { isIOS } from '@/utils/platform';
import fileApi from '@/api/fileApi';
import {imgPreview} from '@/utils/imgCompress';
import cryptoUtils from "@/utils/cryptoUtils";
export default {
	name: "CustomUpload",
	props: {
		data: {},
		mode: {
			default: 'widthPercent'
		},
		percent: {
			default: 3
		},
		align: {
			default: 'right'
		},
		disabled: {
			default: false
		},

		limit: Number,
		photograph: Number,//1相机  2相册 
		compress: {
			type: Boolean,
			default: false
		},
		multiple: {
			type: Boolean,
			default: false
		},
		readAsBase64: Function,
		noTips: {
			type: Boolean,
			default: true
		}
	}, 
	computed:{
		capture(){
			// 安卓
			// 微信公众号  无capture  图册跟相机一起调用   有capture 调用相机
			// 微信小程序  无capture 调用图册             有capture 图册跟相机一起调用

			// ios
			// 无capture  手机 相册一起调用
			// 有capture  调用相机
			if(this.photograph==1){
				//相机
				if(isIOS){
					return 'camera'
				} else {
					if(this.$root.miniprogram){
						//小程序
						return 'camera'
					} else {
						return false
					}
				}
			} else if(this.photograph==2){
				//相册
				if(isIOS){
					return false
				} else {
					if(this.$root.miniprogram){
						//小程序
						return false
					} else {
						return false
					}
				}
			} else {
				if(isIOS){
					return false
				} else {
					if(this.$root.miniprogram){
						//小程序
						return true
					} else {
						return false
					}
				}
			}
		},
		isWeb(){
			return !window.plus && !this.$root.miniprogram && !this.isWeiXin()
		},
		clz(){
			var list = []
			if(this.mode=='widthPercent'){
				list.push('mode-percent')
				list.push('mode-percent-'+ this.percent)
			}
			if(this.align=='left'){
				list.push('custom-upload-align-left')
			}
			if(this.disabled){
				list.push('custom-upload-disabled')
			}
			if(!this.isWeb){
				list.push('custom-upload-not-web')
			}
			if(this.fileList.length >= this.limit){
				list.push('custom-upload-over')
			}
			return list.join(' ')
		},
		remainders(){
			return this.fileList.length - this.limit
		}
	},
  	data() {
		return {
			fileList: [],
			stop: false,
			showActions: false,
			typeList: [
				{name: "图片"},
				{name: "拍照"},
			],
		}
	},
	watch:{
		data: {
			handler(){
				if(this.stop){
					this.stop = false
					return
				}
				if(this.data){
					this.fileList = _.map(this.data, v=>{
						return {
							url: this.$root.setImgUrl(v),
							serverPath: v
						}
					})
				}
			},
			deep: true,
			immediate: true
		},
	},
  	methods: {
		onDelete(file, index){
			this.fileList.splice(index.index, 1)
			this.$emit('update:data', _.map(this.fileList, (v)=>{
				return v.serverPath
			}))
		},
		checkLimit(file){
			var length = file instanceof Array? file.length : 1
			if(this.limit && this.fileList.length + length > this.limit){
                this.$toast(`上传的图片最多只能${this.limit}张`);
                return false;
			}
			return true
		},
		beforeRead(file) {
			return this.checkLimit(file)
		},
		checkUploadType(){
			if(this.isWeb){
				return
			}
			if(this.photograph === 2){
				this.chooseImg()
			} else if(this.photograph === 1){
				this.onCapture()
			} else {
				if(this.$root.miniprogram || this.isWeiXin()){
					this.wxChooseImg(['album', 'camera'])
				} else{
					this.showActions = true
				}
			}
		},
		showLoading(){
			if(!this.noTips){
				this.$toast.loading({
					duration: 0, 
					forbidClick: true,
					loadingType: 'loading',
					message: "上传中..."
				})
			}
		},
		showSuccessTips(){
			if(!this.noTips){
				this.$toast("上传成功");
			}
		},
		async onRead(result) {
            var list = [];
            if (result instanceof Array) {
                list = result;
            } else {
                list.push(result);
			}
			
            list.map((item, index) => {
				item.status = 'uploading';
				item.message = '上传中...';
				setTimeout(()=>{
					this.postImg(item);
				}, 200*index)
            });
		},
		async postImg(item) {
			var uid = new Date().getTime()
            this.showLoading()
			if(this.readAsBase64){
				this.readAsBase64(uid, item.content)
			}
            try{
				this.compressImage2(item).then(async (file)=>{
					var formdata = new FormData();
					formdata.append("file", file);
                    var res = await fileApi.upload_stream(formdata);
                    if (res.status == 200) {
						this.uploadSuccess(uid, res.obj.fullUri, item)
                    } else {
						this.uploadError(uid, item)
                    }
				})
            }catch(e){
                console.error(e)
				this.$toast.clear()
				this.uploadError(uid)
            }
		},
		compressImage2(item) {
            return new Promise((resolve, reject) =>{
				if(!this.compress){
					resolve(item.file)
					return
				}
				imgPreview(item, async (rs, v) => {
                    if(rs!=1){
						resolve(item.file)
                    } else {
						resolve(v)
                    }
				})
            })
		},
		//app内相关操作 开始
		compressImage(srcUrl) {
			return new Promise( (resolve, reject)=> {
				var lastIdx = srcUrl.lastIndexOf("/"),
					imgName = srcUrl;
				if(lastIdx>-1) {
					imgName = srcUrl.slice(lastIdx+1);
				}
				plus.zip.compressImage({
					src: srcUrl,
					dst: "_pati/compressImg/"+imgName,
					quality: 20,
					overwrite: true
				}, (succ)=>{
					resolve(succ.target);
				}, (err)=>{
					reject({
						status: -1,
						msg: "压缩失败:  " + err.message
					});
				});
			});
        },
		plusCapture() {
            var vm = this
            var cmr = window.plus.camera.getCamera();
            var res = cmr.supportedImageResolutions[0];
			var fmt = cmr.supportedImageFormats[0];
			try {
				cmr.captureImage( ( path )=>{
						this.emitMoveBack()
						this.showLoading()
						vm.loadCameraPic(path);
					},
					function( error ) {
						vm.$toast.clear()
						console.error(error)
					},
					{resolution:res,format:fmt}
				);
			} catch (error) {
				console.error(error)
				vm.$toast.clear()
			}
		},
        plusUpload(path, uid, file) {
            var vm = this 
            var task = window.plus.uploader.createUpload(fileApi.upload_stream_path, {
					method: "POST"
				},
				(t, status)=> {
					this.$toast.clear()
					if (status == 200) {
						var res = JSON.parse(t.responseText)
						res = JSON.parse(cryptoUtils.Decrypt(res.data))
						this.uploadSuccess(uid, res.obj.fullUri, file)
					} else {
						this.uploadError(uid, file)
					}
				}
			);
			task.addFile(path, { key: "file" })
			task.start();
		},
		plusChooseImg(){
			var vm = this
			this.emitMoveBack()
			plus.gallery.pick((e)=> {
				if(this.checkLimit(e.files)){
					this.showLoading()
					e.files.forEach((v, i) => {
						setTimeout(()=>{
							vm.loadCameraPic(v);
						}, 200*i)
					})
				}
			}, function(ecb) {

			}, {
				filename: "_pati/gallery/",
				filter: "image",
				multiple: this.multiple,
				maximum: this.remainders,
				system: false,
				onmaxed:()=>{
					// this.$toast.clear()
					// this.$toast('最多只能选择'+ this.limit +'张图片');
				}
			});
		},
		checkReadAsBase64(uid, fileUrl){
			return new Promise( (resolve, reject)=> {
				// if(this.readAsBase64){
					window.plus.io.resolveLocalFileSystemURL(fileUrl, entry => {
						entry.file(file => {
							const reader = new window.plus.io.FileReader()
							reader.readAsDataURL(file)
							reader.onloadend = (e)=> {
								file.close()
								// entry.remove()
								var file = this.addImg(e.target.result)
								this.readAsBase64&&this.readAsBase64(uid, e.target.result)
								resolve(file);
							}
						})
					})
				// } else {
				// 	resolve();
				// }
			});
		},
		//加载拍照图片
		loadCameraPic(fileUrl) {
			var uid = new Date().getTime()
			this.checkReadAsBase64(uid, fileUrl)
				.then((file)=>{
					if(!this.compress){
						this.plusUpload(fileUrl, uid, file);
						return
					}
					this.compressImage(fileUrl)
						.then((res)=>{
							this.plusUpload(res, uid, file);
						})
						.catch(err=>{
							console.error(err)
							this.$toast.clear()
							this.uploadError(uid, file)
							// if(err&&err.status==-1){
							// 	this.$toast(err.msg)
							// } else {
							// 	this.$toast("压缩失败")
							// }
						})
				})
		},
		//app内相关操作 结束

		//微信相关操作 开始
		wxChooseImg(sourceType) {
			console.log("wxChooseImg")
			wx.chooseImage({
				count: this.remainders, //
				sizeType: ['original', 'compressed'], // 'original', 'compressed'可以指定是原图还是压缩图，默认二者都有
				sourceType: sourceType , // ['album', 'camera']  'album', 'camera'可以指定来源是相册还是相机，默认二者都有
				success: (res) => {
					var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
					if(this.checkLimit(localIds)){
						this.showLoading()
						this.uploadFileToWx(res.localIds)
					}
				}
			});
		},
		urlTobase64(mediaId){
			return new Promise((resolve, reject)=>{
				wx.getLocalImgData({
					localId: mediaId,//图片的本地ID
					success: (res)=> {
						var localData = res.localData;
						if (localData.indexOf('data:image') != 0) {                       
							//判断是否有这样的头部
							localData = 'data:image/jpeg;base64,' +  localData
						}                    
						localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg'); // 此处的localData 就是你所需要的base64位
						var file = this.addImg(localData)
						this.readAsBase64&&this.readAsBase64(mediaId, localData)
						resolve(file)
					},
					fail: (res)=>{
						console.log(res)
						resolve()
					}
				})
			})
		},
		async uploadBase64(path) {
            try{
				this.urlTobase64(path)
					.then(res=>{
						
					}).catch(err=>{
						console.error(err)
						this.$toast('获取图片数据失败')
					})
            }catch(e){
                console.error(e)
                this.$toast.clear()
            }
		},
		uploadFileToWx(localIds){
			if(!localIds.length){
				this.showSuccessTips()
				return
			}
			var localId = localIds.pop()
			this.urlTobase64(localId)
				.then(file=>{
					wx.uploadImage({
						localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
						isShowProgressTips: 1, // 默认为1，显示进度提示
						success: (res3)=> {
							console.log('uploadFileToWx', {
								mediaIds: res3.serverId,
								type: 2
							})
							fileApi.uploadFileToWx({
								mediaIds: res3.serverId,
								type: 2
							}).then(res=>{
								if (res.status == 200) {
									this.uploadSuccess(localId, res.obj.path, file)
									//多图片循环上传
									this.uploadFileToWx(localIds)
								} else {
									this.uploadError(localId, file)
								}
							}).catch(err=>{
								console.error(err)
								this.uploadError(localId, file)
							})
						},
						fail: (res)=>{
							this.uploadError(localId, file)
						}
					})
				})
		},
		//微信相关操作 结束

		uploadError(localId, file){
			file.status = 'failed'
			file.message = '上传失败'
			this.$emit('uploadError', localId)
			this.$toast('上传失败')
		},
		uploadSuccess(localId, path, file){
			file.status = ''
			file.message = ''
			file.serverPath = path
			if(!this.$root.miniprogram && !this.isWeiXin()){
				this.showSuccessTips()
			}
			
			this.$emit('update:data', _.map(this.fileList, (v)=>{
				return v.serverPath
			}))
			this.$emit('uploadSuccess', localId, path)
			return
			

			
			if(this.limit == 1){
				this.imgList = [path]
			} else {
				this.imgList.push(path);
			}
			this.$emit('update:data', this.imgList)
			console.log('path', path)
		},
		onCapture(){
			if(window.plus){
				this.plusCapture()
			} else if(this.isWeiXin() || this.$root.miniprogram){
				this.wxChooseImg(['camera'])
			} 
		},
		chooseImg(){
			if(window.plus){
				this.plusChooseImg()
			} else if(this.isWeiXin() || this.$root.miniprogram){
				this.wxChooseImg(['album'])
			} 
		},
		emitMoveBack(){
			//回到后台
			this.$emit("moveBack")
		},
		addImg(base64str){
			var file = {
				status: 'uploading',
				message: '上传中...',
				url: base64str,
				serverPath: ''
			}
			this.fileList.push(file)
		}

  	}
}
</script>
<style lang="scss" scoped>
.custom-upload{
	&.mode-percent{
		width: 100%;
		::v-deep .van-uploader{
			width: 100%;
			.van-uploader__wrapper{
				justify-content: flex-end;
				.van-uploader__preview, .van-uploader__upload{
					width: calc(100% / 3 - 8px);
					margin-right: 0;
					margin-left: 8px;
					.van-uploader__preview-image{
						width: 100%;
						padding-bottom: 100%;
						height: auto;
						position: relative;
					}
					.van-image__error, .van-image__img, .van-image__loading{
						position: absolute;
					}
				}
				.van-uploader__upload{
					width: calc(100% / 3 - 8px);
					height: auto;
					&::after{
						content: "";
						width: 100%;
						padding-bottom: 100%;
						height: auto;
						position: relative;
					}
					.van-icon-photograph{
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translateX(-50%) translateY(-50%);
					}
					input{
						z-index: 1;
					}
					img{
						width: 100%;
					}
				}
				.van-uploader__input-wrapper{
					width: calc(100% / 3 - 8px);
					height: 100%;
					margin-right: 0;
					margin-left: 8px;
					margin-bottom: 8px;
					img{
						width: 100%;
						display: block;
					}
				}
			}
		}

		&.mode-percent-4{
			::v-deep .van-uploader{
				.van-uploader__wrapper{
					.van-uploader__preview, .van-uploader__upload, .van-uploader__input-wrapper{
						width: calc(100% / 4 - 8px);
					}
				}
			}
		}

		&.mode-percent-5{
			::v-deep .van-uploader{
				.van-uploader__wrapper{
					.van-uploader__preview, .van-uploader__upload{
						width: calc(100% / 5 - 8px);
					}
				}
			}
		}

		&.custom-upload-align-left{
			::v-deep .van-uploader{
				.van-uploader__wrapper{
					justify-content: flex-start;
					.van-uploader__preview, .van-uploader__upload, .van-uploader__input-wrapper{
						margin-left: 0;
						margin-right: 8px;
					}
				}
			}
		}
	}
	&.custom-upload-disabled{
		::v-deep .van-uploader{
			.van-uploader__wrapper{
				.van-uploader__upload, .van-uploader__preview-delete, .van-uploader__input-wrapper{
					display: none;
				}
			}
		}
	}

	&.custom-upload-not-web, &.custom-upload-over{
		::v-deep .van-uploader{
			.van-uploader__wrapper{
				.van-uploader__upload, .van-uploader__input-wrapper{
					display: none;
				}
			}
		}
	}
	
	.action-list{
		width: 100%;
		.van-uploader{
			width: 100%;
		}
		.van-uploader__input-wrapper{
			width: 100%;
		}
		.item{
			text-align: center;
			font-size: 16px;
			line-height: 22px;
			padding: 14px 16px;
			background: #fff;
			&.cancel{
				border-top: 10px solid #f5f5f5;
			}
		}
	}
}
</style>
