<template>
	<view class="task-form-item form-item-media">
		<view class="form-lable">
			<text><text class="form-must" v-if="rule && rule.required">* </text>视频:</text>
			<text class="form-media-num">({{videos.length}}/{{num}})</text>
		</view>
		<view class="form-img-video">
			<view v-if="videos.length <= num " class="updata-btn img-video-item" @click.stop="onChooseVideo()">
				<text class="iconfont_yige">&#xe69f;</text>
				<text>请上传视频</text>
			</view>
			<view class="img-video-box img-video-item" v-for="(item,index) in videos">
				<view class="video-cover" @click.stop="onplay(item)" />
				<view class="del-img-video iconfont_yige" @click.stop="delVldeo(index)">&#xe867;</view>
				<video :show-center-play-btn="false" :controls="false" class="img-video" :src="item"
					v-if="!checkPage"></video>
			</view>
		</view>
		<uni-popup ref="videoPlayRef" maskBg="rgba(0, 0, 0,.7)" @change="popupChange">
			<view class="video-play" style="width: 100vw;">
				<video autoplay v-if="playVideoUrl" style="width: 100%;max-height: 60vh;" :src="playVideoUrl" />
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import {
		getcheckBigFile_Api,
		setUpload_tag_Api,
		getMargeTag_Api
	} from "@/api/task.js"
	import {
		getFileMd5,
		cutFile
	} from "@/utils/tool.js"
	import {
		uplaodVideo
	} from "@/utils/uplaodVideo"
	export default {
		name: 'submitVideo',
		model: {
			prop: ['videos'],
			event: ['onChange']
		},
		props: {
			checkPage: {
				type: Boolean,
				default: false
			},
			num: {
				type: Number,
				default: 1
			},
			rule: {
				type: Object,
				default: null
			},
			videos: {
				type: Array,
				default: () => [],
				require: true
			},
		},
		data() {
			return {
				fullscreenLoading: false,
				Storage_key: 'partUploadData',
				File_V: null,
				tempFilePath: null,
				playVideoUrl: '',

				uploadFileObj: {
					tagsList: [],
					uploadUrls: []
				},
			}
		},

		watch: {
			fullscreenLoading: {
				handler(newL, oldL) {
					if (newL) {
						uni.showLoading({
							title: '上传视频中',
							mask: true
						})
					} else {
						uni.hideLoading()
					}
				},

			}
		},
		mounted() {

		},
		methods: {
			popupChange(e) {
				if (!e || !e.show) {
					this.playVideoUrl = null;
				}
			},
			// 播放视频
			onplay(url) {
				this.playVideoUrl = url;
				this.$nextTick(() => {
					this.$refs.videoPlayRef.open();
					this.videoContext = uni.createVideoContext('myVideo');
					this.videoContext.play()
				})
			},
			delVldeo(index) {
				this.videos.splice(index, 1);
			},
			onChooseVideo() {
				try {
					uni.removeStorageSync(this.Storage_key);
				} catch (e) {
					// error
				}
				try {
					uni.chooseVideo({
						sourceType: ['camera', 'album'],
						compressed: true, // 压缩
						success: res => {

							plus.io.resolveLocalFileSystemURL(res.tempFilePath, (entry) => {
								entry.file(async (ent) => {
									// this.file = ent
									console.log('plus.io = ', ent)
									// uploadVideo是我从其他的js文件导入的方法
									await uplaodVideo(ent)
								})
							})


							return
							console.log('fileMd5 1= ', res)
							this.File_V = res;
							this.tempFilePath = res.tempFilePath;
							this.onCheck_Md5(res.tempFilePath, res)

						},
						fail: err => {
							console.log('fileMd5 err = ', err)
						}
					});
				} catch (e) {
					console.log('fileMd5 e= ', e)
					//TODO handle the exception
				}
			},
			async onCheck_Md5(tempFilePath, File) {
				console.log('onCheck_Md5 e= ', tempFilePath, File)
				const fileMd5 = await getFileMd5(File);
				console.log('fileMd5 2= ', fileMd5)
				if (!fileMd5) return
				this.fullscreenLoading = true
				getcheckBigFile_Api({
					fileMd5: fileMd5,
					originalName: File.name || File.tempFilePath
				}).then(res => {
					console.log('b = res ', res)
					const data = res.data;

					if (!data.bigStatus) {
						this.saveFileChunk(File, tempFilePath, fileMd5, data.uploadId);
					} else {
						this.unloadVideos(data.url);
					}

				}).catch(err => {
					console.log('b = ', err)
					this.fullscreenLoading = false;
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				})
			},

			splitFileIntoChunks(file, chunkSize) {
				const fileSize = file.size;
				const chunks = Math.ceil(fileSize / chunkSize);
				const fileChunks = [];

				for (let i = 0; i < chunks; i++) {
					const start = i * chunkSize;
					const end = Math.min(start + chunkSize, fileSize);
					const chunk = file.slice(start, end);
					fileChunks.push(chunk);
				}

				return fileChunks;
			},
			// 保存文件片段到后台
			async saveFileChunk(File, tempFilePath, fileMd5, uploadId) {
				const chunkSize = 1024 * 1024 * 5;
				console.log('b = res ', chunkSize)
				// 获取文件信息
				try {
					let fileSize = File.size; // 文件大小，单位Byte

					const fileChunks = this.splitFileIntoChunks(File, fileSize)

					console.log('fileChunks = ', fileChunks)
					return false

					// 循环处理每个切片
					let chunkList = []
					for (let i = 0; i < chunkCount; i++) {
						let start = i * chunkSize;
						let end = Math.min(start + chunkSize, fileSize);

						function chunkPush(page = 0) {
							chunkList.push(File.slice(start, end))
							// that.uploadFileObj.uploadUrls.push({});

							if (page * chunkSize < fileRaw.size) {
								chunkPush(page + 1)
							}
						}
						chunkPush()
						console.log('1111111 = ', chunkList)
					}
					return

				} catch (e) {
					//TODO handle the exception
					console.log('------------- ', e)
				}

				// cutFile(File).then(cutFileList => {
				// 	console.log('fileMd5  3 = ', cutFileList)
				// 	let num = 0;
				// 	let list = [];
				// 	let uploadFileObj = []
				// 	for (let i = 0; i < cutFileList.length; i++) {
				// 		console.log('fileMd5 = ', i)
				// 		let p = new Promise((resolve, reject) => {
				// 			const item = cutFileList[i];
				// 			uni.uploadFile({
				// 				url: this.$mConfig.baseUrl + '/common/upload-tag',
				// 				formData: {
				// 					file: item.blob,
				// 					fileMd5: fileMd5,
				// 					uploadId: uploadId,
				// 					curPartSize: item.blob.size,
				// 					partNumber: item.partNumber
				// 				},
				// 				success: (uploadFileRes) => {
				// 					const JSON_data = uploadFileRes.data;
				// 					const data = JSON.parse(JSON_data);
				// 					const tag = data.data.tag;
				// 					uploadFileObj.push(tag)
				// 					resolve()

				// 				},
				// 				fail(fail) {
				// 					reject()
				// 				}
				// 			})
				// 		});
				// 		list.push(p)
				// 	}

				// 	Promise.all(list).then(() => {
				// 		this.bigFileMergeFun(uploadFileObj, fileMd5, uploadId)
				// 	}).catch(() => {
				// 		this.fullscreenLoading = false;
				// 		uni.showToast({
				// 			title: '上传失败',
				// 			icon: 'none'
				// 		})
				// 	})
				// })
			},


			// 合并
			bigFileMergeFun(uploadFileObj, fileMd5, uploadId) {
				console.log('bigFileMergeFun 4= ', uploadFileObj)
				let param = {
					fileMd5: fileMd5,
					tagsList: uploadFileObj,
					uploadId: uploadId
				}
				getMargeTag_Api(param).then(res => {
					console.log('getMargeTag_Api 5= ', res)
					const url = res.data.url;
					this.unloadVideos(url)
				}).catch(err => {
					this.fullscreenLoading = false;
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				})
			},

			unloadVideos(url) {
				this.videos.push(url)
				this.fullscreenLoading = false;
				uni.showToast({
					title: '上传成功',
					icon: 'none'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '~./submint.scss';

	.video-cover {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 2;
	}
</style>