<template>
	<view class="content">
		<view class="firstNav flex align-center justify-between">
			<image src='../../static/back-icon.png' class="back-img" @tap="BackPage()"></image>
			<view class="text">{{classifyTitle}}</view>
			<image src='../../static/classify-icon.png' class="classify-img" @tap="toClassify()"></image>
		</view>

		<view class="videoList">
			<view class="video-box" v-if="!nothing">
				<!-- <swiper class="swiper" :autoplay="false" :vertical="true" :current="currentIndex"
					@change="change" @animationfinish="animationfinish" @touchstart="touchStart" @touchend="touchEnd">
					<swiper-item v-for="(item,index) of list" :key="item.id">
						<view class="swiper-item">
							<videoPlayer ref="player" :video="item" :index="index" :first="firstInit"></videoPlayer>
						</view>
					</swiper-item>
				</swiper> :poster="video.videoFaceUrl" -->

            
                <view v-for="(video) in list" :key="video.videoId" class="video-item" style="position: relative;">
                    
                    <view class="title font-30 font-weight4">{{video.videoDesc}}</view>
                    <video class="videoitem" :class="video.vertical?'videobox-vertical':'videobox'" :id="'myVideo'+video.videoId" :show-center-play-btn="false" :controls="(video.isPlay||video.fullScreen)"
		                :src="video.videoUrl" :poster="video.videoFaceUrl" @play="playing" @ended="playEnding($event,video)" @fullscreenchange="fullscreenchange($event,video)" @loadedmetadata="loadedmetadata($event,video)">

			            <cover-image class="play-img" src="../../static/video-black.png" v-if="!video.isPlay" @tap.stop="playClick('myVideo'+video.videoId)"></cover-image>
			            <!-- <cover-image class="poster-img" :src="video.videoUrl+'?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto'" v-if="!video.isPlay&&!video.fullScreen" @tap.stop="playClick('myVideo'+video.videoId)"></cover-image> -->
			            <cover-image class="poster-img" :src="video.videoFaceUrl" v-if="!video.isPlay&&!video.fullScreen" @tap.stop="playClick('myVideo'+video.videoId)"></cover-image>


                        <cover-view class="play-box flex align-center justify-end" v-if="!video.isPlay&&!video.fullScreen">
                            <cover-view class="flex align-center text-sm">
                                <!-- <cover-view class="view-box flex align-center" style="margin-right:10rpx;">
                                    <cover-image class="view-img" src="../../static/video/view.png"></cover-image>
                                    <cover-view>99</cover-view>
                                </cover-view> -->
                                <cover-view class="view-box">
                                    <cover-view>{{video.duration}}</cover-view>
                                </cover-view>
                            </cover-view>
                        </cover-view>

		            </video>

                    <cover-image class="view-list-bg" src="../../static/video/list-bg.png" v-if="!video.isPlay&&!video.fullScreen"></cover-image>
                    <cover-view class="author flex align-center font-26" @tap="toInfo(video.merchantId)" v-if="!video.isPlay&&!video.fullScreen">
                        <cover-image :src='video.merchantAvatar' class="header-img" v-if="!$isNull(video.merchantAvatar)"></cover-image>
                        <cover-image class="header-img" src="../../static/defalut_header.png" v-else></cover-image>
                    </cover-view>
                    <cover-view class="view-merchantName" v-if="!video.isPlay&&!video.fullScreen">{{video.merchantName}}</cover-view>

                </view>
			</view>
			<view v-if="nothing" class="swiper swiper-empty flex align-center flex-direction">
				<image src='../../static/video-empty.png' class="empty-img"></image>
				<view>暂无视频</view>
			</view>
		</view>


        <u-popup v-model="show" mode="top" border-radius="14" z-index="9997">
			<view class="main-box flex flex-wrap">
                <view v-for="item in categoryList" :key="item.categoryId" class="item" :class="parentId==item.categoryId?'active-item':''" @tap="choose(item.categoryId,item.categoryName)">
                    {{item.categoryName}}
                </view>
            </view>
		</u-popup>

	</view>
</template>

