<template>
	<view style="padding-top:120rpx;">
		<view style="width:90%;margin:10px auto; padding-top:15px;height:160px;background:#FFFFFF;border-radius:10px;border: 1px dashed #FFDBD2;" @tap="videoUpload('camera')">
			<view class="_video">
				<view style="margin-bottom: 7px;">
				  <img style="margin-top:5px;width: 30px;padding-left: 155px;padding-top:30px ;" src="../../static/main/shangchuanshipin.png"/>
				</view>
				<view>
				  <text style="color:#111111;font-size: 19px;font-weight:bold;padding-left: 124px;">拍摄新视频</text>
				</view>
			</view>
		</view>
		<view style="width:90%;margin:10px auto;padding-top:15px;height:160px;background:#FFFFFF;border-radius:10px;border: 1px dashed #FFDBD2;" @tap="videoUpload('album')">
			<view class="_video">
				<view style="margin-bottom: 7px;">
				  <img style="margin-top:5px;width: 30px;padding-left: 155px;padding-top:30px ;" src="../../static/main/shangchuanshipin.png"/>
				</view>
				<view>
				  <text style="color:#111111;font-size: 19px;font-weight:bold;padding-left: 130px;">本地视频</text>
				</view>
			</view>
		</view>
        <view style="" class="font-30 color-99 text-center">建议比例16:9，画面清晰，最大上传50M</view>
		<view class="btn-box flex justify-center" @click="tovideoList()">
		    <view class="btn">查看视频列表</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				uploadType: "",
                isBack: false,
                fileObj: {},
                expire: 0,
			}
		},
		onShow() {
			try {
				uni.removeStorageSync('uploadVideo');
			} catch (e) {}
            // this.getAliOssInfo()
		},
        onLoad(options) {
            if(!this.$isNull(options.isBack)) {
                this.isBack = true
            } else {
                this.isBack = false
            }
        },
        beforeDestroy() {
            if(this.isBack) {
                uni.reLaunch({
                    url: '/pages/index/index'
                });
            }
        },
		methods: {
                
            async getAliOssInfo(path,fileName,type) {
                // console.log(fileName,'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");
                // 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, //文件名
                        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
                    // console.log(url)
                    return url //上传成功后，将我们所自定义的key（文件路径名）返回出去
                }
            },



            async videoUpload(type) {
                let that = this;
                that.uploadType = type
                uni.chooseVideo({
                    sourceType: [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)) {
                    let obj = {
                        videoFaceUrl: "",
                        videoUrl: url
                    }
                    uni.setStorageSync('uploadVideo',obj)
                    
                    uni.navigateTo({
                        url: `./uploadVideo?type=${this.uploadType}`
                    })
                }
                
            },

			//视频列表
			tovideoList() {
			    uni.navigateTo({
			        url: './videoList'
			    })
			},
		}
	}
</script>

<style lang='scss' scoped>

.btn-box {
	// position: fixed;
	// bottom: 300rpx;
	// left: calc(50% - 300rpx);
    margin-top: 43rpx;
    // padding-bottom: 40rpx;
    .btn {
        width: 600rpx;
        height: 90rpx;
        color: #FFFFFF;
        line-height: 90rpx;
        text-align: center;
        font-size: 32rpx;
        background:linear-gradient(160deg, #FF6E47 0%, #FF4E1F 100%);
        border-radius: 46rpx;

    }
}

</style>
