<template>
	<view :style="'padding-top:'+nvaHeight+'px;'">
		<view class="videotop" :style="'background-color:'+backgroundColor+';'">
			<cover-view class="navbox" :style="'background-color:'+backgroundColor+';'">
				<!-- leftWidth="200rpx" -->
				<uni-nav-bar  color="#ffffff"  title="实时监控"  :background-color="backgroundColor" :border="false" statusBar='true' fixed="true">
					<!-- <block slot="left">
						<picker range-key='name' :value="adridx" :range="adrlist"    @change='bindDateChangea'>
							<view class="chekt">
								<view class="over">{{address|| ""}}</view>
								<image :src="upimg"></image>
							</view>
						</picker>
					</block> -->
					<cover-view class="jktit" slot="default">实时监控</cover-view>
				</uni-nav-bar>
				<cover-view class="tablist flexc" v-if="tabval==1">
						<cover-view class="tabs" v-for="(ite,idx) in tablist">
							<cover-view class="tabtit" @click.stop="getTabFn(ite.val)" :class="tabval==ite.val?'act':''">{{ite.tit}}</cover-view>
							<cover-view class="tabline" v-if="tabval==ite.val"></cover-view>
						</cover-view>
				</cover-view>
			</cover-view>
			<view class="flexc" v-if="tabval==2">
				<view class="tablist flexc">
					<view class="tabs" v-for="(ite,idx) in tablist">
						<view class="tabtit" @click.stop="getTabFn(ite.val)" :class="tabval==ite.val?'act':''">{{ite.tit}}</view>
						<view class="tabline" v-if="tabval==ite.val"></view>
					</view>
				</view>
				<!-- 道闸 -->
				<view class="chekts" >
					<picker range-key='name' :value="adridx" :range="adrlist"  @change='bindDateChangea'>
						<view class="chekt">
							<view class="over chektit">{{address|| ""}}</view>
							<image :src="upimg" class="chektimg"></image>
						</view>
					</picker>
				</view>
			</view>
		</view>
		<image :src="navbg" class="navbg"></image>
		<view class="zxmain">
			<view class="vidbox mb16">
				<!-- #ifdef APP-PLUS -->
				<video :src="videourl" id="myvideo" autoplay controls></video>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view id="myPlayer" style="width: 100%;" ref="myPlayer"></view>
				<!-- #endif -->
				<!-- 监控 -->
				<view class="control" v-if="tabval==1">
					<view class="contop flexcc">
						<image :src="videoimg"></image>
						<view>监控切换</view>
					</view>
					<view class="flex1 overa conbox">
						<view class="contit over" :class="dzCode==ite.indexCode?'act':''" v-for="(ite,idx) in access" :key="ite.indexCode" @click="getCodeFn(ite)">
						{{ite.name}}
						<image :src="videobg" v-if="dzCode==ite.indexCode" class="videobg"></image>
						</view>
					</view>
					
				</view>
			</view>
			<block v-if="tabval==1">
				<view class="openbox flexcj">
					<view class="btns bga" @click="getOpenFn" v-if="checkPermi(['system:camera:openDz'])">
						<image :src="openimg"></image>
						开门
					</view>
					<view class="btns bgb" @click="getCloseFn" v-if="checkPermi(['system:camera:closeDz'])">
						<image :src="openimg"></image>
						关门
					</view>
				</view>
				<!-- 列表 -->
				<block v-if="checkPermi(['system:door:list'])">
					<view class="vlisttop flexcj">
						<view class="vlleft flexc" @click="getResetFn">
							<image :src="mjimg"></image>门禁记录
						</view>
						<picker mode="date" @change='bindDateChangeb'>
							<view class="rlleft flexc">
								<view>{{daytime||"请选择日期"}}</view>
								<image :src="hupimg"></image>
							</view>
						</picker>
					</view>
					<!-- 表格 -->
					<view class="table" :style="tabflag?'height:calc(100vh - '+tabscheight+'rpx)':''">
						<zb-table
						  :show-header="true"
						  :columns="column1"
						  :stripe="true"
						  :fit="true"
						  :isShowLoadMore="reachflag"
						  :parameter="parameter"
						  :data="list"></zb-table>
						  <!-- @rowClick="rowClick"
						  @toggleRowSelection="toggleRowSelection"
						  @toggleAllSelection="toggleAllSelection"   -->
					</view>
				</block>
				
			</block>
			<view v-if="tabval==2" class="pt5">
				<view class="browntop flexc">
					<image :src="video"></image>
					<view>最近浏览</view>
				</view>
				<view class="flexc" v-if="browselist&&browselist.length">
					<view class="brlists flexccc" v-for="(ite,idx) in browselist" :key="idx" @click="getChangellFn(ite,idx)">
						<image :src="browse"></image>
						<view class="over">{{ite.name}}</view>
					</view>
				</view>
				<block v-else>
					<no-data></no-data>
				</block>
			</view>
			
		</view>
		
		<!-- 第一道；手机号，发送验证码，门就开，记录车牌号，直接进
		第二种：需要审核，预约
		办公人员，配置进门区域，
		访客配置 进门区域 -->
		
	<footers v-if="isfootflag" :footerindex="footerindex"></footers>
  </view>
