<template>
	<view class="container">
		<view class="custom-uni-list">
			<uni-list>
				<view class="list-item-bg" style="border-bottom: 20rpx solid #f2f2f2;">
					<view style="line-height: 110rpx;color: #adb0b5;padding-left: 40rpx;font-weight: 500;">
						{{$t('index.contract-info')}}
					</view>
				</view>

				<view class="list-item-bg">
					<uni-list-item :border="false" style="width: 100%;" :title="$t('index.contract-code')">
						<template v-slot:footer>
							<input class="custom-uni-value" v-model="contractNum" type="text"
								:placeholder="$t('index.enter')+$t('index.contract-code')" />
						</template>
					</uni-list-item>
				</view>
				<view class="list-item-bg">
					<uni-list-item :border="false" style="width: 100%;" :title="$t('index.contract-name')">
						<template v-slot:footer>
							<input class="custom-uni-value" v-model="contractName" type="text"
								:placeholder="$t('index.enter')+$t('index.contract-name')" />
						</template>
					</uni-list-item>
				</view>
				<!-- 有效期 -->
				<view class="list-item-bg">
					<uni-list-item :border="false" style="width: 100%;" :title="$t('index.expire')" showArrow>
						<template v-slot:footer>
							<uni-datetime-picker style="flex: auto" v-model="contractDate" type="daterange"
								:border="false" :clearIcon="false">
								<view class="contract">{{contractDate[0]}}~{{contractDate[1]}}</view>
							</uni-datetime-picker>
						</template>
					</uni-list-item>
				</view>

			</uni-list>
		</view>
		<view class="upload-box">
			<view class="upload-title">{{$t('index.annex-upload')}}</view>
			<view class="upload">
				<view class="plusempty-box">
					<view class="plusempty" @click="choseFile">
						<uni-icons type="plusempty" size="30" color='#D5E2F3'></uni-icons>
						<text>{{$t('index.pdf-upload')}}</text>
					</view>
					<!-- <view class="plusempty" @click="choseImage">
						<uni-icons type="plusempty" size="30" color='#D5E2F3'></uni-icons>
						<text>{{$t('index.pictrue-upload')}}</text>
					</view> -->
				</view>
				<view class="file-box">
					<view class="file" v-for="(item, index) in fileList" :key="item.path">
						<text class="name" @click="previewPDF(item.path)">{{item.name}}</text>
						<icon class="icon-small" @click="deletePDF(index)" type="cancel" size="18"></icon>
					</view>
					<view class="file" v-for="(item, index) in imageList" :key="item.id">
						<text class="name" @click="previewImage(item)">{{item.fileName}}</text>
						<icon class="icon-small" @click="deleteImage(index)" type="cancel" size="18"></icon>
					</view>
				</view>
			</view>
		</view>

		<view class="btn-box">
			<button class="button" type="primary" @click="submite">{{$t('index.sure')}}</button>
		</view>
	</view>
</template>

