<template>
	<view class="imageUploadContainer">
		<view class="imageUploadList">
			<view class="imageItem" v-for="(path, index) in imageListData" :key="index">
				<image :src="path" @tap="previewImage" :data-index="index"></image>
				<view v-if="isShowDel" class="imageDel" @tap="deleteImage" :data-index="index">X</view>
			</view>
			<image v-if="isShowAdd" src="../../static/img/hcdb/i-camera.png" class="imageUpload" @tap="selectImage"></image>
			<!-- <view v-if="isShowAdd" class="imageUpload" @tap="selectImage">+</view> -->
		</view>
	</view>
</template>

<script>
import permision from '@/common/permission.js';
import compressImage from '@/common/imageutil.js';
import { requestUploadFile } from '../../utils/request';

const device = uni.getSystemInfoSync();

export default {
	name: 'image-upload',
	props: {
        value: {
            type: Array,
            default: () => {
                return []
            }
        },
        enableDel: {
            type: Boolean,
            default: true
        },
        enableAdd: {
            type: Boolean,
            default: true
        },
        limit: {
            type: Number,
            default: 9
        },
        attfileList: {
            type: Array,
            default: () => {
                return []
            }
        },
        dataIndex: {
            type: Number,
            default: 0
        },
        filePath: {
            type: String,
            default: ''
        },
        isCurrentUpload: {
            type: Boolean,
            default: true
        }
    },
	data() {
		return {
			imageList: [],
			isDestroyed: false
		};
	},
	mounted: function() {
		this.imageList = this.value;
	},
	destroyed: function() {
		this.isDestroyed = true;
	},
	watch: {
		value: {
			handler (val) {
				this.imageList = val
			},
			immediate: true,
			deep: true
		}
	},
	computed: {
		imageListData: function() {
			if (this.value) {
				return this.value;
			}
		},
		isShowDel: function() {
			if (this.enableDel === false) {
				return false;
			} else {
				return true;
			}
		},
		isShowAdd: function() {
			if (this.enableAdd === false) {
				return false;
			}
			// if (this.limit && this.imageList.length >= this.limit) {
			// 	return false;
			// }
			return true;
		}
	},
	methods: {
		selectImage: async function() {
			var _self = this;
			if (!_self.imageList) {
				_self.imageList = [];
			}
			// #ifdef APP-PLUS
			// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
			// if (this.sourceTypeIndex !== 2) {
			// 	let status = await this.checkPermission();
			// 	if (status !== 1) {
			// 		return;
			// 	}
			// }
			// #endif
			// if (this.imageList.length == this.limit) {
			// 	let isContinue = await this.isFullImg();
			// 	console.log('是否继续?', isContinue);
			// 	if (!isContinue) {
			// 		return;
			// 	}
			// }
			// 限制上传图片数量
			// if (!!this.limit) {
			// 	if (this.imageList.length == this.limit) {
			// 		let isContinue = await this.isFullImgNew();
			// 		return;
			// 	}
			// }
			// 选择图片
			uni.chooseImage({
                sizeType: ['original', 'compressed'],
				count: this.limit ? this.limit : 9,
				success: async e => {
					uni.showLoading({
						title: '上传中',
                        mask: true
					});
                    _self.$emit('uploading', true);
					let imagePathArr = e.tempFilePaths;
					let headerObj = {};
                    if (_self.isCurrentUpload) {
                        if (uni.getStorageSync('access_token')) {
                        	headerObj['Authorization'] = 'Bearer' + uni.getStorageSync('access_token');
                        }
                        for (let i = 0; i < imagePathArr.length; i++) {
                        	const src = await this.compressImageHandler(imagePathArr[i]);
                        	let res = await requestUploadFile({
                        		method: 'post',
                        		url: 'diskUpload',
                        		src: src,
                                path: this.filePath || 'upload'
                        	})
                            let result = JSON.parse(res);
                            if (result.code == 0) {
                                _self.imageList.push(src);
                            	_self.$emit('data', result.data, this.dataIndex);
                            } else {
                                uni.showToast({
                                	title: '上传图片出错',
                                	icon: 'none'
                                });
                            }
                        }
                        uni.hideLoading();
                        if (_self.imageList.length == imagePathArr.length) {
                            uni.showToast({
                            	title: '上传图片成功',
                            	icon: 'success'
                            });
                        }
                        _self.$emit('add', {
                        	currentImages: imagePathArr,
                        	allImages: _self.imageList
                        });
                        _self.$emit('input', _self.imageList);
                        _self.$emit('uploading', false);
                    } else  {
                        uni.hideLoading();
                        _self.imageList = imagePathArr;
                        _self.$emit('data', imagePathArr);
                        _self.$emit('add', {
                        	currentImages: imagePathArr,
                        	allImages: imagePathArr
                        });
                        _self.$emit('input', imagePathArr);
                        _self.$emit('uploading', false);
                    }
                    
				},
				fail: err => {
					console.log(err);
					if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
						this.checkPermission(err.code);
					}
					// uni.getSetting({
					// 	success: res => {
					// 		let authStatus = false;
					// 		switch (this.sourceTypeIndex) {
					// 			case 0:
					// 				authStatus = res.authSetting['scope.camera'];
					// 				break;
					// 			case 1:
					// 				authStatus = res.authSetting['scope.album'];
					// 				break;
					// 			case 2:
					// 				authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
					// 				break;
					// 			default:
					// 				break;
					// 		}
					// 		if (!authStatus) {
					// 			uni.showModal({
					// 				title: '授权失败',
					// 				content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
					// 				success: res => {
					// 					if (res.confirm) {
					// 						uni.openSetting();
					// 					}
					// 				}
					// 			});
					// 		}
					// 	}
					// });
				}
			});
		},
		deleteImage: function(e) {
			var imageIndex = e.currentTarget.dataset.index;
			console.log(this.imageList)
			var deletedImagePath = this.imageList[imageIndex];
			this.imageList.splice(imageIndex, 1);
			this.attfileList.splice(imageIndex, 1);
			this.$emit('delete', {
				currentImage: deletedImagePath,
				allImages: this.imageList
			}, this.dataIndex);
			this.$emit('input', this.imageList);
		},
		previewImage: function(e) {
			var imageIndex = e.currentTarget.dataset.index;
			uni.previewImage({
				// current: this.imageList[imageIndex],
				current: imageIndex,
				indicator: 'number',
				loop: 'true',
				urls: this.imageList
			});
		},
		isFullImg: function() {
			return new Promise(res => {
				uni.showModal({
					content: '已经有' + this.limit + '张图片了,是否清空现有图片？',
					success: e => {
						if (e.confirm) {
							this.imageList = [];
							res(true);
						} else {
							res(false);
						}
					},
					fail: () => {
						res(false);
					}
				});
			});
		},
		// 限制图片上传数量
		isFullImgNew: function() {
			return new Promise(res => {
				uni.showModal({
					content: '最多上传6张照片',
					success: e => {
						if (e.confirm) {
							res(true);
						} else {
							res(false);
						}
					},
					fail: () => {
						res(false);
					}
				});
			});
		},
		async compressImageHandler(src) {
			const tempPath = await compressImage(src, device.platform);
			return tempPath;
		},
		async checkPermission(code) {
			let type = code ? code - 1 : this.sourceTypeIndex;
			let status = permision.isIOS
				? await permision.requestIOS(sourceType[type][0])
				: await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' : 'android.permission.READ_EXTERNAL_STORAGE');
			if (status === null || status === 1) {
				status = 1;
			} else {
				uni.showModal({
					content: '没有开启权限',
					confirmText: '设置',
					success: function(res) {
						if (res.confirm) {
							permision.gotoAppSetting();
						}
					}
				});
			}
			return status;
		}
	}
};
</script>

<style>
.imageUploadContainer {
	/* padding: 10rpx 5rpx; */
	margin: 10rpx 5rpx;
}

.imageUploadList {
	display: flex;
	flex-wrap: wrap;
}

.imageItem,
.imageUpload {
	width: 160rpx;
	height: 160rpx;
	margin: 10rpx;
}

.imageDel {
	position: relative;
	left: 120rpx;
	bottom: 165rpx;
	background-color: rgba(0, 0, 0, 0.5);
	width: 36rpx;
	text-align: center;
	line-height: 35rpx;
	border-radius: 17rpx;
	color: white;
	font-size: 30rpx;
	padding-bottom: 2rpx;
}

.imageItem image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
}

.imageUpload {
	line-height: 130rpx;
	text-align: center;
	font-size: 150rpx;
	color: #d9d9d9;
	/* border: 1px solid #d9d9d9; */
	/* border-radius: 8rpx; */
}
</style>
