<template>
	<view :style="vuex_skin">
		<!-- #ifdef MP-WEIXIN -->
		<u-navbar title-color="#000000" :is-back="true" title="我要报名"></u-navbar>
		<!-- #endif -->

		<view class="add-media" @click="handleUploadWork">
			<view class="flex-direction flex justify-center" style="align-items: center;" v-show="!showUrl">
				<u-icon name="plus-circle-fill" :color="vuex_theme.bgColor" size="90"></u-icon>
				<text style="margin-top: 26rpx; color: #010101; font-size: 24rpx; font-weight: bold; width: 70%; color: red;">{{tipsText}}</text>
			</view>
			<video v-if="activeType == 'VIDEO_TEXT' && showUrl" :src="showUrl"></video>
			<image v-if="activeType == 'IMAGE_TEXT' && showUrl" :src="showUrl" mode="aspectFill"></image>
		</view>

		<view class="fill-info">
			<text class="info-title" style="font-weight: bold; color: #010101; font-size: 34rpx;">填写信息</text>
			<view v-if="activeType == 'VIDEO_TEXT'" style="margin-bottom: 64rpx;">
				<text style="color: #010101; font-size: 28rpx; font-weight: bold;"><text style="color: #f00;">*</text> 作品封面</text>
				<view style="padding: 5rpx 0 20rpx; border-bottom: 1rpx solid #E3E3E3;">
					<upload-img ref="uploadImg" :count="1" col="4" @click="uploadCover"></upload-img>
				</view>
			</view>

			<view style="margin-bottom: 64rpx;">
				<text style="color: #010101; font-size: 28rpx; font-weight: bold;"><text style="color: #f00;">*</text> 标题</text>
				<view style="padding: 32rpx 0 0; border-bottom: 1rpx solid #E3E3E3;">
					<u-input placeholder="请输入标题内容" v-model="applyInfo.title"></u-input>
				</view>
			</view>
			
			<view style="margin-bottom: 64rpx;">
				<text style="color: #010101; font-size: 28rpx; font-weight: bold;"><text style="color: #f00;">*</text> 参赛者</text>
				<view style="padding: 32rpx 0 0; border-bottom: 1rpx solid #E3E3E3;">
					<u-input placeholder="请输入参赛者名称" v-model="applyInfo.player"></u-input>
				</view>
			</view>
            
            <view style="margin-bottom: 64rpx;" v-if="guide === 1">
            	<text style="color: #010101; font-size: 28rpx; font-weight: bold;"> 指导老师</text>
            	<view style="padding: 32rpx 0 0; border-bottom: 1rpx solid #E3E3E3;">
            		<u-input placeholder="请输入指导老师" v-model="applyInfo.guideTeacher"></u-input>
            	</view>
            </view>
            
            <view style="margin-bottom: 64rpx;" v-if="guide === 1">
            	<text style="color: #010101; font-size: 28rpx; font-weight: bold;"> 指导机构</text>
            	<view style="padding: 32rpx 0 0; border-bottom: 1rpx solid #E3E3E3;">
            		<u-input placeholder="请输入指导机构" v-model="applyInfo.guideSchool"></u-input>
            	</view>
            </view>

			<view style="margin-bottom: 64rpx;">
				<text style="color: #010101; font-size: 28rpx; font-weight: bold;"><text style="color: #f00;">*</text> 详细介绍</text>
				<view style="padding: 32rpx 0 0; border-bottom: 1rpx solid #E3E3E3;">
					<u-input placeholder="请输入详细介绍" v-model="applyInfo.content"></u-input>
					<!-- <u-input placeholder="请输入详细介绍" v-model="applyInfo.content" type="textarea" height="60" auto-height></u-input> -->
				</view>
			</view>

			<view style="margin-bottom: 64rpx;">
				<text style="color: #010101; font-size: 28rpx; font-weight: bold;"><text style="color: #f00;">*</text> 联系方式</text>
				<view style="padding: 32rpx 0 0; border-bottom: 1rpx solid #E3E3E3;">
					<u-input placeholder="请输入手机号码" v-model="applyInfo.phone"></u-input>
				</view>
			</view>
			<u-button shape="circle" :custom-style="customStyle" @click="submit">确定提交</u-button>
		</view>
		<compress ref="compress"></compress>
		<toast ref="toast"></toast>
		<uploadAlert ref="uploadAlert" :updateProgress="updateProgress" @cancelUpload="cancelUpload"></uploadAlert>
	</view>
