<template>
	<view style="padding: 0 40rpx;padding-top:48rpx;">
		<view style="background:#FFFFFF;border-radius:16rpx;overflow:hidden;">
			<view class="_video">
				<video id="myVideo" class="videobox" :autoplay="false" :controls="false" :loop="true" :show-center-play-btn="false"
				:src="videoMsg.videoUrl" :poster="videoMsg.videoUrl+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto'">
					<cover-view class="controls" @tap.stop="videoUpload()" @touchmove.stop="stopTouchmove()">
						<!-- 点击更换视频 -->
					</cover-view>
				</video>
			</view>
		</view>
        <view style="" class="font-30 color-99 text-center margin-top-sm">建议比例16:9，画面清晰，最大上传50M</view>
		<view style="padding-top: 48rpx;">
			<text style="font-weight: bold; font-size: 19px; ">视频类目</text>	
		</view>
		<view style="margin-top:16rpx; height:80rpx;background:#FFFFFF;border-radius:10rpx;font-size:30rpx; color:#999;" class="flex align-center justify-between padding-lr-sm"
			:class="videoMsg.videoCategoryId!=''?'active-select':''" @tap="showCategory = true">
			<text>{{categoryName}}</text>
			<u-icon name="arrow-down-fill" color="#909399" size="13px" v-if="videoMsg.videoCategoryId==''"></u-icon>
			<u-icon name="arrow-down-fill" color="#FF4F20" size="13px" v-else></u-icon>
		</view>

		<view style="padding-top: 48rpx;" class="flex align-center justify-between">
			<text style="font-weight: bold; font-size: 19px; ">视频介绍</text>
			<view style="color: #909399;" class="flex align-center">
				<text :class="videoMsg.videoDesc.length!=0?'text-main':''">{{videoMsg.videoDesc.length}}</text>/30</view>
		</view>
		<view class="box">
			<u-input type="textarea" @input="aaa" cursor-spacing="10" v-model="videoMsg.videoDesc" height="200" :auto-height="false" placeholder="请添加视频描述" maxlength="30" :clearable="false"/>
        </view>
        <view v-if="isEmoji" style="margin-top:10rpx;color:#FF2600;padding-left:4rpx;" class="text-sm">视频介绍不能包含特殊字符</view>
		<view class="btn-box flex justify-center">
		    <view class="btn" @click="touploadCover()" :class="videoMsg.videoDesc.length==0||videoMsg.videoCategoryId==''||isEmoji?'':'comitBtn'">上传视频封面</view>
		</view>

		<u-select v-model="showCategory" :list="categoryList" :default-value="defaultValue" value-name="categoryId" label-name="categoryName" @confirm="confirm"></u-select>

		<com-select-picture :show="uploadVideoShow" :length="1" @addProperties="chooseVideoSuccess" @cancelSheet="cancelSheetClick" chooseUploadFileType='video'></com-select-picture>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				showCategory: false,
				type: "",
				categoryName: "请选择视频类目",
				categoryList: [],
				videoMsg: {
					videoDesc: "",
					videoCategoryId: "",
					serverId: "",
					videoUrl: "",
					videoFaceUrl: "",
                    videoId: "",
				},
				defaultValue: [0],
                isEdit: false,
                uploadVideoShow: false,
                isEmoji: false, //是否包含特殊字符
                fileObj: {},
                expire: 0,
			}
		},
		onShow() {
      
			
			
			
		},
		onLoad(options) {
			this.type = options.uploadType;
            if(!this.$isNull(options.videoId)) {
                this.isEdit = true;
                this.getVideoDetail(options.videoId);
            } else {
                let videoData = uni.getStorageSync('uploadVideo')
                // console.log(videoData)
                this.videoMsg = Object.assign(this.videoMsg,videoData)
                this.videoMsg.serverId = uni.getStorageSync('userInfo').serverId
                this.getList();
            }
            // this.isEdit = true;
            // this.videoMsg.videoId = options.videoId
            // this.getVideoDetail('30');

			
		},
		methods: {
            aaa(e) {
                // console.log(e)
                if(this.$isEmojiCharacter(e)) {
                    this.isEmoji = true
                } else {
                    this.isEmoji = false
                }
            },
			//上传封面
			touploadCover() {
				if(this.videoMsg.videoDesc.length==0||this.videoMsg.videoCategoryId==''||this.isEmoji) {
					return;
				}

				uni.setStorageSync('uploadVideo',this.videoMsg)
				// console.log(this.videoMsg)
                let edit = this.isEdit?'edit':'add'
                uni.navigateTo({
			        url: `./uploadCover?isEdit=${edit}`
			    })
			},

            async getAliOssInfo(path,fileName) {
                let that = this
                let time = new Date().getTime()
                let resultUrl = ""
                try {
                    if(time > Number(that.expire)) {
                        const res = await that.$u.api.ossInfo()
                        console.log(res)
                        if(res.code==200) {
                            that.fileObj.dir = res.data.dir
                            that.fileObj.host = res.data.host
                            // that.fileObj.host = 'https://fresh-life.oss-cn-shanghai.aliyuncs.com'
                            that.fileObj.policy = res.data.policy
                            that.fileObj.signature = res.data.signature
                            that.fileObj.accessid = res.data.accessid
                            that.expire = res.data.expire * 1000
                            // console.log(that.fileObj,'pppoooo')

                        } else {
                            that.$api.msg('获取上传信息失败')
                        }
                    }
                    uni.showLoading({
                        mask: true,
                        title: "上传中...",
                    });
                    resultUrl = await this.uploadOss(path,fileName);
                    // console.log(resultUrl,'resultUrl=resultUrl=resultUrl')
                    that.uploadVideoSuccess(resultUrl)
                } catch (error) {
                    
                }
                
                
            },

            async uploadOss(filePath,fileName) {
                let that = this
                let claims = uni.getStorageSync("claims");
                let date = new Date()
                let year = date.getFullYear().toString();
                let month = (date.getMonth() + 1).toString();
                let day = (date.getDate()).toString();
                // console.log(that.fileObj,'mmmmmmm')
                // console.log(fileName,'+fileName')
                let [err, result] = await uni.uploadFile({
                    url: that.fileObj.host, //阿里云的存储地址，可以后端返回给你，也可以前端自己写上
                    filePath:filePath, //要上传的临时文件路径
                    name: 'file',
                    header:{
                        Authorization: claims
                    },
                    formData: {
                        key: that.fileObj.dir+'/'+fileName, //文件名
                        // key: that.fileObj.dir+'/'+year+'/'+month+'/'+day+'/'+fileName, //文件名
                        policy: that.fileObj.policy, //后台获取超时时间
                        OSSAccessKeyId: that.fileObj.accessid, //后台获取临时ID
                        success_action_status: '200', //让服务端返回200,不然，默认会返回204
                        signature: that.fileObj.signature //后台获取签名
                    },
                })
                if (err) {
                    //  上传错误了。。。可以做点什么
                    uni.showToast({
                        title: "上传失败",
                        duration: 1500,
                        mask: false,
                        icon: "none",
                    });
                    return ""
                } else {
                    let url = that.fileObj.host+'/'+that.fileObj.dir+'/'+fileName
                    // let url = that.fileObj.host+'/'+that.fileObj.dir+'/'+year+'/'+month+'/'+day+'/'+fileName
                    // console.log(url)
                    return url //上传成功后，将我们所自定义的key（文件路径名）返回出去
                }
            },

            async videoUpload() {
                let that = this;
                if(that.isEdit) {
                    that.uploadVideoShow = true;
                } else {
                    uni.chooseVideo({
                        sourceType: [that.type],
                        compressed: true,
                        success: async res => {
                            if (res.size <= 52428800) {
                                // console.log(res)
                                // console.log(res.tempFile.type)
                                let fileName = ""
                                let date = new Date()
                                let time = date.getTime()
                                
                                // 获取视频类型，拼接时间戳作为文件名称（H5直接获取，app另外获取）
                                // #ifdef H5
                                // console.log("h5");
                                fileName = that.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+res.tempFile.type.substring(res.tempFile.type.lastIndexOf('/')+1) || 'mp4'
                                // #endif

                                // #ifdef APP-PLUS
                                // console.log("App");
                                uni.getVideoInfo({
                                    src: res.tempFile,
                                    success: function (video) {
                                        //    console.log( image.type,'image.typeimage.type')
                                        fileName = that.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+video.type
                                    }
                                });
                                // #endif
                                // console.log(fileName)
                                that.getAliOssInfo(res.tempFilePath,fileName)
                            } else {
                                uni.showToast({
                                    title: "视频最多50MB",
                                    duration: 1500,
                                    mask: false,
                                    icon: "none",
                                });
                            }
                        }
                    });
                }
            },



            uploadVideoSuccess(url) {
                // console.log(url)
                uni.hideLoading();
                if(!this.$isNull(url)) {
                    this.videoMsg.videoUrl = url
                    uni.setStorageSync('uploadVideo',this.videoMsg)
                    uni.hideLoading();
                }
                
            },

            // 编辑走封装的组件上传
            chooseVideoSuccess(obj) {
				// console.log(obj)
				this.videoMsg.videoUrl = obj.url;
                uni.setStorageSync('uploadVideo',this.videoMsg)
                this.$forceUpdate()
			},
			cancelSheetClick() {
				this.uploadVideoShow = false;
			},
            stopTouchmove() {},
			//选择分类
			getList() {
				this.$u.api.serverCategoryList({serverId: this.videoMsg.serverId}).then(res => {
					// console.log(res)
					if(res.code==200) {
                        this.categoryList = res.data;
                        if(!this.$isNull(this.videoMsg.videoCategoryId)) {
                            this.getIndex(this.videoMsg.videoCategoryId);
                        }
                    }
				}).catch(err => {
					console.log(err)
				})
			},
			//确定选择分类
			confirm(e) {
				let msg = e[0]
				this.videoMsg.videoCategoryId = msg.value;
				this.getIndex(msg.value);
			},
			//获取所选分类对应的下标
			getIndex(id) {
				for (let i = 0; i < this.categoryList.length; i++) {
					if(this.categoryList[i].categoryId==id) {
						this.defaultValue[0] = i;
						this.categoryName = this.categoryList[i].categoryName
						return;
					}
				}
			},

            //视频详情
            getVideoDetail(id) {
                this.$u.api.detailVideo(id).then(res => {
					if(res.code==200) {
                        // console.log(res.data)
                        let data = res.data
                        this.videoMsg = Object.assign(this.videoMsg,res.data)
                        this.videoMsg =  {
                            videoDesc: data.videoDesc,
                            videoCategoryId: data.videoCategoryId,
                            serverId: data.serverId,
                            videoUrl: data.videoUrl,
                            videoFaceUrl: data.videoFaceUrl,
                            videoId: data.videoId,
                        },
                        // console.log(this.videoMsg)
                        uni.setStorageSync('uploadVideo',this.videoMsg)
                        this.getList();
                    }
				}).catch(err => {
					console.log(err)
				})
            },
		}
	}
