<template>
	<view class="upload-file-content" @click="handleDownLoad">
		<view class="upload-btn-box" @click="handleOpenFile" v-if="!disabled">
			<u-icon size="20" color="#2663BF" name="file-text"></u-icon>
			<view class="upload-btn">
				上传文档
			</view>
		</view>
		<view class="flie-list">
			<view class="flie-item" v-for="(file, index) in fileList" :key="file.id">
				<view class="file-item-name">
					{{file.fileName}}
				</view>
				<u-icon v-if="!disabled" @click="$emit('fileDelete', index)" size="16" color="red"
					name="close-circle"></u-icon>
			</view>
		</view>
		<view class="no-file" v-if="disabled && !fileList.length">
			暂无文件
		</view>
		<u-popup :show="popupShow" mode="center" round="12">
			<view class="progress-box">
				<u-line-progress :percentage="percentage" height="12">
				</u-line-progress>
				<view class="progress-label"> 正在努力上传中，请稍等！ </view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	// import fileSelect from "@/uni_modules/lemon-filePicker"
	const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');


	export default {
		name: "upload-file",
		props: {
			disabled: {
				type: Boolean,
				default: false
			},
			acceptType: {
				type: Array,
				default: () => (['pdf', 'doc', 'docx', 'xls', 'xlsx'])
			},
			fileList: {
				type: Array,
				default: () => ([])
			},
			maxCount: {
				type: Number,
				default: 1
			}
		},
		data() {
			return {
				popupShow: false,
				percentage: 0
			};
		},
		methods: {
			/**
			 * app选择本地文件
			 **/
			async handleOpenFile() {
				if (this.fileList.length >= this.maxCount) {
					return this.$.toast(`最多上传【${this.maxCount}】条`)
				}
				const {
					filePath,
					fileName
				} = await this.getFileUrl()

				if (this.validFileType(filePath)) {
					console.log('222222222222222222222222', filePath)
					uni.showModal({
						content: `确定选择上传文件【${fileName}】吗`,
						success: async (res) => {
							if (res.confirm) {
								const fileResult = await this.getFile(filePath)
								if (fileResult.code === 200) {
									this.$.toast('文件上传成功')
									this.$emit('fileSuccess', {
										...fileResult,
										fileName: fileName
									})
								} else {
									this.$.toast('文件上传失败')
									this.$emit('fileError', fileResult)
								}
							}
						}
					})
				} else {
					uni.showModal({
						title: "文件类型提示",
						content: `文件格式仅支持【${this.acceptType.join('、')}】`,
						showCancel: false,
					});
				}
			},
			// 点击下载验收材料
			handleDownLoad(e) {
				if (!this.fileList || !this.fileList.length) {
					return
				}
				let path = this.fileList[0].filePath
				console.log('handleDownLoadhandleDownLoadhandleDownLoad',path)
				uni.downloadFile({
					url: path, //仅为示例，并非真实的资源
					success: function(res) {
						console.log(res, 'resresresresresresresresresres')
						if (res.statusCode === 200) {
							uni.hideLoading();
							var filePath = res.tempFilePath;
							uni.openDocument({
								filePath: filePath,
								success: function(res) {
									console.log("打开文档成功");
								},
							});
						}
					},
				});
			},
			getFile(filePath) {
				return new Promise((resolve, reject) => {
					if (filePath) {
						console.log('333333333333333333333', filePath)
						this.percentage = 1;
						this.popupShow = true;
						const uploadTask = uni.uploadFile({
							url: this.$.baseUrl + '/hiddenDanger/ftp/uploadFileToFtp',
							filePath,
							name: "file",
							success: (uploadFileRes) => {
								console.log('44444444444444444444', uploadFileRes)
								if (uploadFileRes.statusCode === 200) {
									resolve(JSON.parse(uploadFileRes.data))
								} else {
									this.$.toast('文件上传失败')
									reject()
								}
							},
							error: (err) => {
								this.$.toast('文件上传失败')
							},
							complete: () => {
								this.popupShow = false;
							}
						})
						uploadTask.onProgressUpdate((progressEvent) => {
							const {
								totalBytesSent,
								totalBytesExpectedToSend
							} =
							progressEvent;
							const number = Math.round(
								(totalBytesSent * 100) / totalBytesExpectedToSend
							);
							this.percentage = number === 100 ? 99 : number;
						});
					} else {
						this.$.toast('当前未选择文件')
						reject()
					}

				})
			},
			validFileType(fileUrl) {
				const fileUrlArr = fileUrl.split('.')
				const type = fileUrlArr[fileUrlArr.length - 1]
				return this.acceptType.includes(type.toLowerCase())
			},
			getFileUrl() {
				return new Promise((resolve, reject) => {
					// #ifndef APP-PLUS
					uni.showToast({
						title: '仅支持app'
					})
					reject({
						message: '仅支持app',
						status: 0
					});
					// #endif
					// #ifdef APP-PLUS
					const funStr = plus.os.name == "iOS" ? 'showPicker' : 'showNativePicker'
					lemonjkFileSelect[funStr]({
						pathScope: "/",
						mimeType: "*/*",
						utisType: "public.data",
						multi: ''
					}, result => {
						console.log('11111111111111111111', result)
						if (result.code == "0") {
							resolve(result.files[0])
						} else {
							if (result.code == "1001") {
								uni.showModal({
									title: "需要文件访问权限",
									content: "您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限（不同手机厂商表述可能略有差异）请根据自己手机品牌设置",
									confirmText: "去授权",
									cancelText: "算了",
									success(e) {
										if (e.confirm) {
											// 跳转到应用设置页
											lemonjkFileSelect.gotoSetting();
										}
									}
								})
							} else {
								uni.showToast({
									title: result.detail,
									icon: 'none'
								})
							}
							reject()
						}
					})
					// #endif
				})
			}
		}
	}
</script>

<style lang="scss">
	.upload-file-content {
		width: 100%;
		text-align: right;
		font-size: 14px;

		.upload-btn-box {
			display: flex;
			align-items: center;
			color: #2663BF;
			padding: 5px 10px;
			justify-content: flex-end;
		}

		.flie-list {
			padding: 5px;

			.flie-item {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				color: #42b983;

				.file-item-name {
					margin-right: 8px;
					max-width: 200px;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
		}

		.no-file {
			color: var(--UI-FG-0);
		}
	}

	.progress-box {
		height: 120rpx;
		width: 540rpx;
		text-align: center;
		padding: 70rpx 20rpx;

		.progress-label {
			margin-top: 30rpx;
		}
	}
</style>