</template>

<script>
	import compress from "@/components/compress.vue"
	import uploadImg from "@/components/uploadImg/uploadImg.vue"
	import uploadAlert from "@/components/alert/uploadAlert.vue"
	import config from "@/assets/http/config.js"
	let uploadTask
	export default {
		name: '',
		components: {
			compress,
			uploadImg,
			uploadAlert
		},
		data() {
			return {
				//压缩参数
				compressParams: {
					src: '',
					maxSize: 2048,
					fileType: 'jpg',
					quality: 1,
					minSize: 800 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
				},
				customStyle: {
					color: 'white',
					background: "#E72226",
					fontSize: '32rpx',
					width: '340rpx',
					margin: '25rpx auto 0'
				},
				//显示的url，有可能是图文，也有可能是视频
				showUrl: '',

				applyInfo: {},
				activeType: '', //活动类型: VIDEO_TEXT视频图文 IMAGE_TEXT图片文本
				updateProgress: '', //上传进度
				tipsText: '',
				guide: null, //是否需要指导老师和指导机构
			};
		},
		onLoad(options) {
			if (this.$isEmpty(this.vuex_userId) ||
				this.$isEmpty(options.activeType) ||
				this.$isEmpty(options.activeId)) {
				uni.switchTab({
					url: "/pages/index/home"
				})
				return
			}
			this.initData(options)
			
		},
		methods: {
			/**
			 * 初始化数据
			 */
			initData(options) {
				this.guide = options.guide;
				this.customStyle.background = this.vuex_theme.bgColor
				this.activeType = options.activeType;
				if(this.activeType === 'VIDEO_TEXT'){
					this.tipsText = '提示：视频拍摄后，微信转发保存，即可压缩上传，上传速度可以更快哦！';
				}else{
					this.tipsText = '上传图片作品';
				}
				// this.activeType = 'IMAGE_TEXT';
				this.applyInfo = {
					userId: this.vuex_userId,
					phone: this.vuex_phone,
					activeId: options.activeId,
					title: "",
					imgUrl: "",
					videoUrl: "",
					content: "",
					player: "",
                    guideTeacher: "",
                    guideSchool: ""

				}
			},
			/**
			 * 上传封面
			 */
			uploadCover(e) {
				this.applyInfo.imgUrl = e[0]
			},
			/**
			 * 上传文件
			 * 图文存进imgUrl
			 */
			async uploadFile(params) {
				let res = await this.$api.uploadFile(params)
				if (this.activeType == 'VIDEO_TEXT') {
					this.applyInfo.videoUrl = res.data.data.link;
				} else {
					this.applyInfo.imgUrl = res.data.data.link
				}
			},
			/**
			 * 上传作品
			 */
			handleUploadWork() {
				if (this.activeType == 'VIDEO_TEXT') {
					//上传视频作品
					this.uploadVideoWork()
				} else {
					//上传图片作品
					this.uploadImageWork()
				}
			},
			/**
			 * 上传图文作品
			 */
			async uploadImageWork() {
				let res = await this.$mpi.chooseImage()
				this.compressParams.src = res[0]
				this.$dialog.showLoading('作品上传中..')
				let src= await this.$refs.compress.compress(this.compressParams)
				let resp = await this.$api.uploadFile(src)
				this.applyInfo.imgUrl = resp.data.data.link
				//显示的是图文链接
				this.showUrl = this.applyInfo.imgUrl
				uni.hideLoading()
			},
			/**
			 * 上传视频作品
			 */
			async uploadVideoWork() {
				let resp = await this.chooseVideo()
				// this.$dialog.showLoading('正在上传中..')
				this.$refs.uploadAlert.show = true;
				//上传视频链接
				let videoRes = await this.uploadVideo(resp.tempFilePath)
				this.applyInfo.videoUrl = videoRes.data.link;
				//上传视频封面链接
				// let coverRes = await this.$api.uploadFile(resp.thumbTempFilePath)
				// this.applyInfo.imgUrl = coverRes.data.data.link
				// this.$refs.uploadImg.imgList = [this.applyInfo.imgUrl]
				//显示的是视频链接
				this.showUrl = this.applyInfo.videoUrl
				uni.hideLoading()
			},
			/**
			 * 取消视频作品
			 */
			cancelUpload(){
				uploadTask.abort();
			},
			/**
			 * 选择视频
			 */
			chooseVideo() {
				var that = this;
				return new Promise((resolve, reject) => {
					uni.chooseVideo({
						count: 1,
						sourceType: ['album'],
						success: function(res) {
							let fileSize = (res.size/1024/1024).toFixed(2)
							console.log("视频大小", fileSize)
							if(fileSize > 50){
								that.$refs.toast.error('上传视频不能大于50M')
								return
							}
							resolve(res)
						},
						fail() {
							uni.hideLoading()
						}
					});
				})
			},
			/**
			 * 上传视频
			 */
			uploadVideo(tempFilePath) {
				let that = this;
				return new Promise((resolve, reject) => {
					uploadTask = uni.uploadFile({
						url: `${config.baseURL}/blade-resource/oss/endpoint/put-file`,
						filePath: tempFilePath,
						name: 'file',
						formData: { user: 'test' },
						header: { "Blade-Auth": uni.getStorageSync('token') },
						success(res) {
							resolve(JSON.parse(res.data))
							that.$refs.uploadAlert.show = false;
							that.updateProgress = '';
						},
						fail(err) {
							//用户取消上传
							if(err.errMsg === 'uploadFile:fail abort'){
								that.$refs.uploadAlert.show = false;
								that.updateProgress = '';
								that.$refs.toast.warn('取消上传')
							}
						}
					});

					uploadTask.onProgressUpdate(function(res) {
						that.updateProgress = res;
						console.log('上传进度' + res.progress);
						console.log('已经上传的数据长度' + res.totalBytesSent);
						console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
					});
				});
			},
			/**
			 * 压缩视频
			 */
			compressVideo() {
				uni.compressVideo({
					src: tempFilePath,
					quality: 'high', //'low':低，'medium':中，'high':高  
					bitrate: 0,
					fps: 0,
					resolution: 0,
					success: function(csRes) {
						// 未进入                        
						console.log('压缩后大小')
						console.log(csRes.size)

					},
					fail: function(cfRes) {
						console.log(cfRes)
						uni.showToast({
							title: '视频压缩失败',
							icon: 'none'
						})
					}
				});
			},
			submit() {
				if (this.activeType == 'VIDEO_TEXT') {
					//视频
					if (this.$isEmpty(this.applyInfo.videoUrl)) {
						this.$refs.toast.warn('请上传视频作品')
						return
					}
					if (this.$isEmpty(this.applyInfo.imgUrl)) {
						this.$refs.toast.warn('请上传作品封面')
						return
					}
				} else {
					//图文
					if (this.$isEmpty(this.applyInfo.imgUrl)) {
						this.$refs.toast.warn('请上传图文作品')
						return
					}
				}
				if (this.$isEmpty(this.applyInfo.title)) {
					this.$refs.toast.warn('请输入标题内容')
					return
				}
				if (this.$isEmpty(this.applyInfo.player)) {
					this.$refs.toast.warn('请输入参赛者名称')
					return
				}
				if (this.$isEmpty(this.applyInfo.content)) {
					this.$refs.toast.warn('请输入详细介绍')
					return
				}
				if (this.$isEmpty(this.applyInfo.phone)) {
					this.$refs.toast.warn('请输入手机号')
					return
				}
				this.$api.activity.submitForm(this.applyInfo).then(res => {
					if (res.data.success) {
						this.$dialog.showModalAndBack('添加成功', this.vuex_theme.bgColor)
					}
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.add-media {
		width: 700rpx;
		height: 428rpx;
		border-radius: 14rpx;
		background: #FFFFFF;
		margin: 40rpx auto;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.fill-info {
		width: 700rpx;
		border-radius: 14rpx;
		background: #FFFFFF;
		margin: 0 auto;
		display: flex;
		flex-direction: column;
		padding: 40rpx 54rpx 50rpx;
		margin-bottom: 88rpx;

		.info-title {
			position: relative;
			margin-bottom: 60rpx;

			&:before {
				content: '';
				width: 8rpx;
				height: 32rpx;
				background: var(--bgColor);
				position: absolute;
				left: -18rpx;
				top: 50%;
				transform: translateY(-50%);
			}
		}
	}
</style>