</script>

<style lang='scss' scoped>

._video, .controls {
	width: 670rpx;
	height: 380rpx;
}
.videobox {
	width: 100%;
	height: 100%;
}
.box{
	margin-top:16rpx;
	padding:0 32rpx;
	padding-top:22rpx;
	height:260rpx;
	background:#FFFFFF;
	border-radius:10rpx;
	color: #999;
	font-size: 30rpx;
	/deep/ .u-input__textarea {
		height: 200rpx;
	}
}
.active-select{
	background: rgba(255, 79, 32, 0.13) !important;
	border: 2rpx solid #FF4F20;
	color: #FF4F20 !important;
}
.btn-box {
	// position: fixed;
	// bottom: 90rpx;
	// left: 0;
    margin-top: 180rpx;
	width: 100%;
    .btn {
        width: 608rpx;
		height: 88rpx;
		background: #e0e0e0;
		border-radius: 44rpx;
		opacity: 1;
		text-align: center;
		line-height: 88rpx;
		color: #fff;
		font-size: 34rpx;
    }
	.comitBtn {
		background: linear-gradient(160deg, #FF6E47 0%, #FF4E1F 100%);
		box-shadow: 0px 16rpx 32rpx 2rpx rgba(255,78,31,0.27);
	}
}

</style>