<script>
	import videoPlayer from '../../components/videoPlayer/videoPlayer.vue'
	var time = null
	export default {
		components:{
			videoPlayer
		},
		data() {
			return {
				list:[],
				videoId: "",
				indexVideo: false, //从某一视频跳转过来
				// pageStartY: 0,
				// pageEndY: 0,
                // currentIndex: 0,
                // firstInit: false, //首次加载显示上滑查看视频

				page:0,
				parentId: "", //分类id
				pageNum: 1,
				noMore: false,
				nothing: false,
				type: "index",
				serverId: "", //服务人员id
				merchantId: "", //商家id
                oldScrollTop: 0,
                changeScroll: true,
                fullScrollTop: 0,
                outFullScreen: false,
                show: false,
                categoryList: [
					{
						categoryId: "",
						categoryName: "全部"
					}
				],
                classifyTitle: "视频列表"
				
			}
		},
		onShow() {
			
		},
		onLoad(options) {
			
			if(!this.$isNull(options.videoId)) {
				this.videoId = options.videoId
				this.indexVideo = true
			} else {
				this.indexVideo = false
			}
			this.type = options.type
			this.serverId = options.serverId || ""
			this.merchantId = options.merchantId || ""
			this.parentId = options.parentId || ""

			let first = uni.getStorageSync("firstInit")
			this.firstInit = this.$isNull(first)
			// console.log(this.firstInit,'ooooo')
			this.init();
            this.getCaregoryList();

			// uni.$on('changeVideoClassify',parentId=>{
			// 	this.currentIndex = 0;
			// 	this.noMore = false
			// 	this.nothing = false
			// 	this.pageNum = 1
			// 	this.list = []
            //     this.parentId=parentId;
			// 	this.init();
            // })

		},
        onPageScroll(e) {
            let that = this
            // console.log("滚动距离为：" + e.scrollTop);

            if(this.changeScroll) {
                this.fullScrollTop = e.scrollTop
                if(Math.abs(e.scrollTop - this.oldScrollTop) >=100) {
                    this.oldScrollTop = e.scrollTop
                    let trailer = this.list;
                    
                    trailer.forEach(function(item, index) {	// 获取json对象并遍历, 停止视频
                        let temp = 'myVideo'+item.videoId;
                        if (!item.fullScreen&&item.isPlay) {
                            uni.createVideoContext(temp).pause(); //暂停视频播放事件
                            item.isPlay = false
                            item.fullScreen = false
                        }
                    })
                } 
            } else {
                if(that.outFullScreen) {
                    // 退出全屏时，恢复进入全屏前的页面位置，并恢复监听 changeScroll = true
                    that.changeScroll = true
                }
            }
        },
        onReachBottom() {
            this.init();
        },
		methods: {
			init() {
                
				if(this.type=="index") {
					this.getVideos()
				} else if(this.type=='server') {
					this.getServerVideo();
				} else if(this.type=='merchant') {
					this.getMerchantVideo();
				}
			},
			//全部视频列表
			getVideos(){
				let that = this
				if(that.noMore) return
				let params = {
					pageSize: 10,
					pageNum: that.pageNum,
					parentId: that.parentId,
					bizType: that.$bizType
				}
				this.$u.api.allVideoList(params).then(res => {
					if (res.code == 200) {
						// console.log(res)
						//从首页跳转过来，需要将跳转过来的视频排在第一位
                        res.rows.map(item=>{
                            item.isPlay = false;
                            item.fullScreen = false;
                            item.duration = "00:00";
                            item.vertical = false;
                        })
						let arr = JSON.parse(JSON.stringify(res.rows))
						let first = []
						if(that.indexVideo) {
							that.indexVideo = false
							for (let index = 0; index < arr.length; index++) {
								if(arr[index].videoId==this.videoId) {
									first.push(arr[index])
									arr.splice(index,1)
								}
							}
							that.list = first.concat(arr)
						} else {
							that.list = that.list.concat(arr)
						}
						// console.log(that.list)
                        for (let index = 0; index < that.list.length; index++) {
                            uni.getVideoInfo({
                                src: that.list[index].videoUrl,
                                success: function (video) {
                                    // console.log( video,'image.typeimage.type')
                                    if(video.height>video.width) {
                                        that.list[index].vertical = true
                                    } else {
                                        that.list[index].vertical = false
                                    }
                                    
                                }
                            });
                        }
						if(res.rows.length<10) {
							that.noMore = true
							if(that.pageNum==1&&that.list.length==0) {
								that.nothing = true
							} else {
								that.nothing = false
							}
						} else {
							that.noMore = false
							that.pageNum += 1
						}
					}
				}).catch(error => {
					console.log(error)
				})
			},
			
			//服务人员视频列表
			getServerVideo(){
				let that = this
				if(that.noMore) return
				let params = {
					pageSize: 10,
					pageNum: that.pageNum,
					serverId: that.serverId,
					parentId: that.parentId,
					bizType: that.$bizType
				}
				this.$u.api.serverVideoList(params).then(res => {
					if (res.code == 200) {
						// console.log(res)
						//从首页跳转过来，需要将跳转过来的视频排在第一位
                        res.rows.map(item=>{
                            item.isPlay = false;
                            item.fullScreen = false;
                            item.duration = "00:00";
                            item.vertical = false;
                        })
						let arr = JSON.parse(JSON.stringify(res.rows))
						let first = []
						if(that.indexVideo) {
							that.indexVideo = false
							for (let index = 0; index < arr.length; index++) {
								if(arr[index].videoId==this.videoId) {
									first.push(arr[index])
									arr.splice(index,1)
								}
							}
							that.list = first.concat(arr)
						} else {
							that.list = that.list.concat(arr)
						}
                        // console.log(that.list)
                        for (let index = 0; index < that.list.length; index++) {
                            uni.getVideoInfo({
                                src: that.list[index].videoUrl,
                                success: function (video) {
                                    // console.log( video,'image.typeimage.type')
                                    if(video.height>video.width) {
                                        that.list[index].vertical = true
                                    } else {
                                        that.list[index].vertical = false
                                    }
                                    
                                }
                            });
                        }
						// console.log(that.list)
						if(res.rows.length<10) {
							that.noMore = true
							if(that.pageNum==1&&that.list.length==0) {
								that.nothing = true
							} else {
								that.nothing = false
							}
						} else {
							that.noMore = false
							that.pageNum += 1
						}
					}
					
				}).catch(error => {
					console.log(error)
				})
			},

			//商家视频列表 
			getMerchantVideo() {
				let that = this
				if(that.noMore) return
				let params = {
					pageSize: 10,
					pageNum: that.pageNum,
					merchantId: that.merchantId,
					parentId: that.parentId,
					bizType: that.$bizType
				}
				this.$u.api.merchantVideoList(params).then(res => {
					if (res.code == 200) {
						// console.log(res)
						//从首页跳转过来，需要将跳转过来的视频排在第一位
                        res.rows.map(item=>{
                            item.isPlay = false;
                            item.fullScreen = false;
                            item.duration = "00:00";
                            item.vertical = false;
                        })
						let arr = JSON.parse(JSON.stringify(res.rows))
						let first = []
						if(that.indexVideo) {
							that.indexVideo = false
							for (let index = 0; index < arr.length; index++) {
								if(arr[index].videoId==this.videoId) {
									first.push(arr[index])
									arr.splice(index,1)
								}
							}
							that.list = first.concat(arr)
						} else {
							that.list = that.list.concat(arr)
						}
                        // console.log(that.list)
                        for (let index = 0; index < that.list.length; index++) {
                            uni.getVideoInfo({
                                src: that.list[index].videoUrl,
                                success: function (video) {
                                    // console.log( video,'image.typeimage.type')
                                    if(video.height>video.width) {
                                        that.list[index].vertical = true
                                    } else {
                                        that.list[index].vertical = false
                                    }
                                    
                                }
                            });
                        }
						// console.log(that.list)
						if(res.rows.length<10) {
							that.noMore = true
							if(that.pageNum==1&&that.list.length==0) {
								that.nothing = true
							} else {
								that.nothing = false
							}
						} else {
							that.noMore = false
							that.pageNum += 1
						}
					}
				}).catch(error => {
					console.log(error)
				})
			},

            //分类列表
            getCaregoryList() {
                let that = this;
				this.$u.api.categoriesList({
					bizType: this.$bizType
				}).then(res => {
					// console.log(res)
					if (res.code == 200) {
                        that.categoryList =that.categoryList.concat(res.data);
                        if(that.parentId!='') {
                            that.categoryList.map(item=>{
                                if(item.categoryId==that.parentId) {
                                    that.classifyTitle = item.categoryName
                                }
                            })
                        }
					}
				}).catch(error => {
					console.log(error)
				})
			},
            //选择分类
			choose(id,title) {
                if(id=='') {
                    this.classifyTitle = "视频列表"
                } else {
                    this.classifyTitle = title
                }
                
				this.parentId = id
                this.currentIndex = 0;
				this.noMore = false
				this.nothing = false
				this.pageNum = 1
				this.list = []
				this.init();
				this.show = false
			},

            fullscreenchange(e,item) {
                // 进入退出全屏时停止监听滚动 changeScroll = false
                // console.log(e)
                this.changeScroll = false;
                if(e.detail.fullScreen) {
                    this.outFullScreen = false;
                } else if(!e.detail.fullScreen) {
                    // 退出全屏时，恢复进入全屏前的页面位置，并恢复监听 changeScroll = true
                    this.outFullScreen = true;
                    uni.pageScrollTo({
                        scrollTop: this.fullScrollTop,
                        duration: 0
                    })
                }
                item.fullScreen = e.detail.fullScreen

            },
            loadedmetadata(e,item) {
                // console.log(e)
                // console.log(item)
                

                let secondTime = parseInt(e.detail.duration);// 秒
                // let secondTime = parseInt(3661);// 秒
                let minuteTime = 0;// 分
                let hourTime = 0;// 小时
                if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
                    //获取分钟，除以60取整数，得到整数分钟
                    minuteTime = parseInt(secondTime / 60);
                    //获取秒数，秒数取佘，得到整数秒数
                    secondTime = parseInt(secondTime % 60);
                    //如果分钟大于60，将分钟转换成小时
                    if(minuteTime > 60) {
                        //获取小时，获取分钟除以60，得到整数小时
                        hourTime = parseInt(minuteTime / 60);
                        //获取小时后取佘的分，获取分钟除以60取佘的分
                        minuteTime = parseInt(minuteTime % 60);
                    }
                }
            
                let result = "";
                let h = "00"
                let m = "00"
                let s = "00"
                
                s = parseInt(secondTime)<10?'0'+secondTime:secondTime;
                m = parseInt(minuteTime)<10?'0'+minuteTime:minuteTime
                h = parseInt(hourTime)<10?'0'+hourTime:hourTime

                if(secondTime > 0) {
                    result = m+':'+s
                }

                if(minuteTime > 0) {
                    result = m+':'+s
                }
                if(hourTime > 0) {
                    result = h+':'+m+':'+s
                }

                item.duration = result

                // console.log('result',result);


            },
            playing(e) {
                // console.log(e)
                let currentId = e.currentTarget.id;// 获取当前视频id
                // console.log("currentId", currentId);
                let trailer = this.list;
                trailer.forEach(function(item, index) {	// 获取json对象并遍历, 停止非当前视频
                    if (item.videoUrl != null && item.videoUrl != "") {
                        let temp = 'myVideo'+item.videoId;
                        if (temp != currentId) {
                            // console.log(temp);
                            uni.createVideoContext(temp).pause(); //暂停视频播放事件
                            item.isPlay= false
                        } else {
                            item.isPlay= true
                        }
                    }
                })
            },
            playEnding(e,item) {
                item.isPlay= false
            },


            playClick(idName) {
                // this.videoContent = uni.createVideoContext(idName);
                uni.createVideoContext(idName).seek(0)
                uni.createVideoContext(idName).play();
            },


            toInfo(merchantId) {
                let obj = {
                    merchantId: merchantId,
                    bizType: this.$bizType
                }
                uni.setStorageSync('indexDetails', obj)
                uni.navigateTo({
                    url: '../index/shopDetails'
                })
            },
		
		
			// pauseVideo(){
			// 	if(this.play === true){
			// 		// console.log('pause')
			// 		this.videoContext.pause()
			// 		this.play = false
			// 	}
			// },
		
			// change(res) {
			// 	// console.log(res,'ppppp')
			// 	clearTimeout(time)
			// 	this.page = res.detail.current
			// 	this.currentIndex = res.detail.current
			// 	time = setTimeout(() => {
					
			// 		if (this.pageStartY > this.pageEndY) {
			// 			// console.log("向上滑动"+this.page);
			// 			if(this.$refs.player[this.page-1]) {
			// 				this.$refs.player[this.page-1].pauseVideo()
			// 			}
			// 			if(this.$refs.player[this.page]) {
			// 				this.$refs.player[this.page].playVideo()
			// 			}

			// 			this.pageStartY = 0
			// 			this.pageEndY = 0
			// 			if(this.firstInit) {
			// 				uni.setStorageSync("firstInit","again")
			// 				this.firstInit = false
			// 			}
			// 		} else {
			// 			// console.log("向下滑动"+this.page);
			// 			if(this.$refs.player[this.page+1]) {
			// 				this.$refs.player[this.page+1].pauseVideo()
			// 			}
			// 			if(this.$refs.player[this.page]) {
			// 				this.$refs.player[this.page].playVideo()
			// 			}
						
			// 			this.pageStartY = 0
			// 			this.pageEndY = 0
			// 			if(this.firstInit) {
			// 				uni.setStorageSync("firstInit","again")
			// 				this.firstInit = false
			// 			}
			// 		}

			// 	},1)
			// },
			// animationfinish(res) {
			// 	let current = res.detail.current;
			// 	if(current === this.list.length-1) {
			// 		// console.log('数据数据')
			// 		this.init()
			// 	}
			// },
			// touchStart(res) {
			// 	this.pageStartY = res.changedTouches[0].pageY;
			// 	// console.log(this.pageStartY);
			// },
			// touchEnd(res) {
			// 	this.pageEndY = res.changedTouches[0].pageY;
			// 	// console.log(this.pageEndY);
			// },
			BackPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			toClassify() {
                this.show = !this.show
				// uni.navigateTo({
				// 	url: `/pages/video/videoClassify?categoryId=${this.parentId}`
				// })
			}
		},
		
	}