</template>

<script>
	import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
	import self from '@/utils/location.js';
	import yList from "@/components/order/list.vue"
	let { calendar } = require("@/components/lunc-calendar/calendar.js");
	import {getCameraList,getCameraVideo,getVideoOpenDz,getVideoCloseDz,getDoorList} from "@/api/mine/order.js"
	import {column1} from '@/components/zb-table/all.js'
	import {getDictionaryFn} from "@/api/mine/register.js"
	import footers from '@/components/footer/footer.vue'
	import zbTable from "@/components/zb-table/zb-tables.vue"
	import noData from "@/components/nodata/nodata.vue"
	// #ifdef H5
	import flvjs from 'flv.js';
	// #endif
	
  export default {
	components:{yList,footers,zbTable,noData},
	data(){
		return{
			column1,
			footerindex:'video',
			isfootflag:true,
			navbg:require("@/static/images/vibg.png"),
			upimg:require("@/static/images/order/up.png"),
			hupimg:require("@/static/images/order/hup.png"),
			mjimg:require("@/static/images/order/control.png"),
			bigimg:require("@/static/images/order/pre.png"),
			voiceimg:require("@/static/images/order/voice.png"),
			openimg:require("@/static/images/order/open.png"),
			closeimg:require("@/static/images/order/close.png"),
			resetimg:require('@/static/images/order/reset.png'),
			wresetimg:require('@/static/images/order/wreset.png'),
			videoimg:require('@/static/images/order/video.png'),
			videobg:require('@/static/images/order/videobg.png'),
			video:require('@/static/images//video.png'),
			browse:require('@/static/images/browse.png'),
			noiconpimg:require("@/static/images/noiconp.png"),
			backgroundColor: "transparent",
			tabval:1,
			tablist:[{tit:'道闸',val:1},{tit:'监控',val:2}],
			list:[],
			pageSize: 15,
			pageNum: 1,
			reachflag: false,
			wtdt:'',
			parameter:{
				kgmlist:[],
			},
			adridx:0,
			address:'',
			access:[],//道闸
			adrlist:[],//
			browselist:[],
			indexCode:'',
			dzaddress:'',
			dzCode:"",
			fixedflag:false,
			videourl:'',
			nvaHeight:44,
			marTop:0,//距离顶部的距离
			stubarHeight:0,//
			tabtop:0,//表格距离顶部的距离
			daytime:'',//时间
			tabflag:false,
			tabscheight:0,//减去的部分
			autoplay:true,
			controls:true,
			enableProgressGesture: false,
            showPlayBtn: false,
            showCenterPlayBtn: false,
            showFullscreenBtn: false,
            windowWidth: '',
            windowHeight: '',
            flvPlayer: null,
            player: null,
			isloading:false,
		}
	},
	onPageScroll(e) {
		var scrollTop = Number(e.scrollTop);
		if (scrollTop > 0) {
			this.backgroundColor = '#0491FD'
		} else {
			this.backgroundColor = 'transparent'
		}
		if(scrollTop<this.tabtop){
			this.tabflag=false;
		}else{
			this.tabflag=true;
		}
	},
	onLoad: function() {
		// uni.$on('refreshdatalist',(e) => {
		// 	this.reachflag=false;
		// 	this.pageNum=1;
		// 	this.list=[];
		// 	 this.getDataFn();
		// })
		this.time()
		if(checkPermi(['system:camera:list'])){
			this.getCameraList()
		}
		this.init()
		// this.getDataFn()
		uni.getSystemInfo({
			success: (e) => {
				this.stubarHeight=Number(e.statusBarHeight);
				this.nvaHeight = Number(e.statusBarHeight)+44;
				this.tabscheight=Number(this.nvaHeight)*2+100+84;
			}
		})
		// 获取储存的浏览记录
		if(uni.getStorageSync('browse')){
			this.browselist=JSON.parse(JSON.stringify(uni.getStorageSync('browse')))
		}
	},
	onUnload() {
		uni.setStorageSync('browse', JSON.parse(JSON.stringify(this.browselist)))
		uni.$off('refreshdatalist')
		// #ifdef H5
		this.flv_destroy();
		// #endif
		
	},
	onShow() {
	},
	// 上拉触底加载更多触发事件
	onReachBottom() {
		if (this.reachflag) {
			this.pageNum++
			this.getDataFn()
		}
	},
	methods:{
		checkPermi, checkRole,
		getTabFn(val){
			var tabval=this.tabval;
			this.tabval=val;
			// 浏览记录
			var newArr=JSON.parse(JSON.stringify(this.browselist))
			if(val==2){
				// 默认看第浏览记录第一个
				if(newArr&&newArr.length){
					var obj=newArr[0];
					this.adridx=obj.adridx;
					this.address=obj.name;
					this.indexCode=obj.indexCode;
					// 获取直播视频
					this.getCameraVideo()
				}else{
					var adrList=JSON.parse(JSON.stringify(this.adrlist))
					if(adrList&&adrList.length){
						var obj=adrList[0];
						this.adridx=obj.adridx;
						this.address=obj.name;
						this.indexCode=obj.indexCode;
						// 获取直播视频
						this.getCameraVideo()
					}
				}
			}else if(val==1&&tabval==2){
				if(newArr.length<1){
					var obj={
						name:this.address,
						indexCode:this.indexCode,
						adridx:this.adridx,
					}
					this.browselist.unshift(obj)
				}
				// 获取直播视频
				this.getCameraVideo()
			}
		},
		getOpenFn(){
			var that=this
			if(this.isloading){
				return
			}
			this.isloading=true;
			var params={
				equipmentName:this.dzaddress
			}
			getVideoOpenDz(params).then(res=>{
				this.isloading=false
				if(res.code==200){
					this.$toast(res.msg)
				}
				this.getrefreshData()
			}).catch(error=>{
				this.isloading=false
			})
		},
		getCloseFn(){
			var that=this
			if(this.isloading){
				return
			}
			this.isloading=true;
			var params={
				equipmentName:this.dzaddress
			}
			getVideoCloseDz(params).then(res=>{
				this.isloading=false
				if(res.code==200){
					this.$toast(res.msg)
				}
				this.getrefreshData()
			}).catch(error=>{
				this.isloading=false
			})
		},
		time() {
			var date = new Date();
			var y = date.getFullYear();
			var m = date.getMonth() + 1;
			var d = date.getDate();
			// var h = date.getHours();
			// var min = date.getMinutes();
			// var s = date.getSeconds();
			// var week = date.getDay(); //获取当前星期X(0-6,0代表星期天)
			// var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
			this.daytime = y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d)
			// var timeStr = (h < 10 ? ('0' + h) : h) + ':' + (min < 10 ? ('0' + min) : min) + ':' + (s < 10 ? (
			// 	'0' + s) : s);
			if(checkPermi(['system:door:list'])){
				this.getDataFn()
			}
		},
		getLivePlayer() {
		    uni.showLoading({
		        mask: true,
		        title: 'loading...'
		    });
			if(this.flvPlayer){
				this.flvPlayer.flv_destroy();
			}
		    // 生成需要的video 组件
		    // var player = document.getElementById('videoElement');
		    var player = document.createElement('video');
		    player.id = 'video';
		    player.style = 'width: 100%;height: 211px';
		    player.enableProgressGesture = this.enableProgressGesture;
		    player.controls = this.controls;
		    player.muted = true;
		    player.showCenterPlayBtn = this.showCenterPlayBtn;
		    player.showPlayBtn = this.showPlayBtn;
		    player.showFullscreenBtn = this.showFullscreenBtn;
		    player.x5VideoPlayerType = 'h5-page';
		    player.x5VideoPlayerFullscreen = 'false';
		    player.autoplay = this.autoplay; // 以上均为 video标签的属性配置
			var myPlayer= document.getElementById('myPlayer')
			// console.log(myPlayer.childNodes,1)
			myPlayer.innerHTML=''
			myPlayer.appendChild(player);
		    if (flvjs.isSupported()) {
		        this.flvPlayer = flvjs.createPlayer({
		            type: 'flv',
		            isLive: true, //<====直播的话，加个这个
		            url: this.videourl//直播流地址
		        });
		        this.flvPlayer.attachMediaElement(player);
		        this.flvPlayer.load(); //加载
		        
		        // setTimeout(() => {
		        //     var player2 = document.createElement('video');
		        //     player2.play();
		        // }, 2000);
		        this.player = player;
		        this.flvPlayer.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
		            console.log('播放错误',errorType,errorDetail,errorInfo);
		            this.flv_destroy();
		            
		        });
		        uni.hideLoading();
		    }                   
		},
		flv_start() {
		    //开始
		    console.log(this.player);
		    this.player.play();
		},
		flv_pause() {
		    //暂停
		    this.player.pause();
		},
		flv_destroy() {
			// console.log(23)
		    //停止
			if(this.flvPlayer){
				this.flvPlayer.pause();
				this.flvPlayer.unload();
				this.flvPlayer.detachMediaElement();
				this.flvPlayer.destroy();
				this.flvPlayer = null;
				this.player=null;
			}
		    
		},
		flv_seekto() {
		    // 复制其他人的  我还没用这个
		    this.player.currentTime = parseFloat(document.getElementsByName('seekpoint')[0].value);
		}, 
		getChangellFn(ite,idx){
			this.address=ite.name
			this.indexCode=ite.indexCode
			this.adridx=ite.adridx;
			this.getCameraVideo()
			// 点击就放在第一位
			this.browselist.splice(idx,1)
			this.browselist.unshift(ite)
		},
		bindDateChangea(e){
			var val=e.detail.value;
			this.adridx=val
			this.address=this.adrlist[val].name;
			this.indexCode=this.adrlist[val].indexCode;
			// 获取直播视频
			this.getCameraVideo()
			// 添加浏览记录
			// 查重
			var newArr=JSON.parse(JSON.stringify(this.browselist))
			const index = newArr.findIndex(text => text.indexCode === this.indexCode);
			var obj={
				name:this.address,
				indexCode:this.indexCode,
				adridx:this.adridx,
			}
			if(index!=-1){
				this.browselist.splice(index,1)
				this.browselist.unshift(obj)
			}else{
				var len=newArr.length;
				if(len>2){
					this.browselist.pop()
				}
				this.browselist.unshift(obj)
			}	
		},
		getCodeFn(ite){
			this.dzaddress=ite.name;
			this.dzCode=ite.indexCode;
			// 获取直播视频
			this.getCameraVideo()
		},
		getCameraVideo(){
			// 设备
			this.videourl='';
			var indexCode=this.dzCode;
			if(this.tabval==2){
				indexCode=this.indexCode
			}
			getCameraVideo(indexCode).then(res=>{
				if(res.code==200){
					var data=res.data.data;
					if(data){
						this.videourl=data.url;
						// #ifdef H5
						this.flv_destroy()
						this.getLivePlayer()
						// #endif	
					}
				}else{
					this.$toast(res.msg)
				}
			}) 
		},
		getResetFn(){
			// 重置
			this.daytime='';
			this.getrefreshData()
		},
		bindDateChangeb(e){
			this.daytime=e.detail.value;
			this.getrefreshData()
		},
		getrefreshData(){
			this.pageNum=1;
			this.list=[];
			this.reachflag=true;
			this.getDataFn()
		},
		getCameraList(){
			// 设备
			var params={
				pageSize:1000,
				pageNo: 1,
			}
			getCameraList(params).then(res=>{
				if(res.code==200){
					var data=res.data.data;
					if(data&&data.access&&data.access.length>0){
						this.access=data.access;
						this.dzaddress=data.access[0].name;
						this.dzCode=data.access[0].indexCode;
						if(checkPermi(['system:camera:video'])){
							this.getCameraVideo()
						}
					}
					if(data&&data.list&&data.list.length>0){
						this.adrlist =data.list;
					}
				}else{
					this.$toast(res.msg)
				}
			}) 
		},
		init(){
			// 开关门类型
			getDictionaryFn('is_open').then(res=>{
				if(res.code==200){
					this.parameter.kgmlist = res.data.map(v => {
						return {
							label: v.dictLabel,
							value: v.dictValue
						}
					})
				}
			})
		},
		getDataFn(){
			var params={
				pageSize:this.pageSize,
				pageNum: this.pageNum,
			}
			if(this.daytime){
				params.controlsTime=this.daytime
			}
			getDoorList(params).then(res=>{
				if(res.code==200){
					if (res.rows.length < this.pageSize) {
						this.reachflag = false
						this.wtdt = '到底了~';
					} else {
						var num = parseInt(res.rows.length) + parseInt(this.pageSize) * parseInt(this.pageNum -	1)
						if (num < res.total) {
							this.reachflag = true
							this.wtdt = '上拉加载更多'
						} else {
							this.reachflag = false
							this.wtdt = '到底了~';
						}
					}
					if (this.pageNum == 1) {
						this.list = res.rows;
					} else {
						this.list = this.list.concat(res.rows)
					}
				}else{
					this.$toast(res.msg)
				}
			}) 
			
		},
	},
	
  }