<script>
	import {
		uploadFile,
		uploadSaveContract
	} from '@/config/api.js'
	// #ifdef APP-PLUS
	// import fileSelect from "@/uni_modules/lemon-filePicker"

	const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
	// #endif
	let orderId = null;
	export default {
		name: 'detail',
		data() {
			const date = new Date();
			const currentDate = this.getDate(date)
			const nextDate = new Date(date.getTime() + 30 * 24 * 60 * 60 * 1000)
			const monthDate = this.getDate(nextDate)
			return {
				contractNum: '',
				contractName: '',
				contractDate: [currentDate, monthDate],
				fileList: [],
				imageList: []
			}
		},
		computed: {
			canImageNumber() {
				return (3 - this.fileList.length - this.imageList.length)
			}
		},
		methods: {
			getDate(date) {
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// bindDateChange: function(e) {
			//     this.date = e.detail.value
			// },
			choseImage() {
				if ((this.fileList.length + this.imageList.length) >= 3) {
					uni.showToast({
						title: this.$t('index.upload-max'),
						icon: 'none'
					});
					return
				}
				let _this = this
				uni.chooseImage({
					count: _this.canImageNumber,
					success: (res) => {
						_this.select(res)
					}
				});
			},
			choseFile() {
				if ((this.fileList.length + this.imageList.length) >= 3) {
					uni.showToast({
						title: this.$t('index.upload-max'),
						icon: 'none'
					});
					return
				}
				let _this = this
				// #ifdef APP-PLUS
				lemonjkFileSelect.showPicker({
					//各属性配置见下方【showPicker可配置参数说明】
					pathScope: "/Download",
					mimeType: "*/*",
					utisType: "public.data",
				}, result => {
					// 返回值说明见下方【showPicker返回值说明】

					//（仅安卓，插件版本<4.0.0）当错误码为1001，即未授权文件读取权限,可以提示用户未打开读取文件权限，并跳转设置页
					//插件版本4.0.0+当没有相关权限时会自动跳转到设置页面，无需判断，如需在跳转前执行
					//用户提示等需求，请使用4.0.0+新增的API(isHaveSecurityScopeGrant)查询权限
					if (result.code == 1001) {
						uni.showModal({
							title: _this.$t('index.access-title'),
							content: _this.$t('index.access-desc'),
							confirmText: _this.$t('index.access-sure'),
							cancelText: _this.$t('index.access-cancel'),
							success(e) {
								if (e.confirm) {
									// 跳转到应用设置页
									lemonjkFileSelect.gotoSetting();
								}
							}
						})
					}
					if (result.code == 0) {
						uni.downloadFile({
							url: res.filePath,
							success(e) {
								console.log(e);
								// ios请使用该路径（e.tempFilePath）
								let serveList = []
								serveList.push(_this.uploadPDF(e.tempFilePath))
								Promise.all(serveList).then(data => {
									var fileData = [{
										id: data[0].id,
										name: res.fileName,
										path: res.filePath
									}]
									_this.fileList = _this.fileList.concat(
										fileData)
									setTimeout(() => {
										uni.showToast({
											title: _this.$t(
												'index.operate-success'
											),
											icon: 'none'
										});
									}, 30)
								}).catch(err => {
									setTimeout(() => {
										uni.showToast({
											title: _this.$t(
												'index.msg-upload-err'
											),
											icon: 'none'
										});
									}, 30)
								})
							}
						})
					}
				})

				// fileSelect({
				// 	permission: false,
				// 	mimetype: "application/pdf",
				// 	success(res) {
				// 		console.log(res);
				// 		//返回数据格式说明见下方 【fileSelect返回值说明】             
				// 		uni.getSystemInfo({
				// 			success(info) {
				// 				if (info.osName == 'ios') {
				// 					console.log("我是ios")
				// 					// 由于ios文件沙盒机制，需要使用uni.downloadFile下载后，获取到的文件临时路径（_doc/xxx）后使用该路径去上传
				// 					// 或使用原生插件版文件选择，免此步骤：  https://ext.dcloud.net.cn/plugin?id=14059
				// 					uni.downloadFile({
				// 						url: res.filePath,
				// 						success(e) {
				// 							console.log(e);
				// 							// ios请使用该路径（e.tempFilePath）
				// 							let serveList = []
				// 							serveList.push(_this.uploadPDF(e.tempFilePath))
				// 							Promise.all(serveList).then(data => {
				// 								var fileData = [{
				// 									id: data[0].id,
				// 									name: res.fileName,
				// 									path: res.filePath
				// 								}]
				// 								_this.fileList = _this.fileList.concat(
				// 									fileData)
				// 								setTimeout(() => {
				// 									uni.showToast({
				// 										title: _this.$t(
				// 											'index.operate-success'
				// 										),
				// 										icon: 'none'
				// 									});
				// 								}, 30)
				// 							}).catch(err => {
				// 								setTimeout(() => {
				// 									uni.showToast({
				// 										title: _this.$t(
				// 											'index.msg-upload-err'
				// 										),
				// 										icon: 'none'
				// 									});
				// 								}, 30)
				// 							})

				// 						}
				// 					})
				// 				} else {
				// 					console.log("我是安卓", res)
				// 					//安卓可以直接使用  res.filePath
				// 					let serveList = []
				// 					serveList.push(_this.uploadPDF(res.filePath))
				// 					Promise.all(serveList).then(data => {
				// 						var fileData = [{
				// 							id: data[0].id,
				// 							name: res.fileName,
				// 							path: res.filePath
				// 						}]
				// 						_this.fileList = _this.fileList.concat(fileData)
				// 						setTimeout(() => {
				// 							uni.showToast({
				// 								title: _this.$t(
				// 									'index.operate-success'),
				// 								icon: 'none'
				// 							});
				// 						}, 30)
				// 					}).catch(err => {
				// 						setTimeout(() => {
				// 							uni.showToast({
				// 								title: _this.$t(
				// 									'index.msg-upload-err'),
				// 								icon: 'none'
				// 							});
				// 						}, 30)
				// 					})
				// 				}
				// 			}
				// 		})
				// 	},
				// 	fail(err) {
				// 		console.log(err);
				// 		// err.code=1001  未授权文件读取权限,可以提示用户未打开读取文件权限（仅安卓）
				// 		if (err.code == 1001) {
				// 			uni.showModal({
				// 				title: _this.$t('index.access-title'),
				// 				content: _this.$t('index.access-desc'),
				// 				confirmText: _this.$t('index.access-sure'),
				// 				cancelText: _this.$t('index.access-cancel'),
				// 				success(e) {
				// 					if (e.confirm) {
				// 						fileSelect({
				// 							permission: true
				// 						})
				// 					}
				// 				}
				// 			})
				// 		}
				// 	}
				// })
				// #endif
				// #ifdef MP-WEIXIN
				wx.chooseMessageFile({
					count: _this.canImageNumber,
					type: 'file',
					extension: ['pdf', 'PDF'],
					success(res) {
						// tempFilePath可以作为 img 标签的 src 属性显示图片
						let serveList = []
						res.tempFiles.forEach(item => {
							serveList.push(_this.uploadPDF(item.path))
						})
						Promise.all(serveList).then(data => {
							res.tempFiles.forEach((item, index) => {
								item['id'] = data[index]['id']
							})
							_this.fileList = _this.fileList.concat(res.tempFiles)
							setTimeout(() => {
								uni.showToast({
									title: _this.$t('index.operate-success'),
									icon: 'none'
								});
							}, 30)
						}).catch(err => {
							setTimeout(() => {
								uni.showToast({
									title: _this.$t('index.msg-upload-err'),
									icon: 'none'
								});
							}, 30)
						})
					}
				})
				// #endif
			},
			uploadPDF(path) {
				return new Promise((resolve, reject) => {
					uploadFile({
						filePath: path,
						name: 'file',
						formData: { //其他需要携带的参数
							'modelType': 'default'
						}
					}).then(({
						content
					}) => {
						resolve(content)
					}).catch(err => {
						reject(err)
					})
				})
			},
			previewPDF(filePath) {
				//预览本地文档
				// #ifdef MP-WEIXIN
				wx.openDocument({
					fileType: 'pdf', // 需要写上文件类型才能预览，不让回找系统应用打开，体验不好
					filePath,
					showMenu: false, //是否显示右上角菜单按钮  默认为 false
					success: function(res) {
						console.log('打开本地文档成功')
					},
					fail: function(error) {
						console.log("打开本地文件失败")
					}
				})
				// #endif
				//#ifdef APP-PLUS
				console.log(">>>>>>>>>>", filePath)
				uni.openDocument({
					filePath: filePath,
					showMenu: true,
					success: function(res) {
						console.log('打开本地文档成功');
					},
					fail: function(error) {
						console.log("打开本地文件失败", error)
					}
				});
				// #endif
			},
			previewImage(item) {
				let urls = item.urlPrefix + item.fullFilePath
				uni.previewImage({
					urls: [urls]
				})
			},
			// 获取上传状态
			select(e) {
				let serveList = []
				e.tempFilePaths.forEach(url => {
					serveList.push(this.uploadImage(url))
				})
				Promise.all(serveList).then(data => {
					setTimeout(() => {
						uni.showToast({
							title: this.$t('index.operate-success'),
							icon: 'none'
						});
					}, 30)
					this.imageList = this.imageList.concat(data)
				}).catch(err => {
					setTimeout(() => {
						uni.showToast({
							title: this.$t('index.msg-upload-err'),
							icon: 'none'
						});
					}, 30)
				})
			},
			uploadImage(path) {
				return new Promise((resolve, reject) => {
					uploadFile({
						filePath: path,
						name: 'file',
						formData: { //其他需要携带的参数
							'modelType': 'default'
						}
					}).then(({
						content
					}) => {
						resolve(content)
					}).catch(err => {
						reject(err)
					})
				})
			},
			deletePDF(index) {
				this.fileList.splice(index, 1)
			},
			deleteImage(index) {
				this.imageList.splice(index, 1)
			},
			submite() {
				if (!this.contractNum.trim()) {
					uni.showToast({
						title: this.$t('index.enter') + this.$t('index.contract-code'),
						icon: 'none'
					});
					return
				}
				if (!this.contractName.trim()) {
					uni.showToast({
						title: this.$t('index.enter') + this.$t('index.contract-name'),
						icon: 'none'
					});
					return
				}
				if (!this.fileList.length && !this.imageList.length) {
					uni.showToast({
						title: this.$t('index.enter-annex-upload'),
						icon: 'none'
					});
					return
				}
				let uploadFileId = this.fileList.concat(this.imageList).map(item => item.id).join(',')
				uploadSaveContract({
					contractDate: this.contractDate,
					contractNum: this.contractNum,
					contractName: this.contractName,
					startDate: this.contractDate[0],
					endDate: this.contractDate[1],
					orderId,
					uploadFileId
				}).then(res => {
					setTimeout(() => {
						uni.showToast({
							title: this.$t('index.operate-success')
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500)
					}, 30)
				})
			}
		},
		onLoad(options) {
			orderId = options.id
			this.contractNum = options.code || ''
			this.contractName = options.name || ''
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		box-sizing: border-box;
		min-height: 100vh;
		background-color: #fff;

		.contract {
			font-size: 14px;
			color: #B60001;
			text-align: right;
		}

		.upload-box {
			padding: 12px 15px 0;

			.upload-title {
				font-size: 14px;
				color: #B60001;
				;
			}

			.upload {
				margin-top: 12px;

				.plusempty-box {
					display: flex;

					.plusempty {
						width: 190rpx;
						height: 190rpx;
						background: #FFFFFF;
						border: 1px solid #D5E2F3;
						border-radius: 20rpx;
						font-size: 32px;
						margin-right: 30rpx;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
					}

					text {
						color: #999;
						font-size: 12px;
					}
				}

				.file-box {
					padding-top: 30rpx;

					.file {
						display: flex;
						justify-content: space-between;
						align-items: center;
						word-break: break-all;

						.name {
							flex: auto;
							padding: 15rpx 0;
							font-size: 12px;
							color: #B60001;
						}

						.icon {
							flex: none;
							margin-left: 30px;
						}
					}
				}
			}
		}

		.btn-box {
			padding: 0 30rpx;
			margin-top: 100rpx;

			.button {
				height: 92rpx;
				line-height: 92rpx;
				background-color: #086DCA;
				font-size: 30rpx;
				color: #FFFFFF;
			}
		}
	}

	.list-item-bg {
		background: #fff;
		display: flex;
		align-items: center;
		height: 110rpx;
		border-bottom: 1px solid #f2f2f2;
	}
</style>