</script>

<style>
    page {
		background: #fff;
	}
</style>
<style lang="less" scoped>

	
	.content{
		width: 100%;
		height: 100vh;
		padding-top: 100rpx;
		// color: #fff;
	}
	
	.firstNav{
		width: 100%;
		height: 100rpx;
		position: fixed;
		top: 0px;
		left: 0;
		z-index: 20;
		background: #fff;
		margin: 0 auto;
		padding: 0 26rpx;
		z-index: 9999;
		font-size: 35rpx;
	}


	.back-img {
		width: 22rpx;
		height: 40rpx;
	}
	.classify-img {
		width: 46rpx;
		height: 40rpx;
	}
	
	.videoList {
		width: 100%;
		/* height: 100%; */
		height: calc(100vh - 100rpx);
	}

	.video-box {
		width: 100%;
		height: 100%;
	}

	.swiper {
		width: 100%;
		height: 100%;
	}

	.swiper-item {
		width: 100%;
		height: 100%;
		z-index: 19;
	}
	.swiper-empty {
		background: #f6f6f6;
		font-size: 22rpx;
		color: #999;
	}
	.empty-img {
		width: 566rpx;
		height: 290rpx;
		margin-bottom: 42rpx;
		margin-top: 272rpx;
        margin-left: 52rpx;
	}
	
    .videobox {
		width: 100%;
		height: 422rpx;
	}
    .videobox-vertical {
        width: 100%;
		height: 750rpx;
    }
    .video-item {
        border-bottom: 2rpx solid #F2F2F2;
    }
    .video-item:last-of-type{
        border: none;
    }
    .poster-img {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 20;
        width: 100%;
		// height: 422rpx;
        height: 100%;
        /deep/ .uni-cover-image {
           img {
                object-fit: cover;
                // object-fit: contain;
            } 
        }
    }
    .videoitem {
        position: relative;
        // width: 100%;
        // height: 100%;
        margin-bottom: 70rpx;
    }
    .title{
        width: calc(100% - 60rpx);
        padding: 20rpx 30rpx;
        // margin-top: 30rpx;
        line-height: 38rpx;
        word-break: break-all;
        word-wrap: break-word;
        white-space: pre-wrap;
        // color: #fff;
        // position: absolute;
        // left: 0;
        // top: 0;
        z-index: 20;
    }
    .play-box {
        z-index: 20;
        width: calc(100% - 166rpx);
        padding: 0rpx 30rpx 0rpx 136rpx;
        position: absolute;
        left: 0;
        bottom: 10rpx;
        color: #fff;
        .view-box {
            background: rgba(0, 0, 0, 0.3);
            padding: 4rpx 18rpx;
            border-radius: 8rpx;
        }
        .view-img {
            width: 24rpx;
            height: 17rpx;
            margin-right: 10rpx;
        }
        
    }

    .author {
        text-shadow: 0px 2px 0px rgba(17, 17, 17, 0.52);
    }
    .header-img {
        width: 90rpx;
        height: 90rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        position: absolute;
        left: 32rpx;
        bottom: 25rpx;
        z-index: 21;
    }

 
	.play-img {
		z-index: 22;
		position: absolute;
		width: 80rpx;
		height: 80rpx;
		top: calc(50% - 40rpx);
		left: calc(50% - 40rpx);
	}
    
    .view-list-bg {
        position: absolute;
        bottom: 0rpx;
        left: 0;
        width: 750rpx;
        height: 120rpx;
        z-index: 20;
    }
    .view-merchantName {
        position: absolute;
        left: 136rpx;
        bottom: 30rpx;
        z-index: 21;
        font-size: 26rpx;
        color: #1A1A1A;
    }


    .main-box {
        border-top: 2rpx solid #eee;
        padding: 110rpx 0rpx 0 26rpx;
    }
    .item {
        width: 152rpx;
        text-align: center;
        height: 52rpx;
        line-height: 52rpx;
        background: rgba(241, 241, 241, 0.6);
        border-radius: 26rpx;
        font-size: 26rpx;
        margin-bottom: 30rpx;
        color: #313131;
        margin-right: 26rpx;
    }
    .active-item {
        background: linear-gradient(90deg, #ED653F 0%, #F19A91 100%);
        opacity: 1;
        color: #fff;
    }
	
</style>