</script>
<style>
page{background: #ffffff;}
</style>
<style lang="scss" scoped>
.jktit{text-align: center;font-weight: bold;font-size: 30rpx;color: #FFFFFF;width: 100%;}
.navbox /deep/ .uni-navbar__header-container {align-items: center;padding-left: 0;}
.navbox /deep/ uni-picker{flex: 1;}
.navbox /deep/ uni-cover-view{overflow: initial;}
.videotop{position: fixed;left: 0;right: 0;top: 0;z-index: 4;}
.navbox{
	
}
.tablist{padding: 0 200rpx 0rpx 32rpx;flex: 1;
		.tabs{position: relative;min-width: 156rpx;height: 64rpx;
			.tabtit{font-weight: 500;font-size: 28rpx;color: #C2E2FC;width: 100%;text-align: center;height: 56rpx;line-height: 56rpx;
				&.act{font-weight: bold;color: #FFFFFF;}
			}
			.tabline{width: 34rpx;height: 8rpx;background: #FFFFFF;border-radius: 4rpx;position: absolute;left: 50%;margin-left: -16rpx;bottom:0rpx;}
		}
	}
.chekts{
	position: absolute;right: 32rpx;bottom: 8rpx;z-index: 1;
	.chekt{font-weight: bold;font-size: 30rpx;color: #FFFFFF;display: flex;align-items: center;width: 200rpx;height: 56rpx;
		.chektit{flex: 1;min-width: 100rpx;text-align: right;}
		.chektimg{width: 16rpx;height: 10rpx;margin-left: 10rpx;flex: 0 0 auto;}
	}
}

.reset{width:56rpx; height: 88rpx;display: flex;align-items: center;justify-content: center;
	image{width: 26rpx;height: 30rpx;}
}
.navbg{width: 100%;height: 692rpx;z-index: 0;}	
.vidbox{overflow: hidden;
	border-radius: 14rpx;box-sizing: border-box;width:100%;position: relative;display: flex;align-items: center;overflow: auto;flex-wrap: nowrap;
	video{width: 100%;height: 450rpx;flex: 1;}
	.control{width: 210rpx;flex: 0 0 auto;background: #FFFFFF;border-radius: 14rpx;height: 450rpx;padding: 18rpx 0 4rpx;box-sizing: border-box;display: flex;flex-direction: column;margin-left: 16rpx;
		.contop{font-weight: bold;font-size:26rpx;color: #161616;margin-bottom: 10rpx;flex: 0 0 auto;
			image{width: 26rpx;height: 20rpx;margin-right: 12rpx;}
		}
		.conbox{
			mask:linear-gradient(#fff,#fff,#fff,transparent);
			-webkit-mask: linear-gradient(#fff,#fff,#fff,transparent);
		}
		.contit{font-size: 22rpx;height: 48rpx;line-height: 48rpx;text-align: center;
color: #161616;position: relative;
		&.act{font-weight: bold;color: #FFFFFF;}
		}
		.videobg{position: absolute;left: 0;right: 0;top: 0;bottom: 0;width: 100%;height: 48rpx;z-index: -1;}
	}
}
.openbox{margin-bottom: 36rpx;
	.btns{width: 320rpx;height: 98rpx;border-radius: 14rpx;display: flex;align-items: center;justify-content: center;
		font-weight: bold;font-size: 28rpx;color: #FFFFFF;
		image{width: 24rpx;height: 20rpx;margin-right: 14rpx;}
		
		&.bga{background: #0391FD;}
		&.bgb{background: #58CA5C;}
	}
}
.vlisttop{font-weight: bold;font-size: 30rpx;color: #161616;padding: 16rpx 0;margin-bottom: 20rpx;
	.vlleft{flex: 1;
		image{width: 26rpx;height: 26rpx;margin-right: 12rpx;}
	}
	.rlleft{
		view{font-weight: bold;font-size: 26rpx;color: #0391FD;min-width: 152rpx;}
		image{width: 18rpx;height: 10rpx;margin-left: 12rpx;}
	}
}
.table{
	// height: calc();
	overflow: auto;
}
.zxmain{position: relative;padding: 86rpx 32rpx 20rpx;}
.browntop{margin-bottom: 16rpx;
	image{width: 28rpx;height: 24rpx;margin-right: 10rpx;flex: 0 0 auto;}
	view{font-weight: bold;font-size: 30rpx;color: #161616;}
}
.brlists{margin-right: 16rpx;flex: 0 0 auto;width:216rpx;
	&:nth-of-type(3n){margin-right: 0;}
	image{width: 216rpx;height: 162rpx;margin-bottom: 18rpx;}
	view{font-size: 24rpx;color: #161616;width: 100%;text-align: center;}
}
</style>
