<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 photos_list"
				@click.stop="onBigImg(index)">
				<view class="del-img-video iconfont_yige" @click.stop="delphotos(index)" v-if="!checkPage">&#xe867;
				</view>
				<image class="img-video" :src="item" mode="aspectFit"></image>
			</view> -->
			<view class="img-video-box img-video-item" v-for="(item,index) in videos" :key="`video_${index}`"
				@click.stop="onplay(item)">
				<view class="del-img-video iconfont_yige" v-if="!checkPage" @click.stop="delVldeo(index)">&#xe867;
				</view>
				<image class="img-video" :src="item + '?x-oss-process=video/snapshot,t_0,f_jpg'" mode="aspectFit" />
			</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 } from "@/utils/tool.js"
	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 {
				uploadingLoading: false,
				Storage_key: 'partUploadData',
				File_V: null,
				tempFilePath: null,
				playVideoUrl: '',
			}
		},

		watch: {
			uploadingLoading: {
				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) {
				try {
					this.playVideoUrl = url;
					this.$refs.videoPlayRef.open();
					this.$nextTick(() => {
						try {
							this.videoContext = uni.createVideoContext('myVideo');
							this.videoContext.play();
						} catch (e) {
							console.log('onpssssslay = ', e)
							//TODO handle the exception
						}
					})
				} catch (e) {
					console.log('onplay = ', e)
					//TODO handle the exception
				}
			},
			delVldeo(index) {
				this.videos.splice(index, 1);
			},

			upLoadError(message = '') {
				this.uploadingLoading = false;
				uni.showToast({
					title: message || '上传失败',
					icon: 'none'
				})
			},

			onChooseVideo() {

				try {
					let that = this;
					uni.chooseVideo({
						sourceType: ['camera', 'album'],
						compressed: false, // 压缩
						success: res_file => {
							const max_size = 200 * 1024 * 1024;
							console.log('max_size', res_file)
							if (res_file.size > max_size) {
								uni.showToast({
									title: '最大上传200M视频',
									icon: 'none'
								})
								return
							};
							this.onCheckBigFile(res_file.tempFile)
						},
						fail: err => {
							this.upLoadError()
						}
					});
				} catch (e) {
					this.upLoadError()
				}
			},

			async onCheckBigFile(file) {
				this.uploadingLoading = true
				try {
					const fileMd5 = await getFileMd5(file)
					// 检查是否上传过
					getcheckBigFile_Api({
						fileMd5: fileMd5,
						originalName: file.name
					}).then(res => {
						const { bigStatus, uploadId, url } = res.data || {};
						if (!bigStatus) {
							this.saveFileChunk(file, fileMd5, uploadId);
						} else {
							this.unloadVideos(url);
						}
					}).catch(err => {
						this.upLoadError()
					})
				} catch (e) {
					this.upLoadError()
				}
			},



			// 保存文件片段到后台
			saveFileChunk(File, fileMd5, uploadId) {
				try {
					// 每片的大小为 5M 可调整
					const chunkSize = 5 * 1024 * 1024
					// 文件分片储存
					let chunkList = []

					function chunkPush(page = 1) {
						chunkList.push(File.slice((page - 1) * chunkSize, page * chunkSize))
						// that.uploadFileObj.uploadUrls.push({});

						if (page * chunkSize < File.size) {
							chunkPush(page + 1)
						}
					}
					chunkPush();
					let list = [];
					chunkList.forEach((el, i) => {
						let p = new Promise((resolve, reject) => {
							uni.uploadFile({
								url: this.$mConfig.baseUrl + `/common/upload-tag`,
								file: File,
								formData: {
									fileMd5: fileMd5,
									uploadId: uploadId,
									curPartSize: el.size,
									partNumber: i + 1
								},
								name: 'file',
								success: (uploadFileRes) => {
									const JSON_data = uploadFileRes.data;
									const data = JSON.parse(JSON_data);
									const { tag } = data.data
									resolve(tag)
								},
								fail: err => {
									this.upLoadError()
								}
							});
						})
						list.push(p)

					})

					Promise.all(list).then(tagsList => {
						this.bigFileMergeFun(fileMd5, tagsList, uploadId)
					}).catch(() => {
						this.upLoadError()
					})
				} catch (e) {
					this.upLoadError()
					//TODO handle the exception
				}
			},

			bigFileMergeFun(fileMd5, tagsList, uploadId) {
				try {
					getMargeTag_Api({ fileMd5: fileMd5, tagsList: tagsList, uploadId: uploadId }).then(res => {
						const { url } = res.data || {};
						this.unloadVideos(url)
					}).catch(err => {
						this.upLoadError()
					})
				} catch (e) {
					this.upLoadError()
				}


			},

			unloadVideos(url) {
				if (url) {
					this.videos.push(url)
					this.uploadingLoading = false;
					uni.showToast({
						title: '上传成功',
						icon: 'none'
					})
				} else {
					this.upLoadError()
				}

			}
		}
	}
</script>

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