<template>
	<div class="video-container">
		<div v-if="!isShowDetail">
			<div class="table-filter">
				<Select v-model="curGroup" style="width:200px" @on-change="onGroupFilter">
					<Option v-for="(item,index) in groupList" :value="item.groupName" :key="index">{{ item.groupName }}
					</Option>
				</Select>
				<Input v-model="searchVal" suffix="ios-search" placeholder="搜索姓名..." style="width: auto"
					@on-change="onSearch" />
			</div>
			<Table :columns="ablitiesColumn" :data="origin" border :loading="tableLoading">
				<template slot-scope="{ row, index }" slot="result">
					<span v-show="row.result === '优秀'" style="color: #007700;font-weight: bold;">优秀</span>
					<span v-show="row.result === '合格'" style="color: #ff6326;font-weight: bold;">合格</span>
					<span v-show="row.result === '不合格'" style="color: red;font-weight: bold;">不合格</span>
					<span v-show="row.result === '-'">-</span>
				</template>
				<template slot-scope="{ row, index }" slot="action">
					<Button type="primary" size="small" style="margin-right: 5px;font-size: 12px;"
						@click="goReview(row)">评审</Button>
				</template>
			</Table>
		</div>
		<div class="animated appraise-detail" v-if="isShowDetail">
			<div class="video-wrap" style="display: flex;width: 100%;">
				<div class="left-panel">
					<div class="detail-title">
						<Icon type="md-arrow-back" @click="goBack" />
						<span>{{ curData.video.name }} 【 {{ curData.name }} - 课堂实录】</span>
					</div>
					<video-player class="video-player-box" style="width:100%;margin-bottom: 20px;" ref="videoPlayer" v-if="videoReady"
						:options="playerOptions" :playsinline="true" @playing="onPlayerPlaying($event)"
						@ready="playerReadied">
					</video-player>
					<div class="comment-input-wrap" v-if="!isSelf">
						<Input v-model="commentVal" type="textarea" :rows="3" placeholder="输入评论内容..."
							@on-focus="onInputFocus" />
						<div style="display: flex;flex-direction: column;">
							<Select v-model="curTypeIndex">
								<Option v-for="(item,index) in typeList" :value="index" :key="index">{{ item }}</Option>
							</Select>
							<Button type="success" @click="onSubmitComment" :loading="commentBtnLoading">提交评论</Button>
						</div>
					</div>
					<div class="right-block-item">
						<p class="video-title">{{ isSelf ? '校评结果' : '课纲实录评分'}}</p>
						<div style="display: flex;justify-content: space-between;">
							<div>
								<div class="appraise-item" v-for="(item,index) in dimensionList" :key="index">
									<p class="appraise-dimension-name">{{ item.val }}</p>
									<Rate v-model="appraiseArr[index]" @on-change="onRateChange" :disabled="isSelf"/>
								</div>
							</div>
							<div
								style="display: flex;flex-direction: column;align-items: center;margin-right: 100px;padding-top: 35px;">
								<div class="quick-appraise" v-if="!isSelf">
									<!-- <span>一键评分：</span> -->
									<span class="quick-item" @click="doQuickAppraise(2)"
										:style="{ background: curQuickAppraise === 2 ? '#19be6b' : '#a9a9a9' }">
										<Icon type="md-happy" /> 优秀
									</span>
									<span class="quick-item" @click="doQuickAppraise(1)"
										:style="{ background: curQuickAppraise === 1 ? '#df6d1c' : '#a9a9a9' }">
										<Icon type="md-done-all" /> 合格
									</span>
									<span class="quick-item" @click="doQuickAppraise(0)"
										:style="{ background: curQuickAppraise === 0 ? '#e50003' : '#a9a9a9' }">
										<Icon type="md-sad" /> 不合格
									</span>
								</div>
								<div class="appraise-result">
									<!-- <Icon :type="curQuickAppraise === 2 ? 'md-happy' : curQuickAppraise === 1 ? 'md-done-all' : 'md-sad'" size="40" :color="curQuickAppraise === 2 ? '#19be6b' : curQuickAppraise === 1 ? '#df6d1c' : '#e50003'"/> -->
									<!-- <span style="font-size: 50px;font-weight: bold;" :style="{ color: curQuickAppraise === 2 ? '#19be6b' : '#a9a9a9' }" v-if="curQuickAppraise === 2">优秀</span>
									<span style="font-size: 50px;font-weight: bold;" :style="{ color: curQuickAppraise === 1 ? '#df6d1c' : '#a9a9a9' }" v-else-if="curQuickAppraise === 1">合格</span>
									<span style="font-size: 50px;font-weight: bold;" :style="{ color: curQuickAppraise === 0 ? '#e50003' : '#a9a9a9' }" v-else>不合格</span> -->
									<img src="@/assets/image/good.png" alt="" v-if="curQuickAppraise === 2">
									<img src="@/assets/image/normal.png" alt="" v-else-if="curQuickAppraise === 1">
									<img src="@/assets/image/bad.png" alt="" v-else-if="curQuickAppraise === 0">
									<span style="font-size: 34px;font-weight: bold;" v-else>暂未评分</span>
									<span style="color: #a5a5a5;margin-top: 20px;">最终结果</span>
								</div>
								<Button type="success" size="large" icon="ios-paper-plane" @click="onSubmit"
									style="margin-left: 10px;" :loading="isBtnLoading" v-if="!isSelf">提交评审结果</Button>
							</div>
						</div>
					</div>
				</div>
				<div class="right-panel">
					<div class="right-block-item">
						<p class="video-title">课堂点评分析图</p>
						<!-- 视频打点统计曲线图 -->
						<div id="videoLine"></div>
					</div>
					<div class="right-block-item">
						<p></p>
						<span class="video-title">课堂评论详细表</span>
						<Table stripe :columns="commentCol" :data="commentList" width="100%">
							<template slot-scope="{ row, index }" slot="time">
								<span class="comment-time"
									@click="onTimeClick(time_to_sec(row.time))">{{ row.time }}</span>
							</template>
							<template slot-scope="{ row, index }" slot="type">
								<span class="comment-type">{{ row.type }}</span>
							</template>
							<template slot-scope="{ row, index }" slot="name">
								<span>
									<span>{{ row.name }}</span>
									<span class="comment-type" style="background-color: #06b550;margin-left: 10px;"
										v-if="row.role !== 'member'">{{ row.role === 'school' ? '管理员' : row.role === 'expert' ? '专家' : '' }}</span>
								</span>
							</template>
						</Table>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import {
		mapGetters
	} from 'vuex'
	import "videojs-contrib-hls.js/src/videojs.hlsjs"
	export default {
		data() {
			return {
				curQuickAppraise: 0,
				appraiseArr: [0, 0, 0, 0, 0],
				dimensionList: this.$GLOBAL.VIDEO_DIMENSIONS(),
				commentVal: '',
				curTypeIndex: 0,
				typeList: ['新颖', '适当', '建议', '问题'],
				videoReady: false,
				playerOptions: {
					playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
					autoplay: true, //如果true,浏览器准备好时开始回放。
					controls: true, //控制条
					preload: 'auto', //视频预加载
					muted: false, //默认情况下将会消除任何音频。
					loop: false, //导致视频一结束就重新开始。
					language: 'zh-CN',
					aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
					fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
					sources: [{
						type: 'video/mp4',
						src: ''
					}],
					poster: "", //你的封面地址
					width: document.documentElement.clientWidth,
					notSupportedMessage: '此视频暂无法播放，请稍后再试' //允许覆盖Video.js无法播放媒体源时显示的默认信息。
				},
				isBtnLoading: false,
				appraiseResult: 'good',
				checkAllGroup: [],
				spanb: [],
				groupList: [],
				origin: [],
				ablitiesColumn: [{
						title: '教师姓名',
						key: 'name'
					},
					{
						title: '课堂实录内容',
						key: 'videoName'
					},
					{
						title: '教研组',
						key: 'group'
					},
					{
						title: '校评结果',
						slot: 'result'
					},
					{
						title: '专家抽查',
						key: 'teacherAppraise'
					},
					{
						title: '操作',
						slot: 'action',
						key: 'action'
					}
				],
				curAbility: 0,
				curGroup: '全部教研组',
				isShowDetail: false,
				isShowReview: false,
				commentBtnLoading: false,
				tableLoading: false,
				curData: {
					video: {
						name: ''
					}
				},
				groupData: [],
				searchVal: '',
				curSas: {
					sas: '',
					url: '',
					name: ''
				},
				originList: [],
				commentCol: [{
						title: '时间',
						slot: 'time',
						width: 100
					},
					{
						title: '标签',
						slot: 'type',
						width: 100
					},
					{
						title: '评论人',
						slot: 'name',
					},
					{
						title: '评论内容',
						key: 'content'
					},
				],
				commentList: [],
				commentChartData: [],
				isTeacherRole: false,
				isSelf:false,
				curCommentPerArr:[]
			}
		},
		created() {
			//由DB取得該校所有使用者並放入state.schoolUserList
			this.$store.dispatch('user/getSchoolTeacher').then(
				res => {
					this.handelGroup()
					if (res.code == 0) {
						this.$Message.error('無法取得使用者資料')
					}
				},
				err => {
					this.$Message.error('user/setSchoolTeacher API error!')
				}
			)

			this.getAllVideo()
			let routerData = this.$route.params.data
			let isSelf = this.$route.params.isSelf
			console.log(isSelf)
			if (routerData && isSelf) {
				this.isSelf = isSelf
				this.isShowDetail = true
				this.isTeacherRole = false
				let data = {
					name: this.$store.state.userInfo.name,
					videoName: routerData.name,
					school: this.$store.state.userInfo.schoolCode,
					video: {
						id: routerData.id,
						name: routerData.name,
						url: routerData.url
					},
					teacher: {
						id: this.$store.state.userInfo.TEAMModelId,
						name: this.$store.state.userInfo.name
					}
				}
				this.goReview(data)
				
			}else if(routerData){
				this.isTeacherRole = true
				this.isShowDetail = true
				let data = {
					name: routerData.tmdname,
					videoName: routerData.vname,
					school: routerData.school,
					video: {
						id: routerData.vid,
						name: routerData.vname,
						url: routerData.vurl
					},
					teacher: {
						id: routerData.tmdid,
						name: routerData.tmdname
					}
				}
				this.goReview(data)
			}
		},
		methods: {
			onInputFocus() {
				// this.curVideoTime = 
			},
			/* 提交点评 */
			onSubmitComment() {
				if (this.commentVal.trim() === '') {
					this.$Message.warning('评论内容不能为空！')
					return
				}
				this.commentBtnLoading = true
				let totalSecond = document.getElementsByClassName('vjs-tech')[0].duration;
				let curSecond = this.$refs.videoPlayer.player.currentTime()
				let per = totalSecond <= 0 ? 0 : Math.round(curSecond / totalSecond * 10000) / 100.00
				let curRole = this.curUserRoles.includes('area') || this.curUserRoles.includes('admin') ? 'school' : (this
					.curUserRoles.includes('expert') ? 'expert' : 'member')
				let params = {
					"videoId": this.curData.video.id,
					"tmdid": this.curData.teacher.id,
					"commentTmdid":this.$store.state.userInfo.TEAMModelId,
					"opt": "Comment",
					"roleType": this.isTeacherRole ? 'member' : curRole,
					"comment": {
						"per": per,
						"videoTime": parseInt(curSecond),
						"tag": this.typeList[this.curTypeIndex],
						"tmdname": this.$store.state.userInfo.name,
						"content": this.commentVal,
						"atSchool": this.curData.school,
						"atTmdid": this.curData.teacher.id,
						"atTmdname": this.curData.teacher.name,
						"videoName": this.curData.videoName
					}
				}
				this.$api.jyzx.saveVideoAppraise(params).then(res => {
					if (!res.error) {
						setTimeout(() => {
							this.curCommentPerArr.push(per)
							let perGroup = this.getPercentGroup(this.curCommentPerArr)
							this.commentChartData = [0, ...perGroup]
							this.commentList.push({
								name: this.$store.state.userInfo.name,
								content: this.commentVal,
								type: this.typeList[this.curTypeIndex],
								time: this.transferSecond(curSecond),
								second:curSecond,
								role: this.isTeacherRole ? 'member' : curRole
							})
							this.commentList = this.commentList.sort((a,b) => a.second - b.second)
							this.initLineChart()
							this.commentVal = ""
							this.$Message.success('评论成功！')
							this.commentBtnLoading = false
						}, 1000)
					}
				}).catch(e => {
					this.commentBtnLoading = false
				})
			},
			/* 快速评分 */
			doQuickAppraise(val) {
				this.curQuickAppraise = val
				this.appraiseArr = val === 2 ? [5, 5, 5, 5, 5] : val === 1 ? [4, 4, 4, 4, 4] : [0, 0, 0, 0, 0]
			},
			/* 评星回调 */
			onRateChange() {
				this.curQuickAppraise = this.appraiseArr.every(i => i === 5) ? 2 : this.appraiseArr.every(i => i === 0) ?
					0 : 1
			},
			/* 点击时间点进行视频跳转 */
			onTimeClick(seconds) {
				this.$refs.videoPlayer.player.play();
				this.$refs.videoPlayer.player.currentTime(seconds);
			},
			/* 时间店转秒数 */
			time_to_sec(time) {
				var s = '';
				var hour = 0;
				var min = time.split(':')[0];
				var sec = time.split(':')[1];
				s = Number(hour * 3600) + Number(min * 60) + Number(sec);
				return s;
			},
			/* 提交评审结果 */
			onSubmit() {
				let canAppraiseRoles = ['admin', 'area', 'expert']
				if (!this.curUserRoles.some(i => canAppraiseRoles.includes(i)) || this.isTeacherRole) {
					this.$Message.warning('只有专家或管理员身份才能进行评审操作！')
					return
				}
				this.isBtnLoading = true
				let params = {
					"tmdid": this.curData.teacher.id,
					"commentTmdid": this.$store.state.userInfo.TEAMModelId,
					"opt": "Score",
					"videoId": this.curData.video.id,
					"school":this.curData.school,
					"score": this.appraiseResult === 'good' ? 2 : this.appraiseResult === 'normal' ? 1 : 0,
					"roleType": 'school',
					"dimensions": this.appraiseArr.map((i, index) => {
						return {
							id: this.dimensionList[index].code,
							star: i
						}
					})
				}
				this.$api.jyzx.saveVideoAppraise(params).then(res => {
					if (!res.error) {
						setTimeout(() => {
							this.goBack()
							this.isBtnLoading = false
							this.curQuickAppraise = 0
							this.appraiseResult = 'bad'
							this.appraiseArr = [0, 0, 0, 0, 0]
							this.$Message.success('提交成功！')
						}, 1000)
					}
				})

			},
			onPlayerPlay(player) {
				console.log('player play!', player)
			},
			onPlayerPause(player) {
				console.log('player pause!', player)
			},
			onPlayerPlaying(player) {
				console.log('视频播放中')
			},
			playerReadied(player) {
				console.log('视频已就绪')
			},
			/* 初始化点评折线图 */
			initLineChart() {
				let myChart = this.$echarts.init(document.getElementById('videoLine'));
				let that = this
				let option = {
					calculable: true,
					xAxis: {
						type: 'category',
						name: '视频进度',
						nameTextStyle:{
							padding:[70,0,0,-26]
						},
						boundaryGap: false,
						axisLabel: {
							showMaxLable: true, // 显示最大值
							showMinLable: false, // 显示最小值
							formatter: '{value}%'
						},
						splitLine: {
							// 网格线
							lineStyle: {
								type: 'dashed', // 设置网格线类型 dotted：虚线   solid:实线
								width: 0.5,
								color: '#39404D'
							},
							show: true // 隐藏或显示
						},
						axisLine: {
							onZero: false
						},
						data: ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100']
					},
					yAxis: {
						min: 0,
						type: 'value',
						name: '专家点评数',
						nameLocation: 'end',
						axisLine: {
							onZero: false
						},
						axisLabel: {
							showMaxLable: true, // 显示最大值
							showMinLable: false, // 显示最小值
						},
						splitLine: {
							// 网格线
							lineStyle: {
								type: 'dashed', // 设置网格线类型 dotted：虚线   solid:实线
								width: 0.5,
								color: '#39404D'
							},
							show: true // 隐藏或显示
						}
					},
					series: [{
						name: '评论数',
						type: 'line',
						smooth: true,
						data: that.commentChartData,
						symbolSize: 8,
						itemStyle: {
							normal: {
								color: '#66CDAA', //改变折线点的颜色
								borderWidth: 5,
								areaStyle: {
									color: that.$echarts.graphic.LinearGradient(0, 1, 0, 0, [{
										offset: 0.4,
										color: 'rgba(7,44,90,0.1)'
									}, {
										offset: 1,
										color: 'rgba(0,146,246,0.9)'
									}]),
								}
							}
						},
						markPoint: {
							itemStyle: {
								normal: {
									color: 'red'
								}
							}
						},
						lineStyle: {
							color: '#66CDAA', //改变折线颜色
							width: 3,
						},
					}],
					tooltip: {
						formatter: function(point) {
							if (point.dataIndex === 0) return
							let range = point.dataIndex === 1 ? `${point.dataIndex}0%` :
								`${point.dataIndex - 1}0% - ${point.dataIndex}0%`
							return `视频前${range} </br>评论数量：${point.value}`
						}
					}
				};

				myChart.setOption(option);
				myChart.on('click', function(params) {
					let totalSecond = document.getElementsByClassName('vjs-tech')[0].duration;
					that.onTimeClick(totalSecond * parseInt(params.value[0]) * 0.01)
				});
			},
			/* 秒数转化为时间点 */
			transferSecond(s) {
				var t = '';
				if (s > -1) {
					var hour = Math.floor(s / 3600);
					var min = Math.floor(s / 60);
					var sec = s % 60;
					//  if (hour < 10) {
					// t = '0' + hour + ":";
					//  } else {
					// t = hour + ":";
					//  }

					if (min < 10) {
						t += "0";
					}
					t += min + ":";
					if (sec < 10) {
						t += "0";
					}
					t += sec.toFixed(0);
				}
				return t;
			},
			/* 返回 */
			goBack() {
				if (this.isTeacherRole || this.isSelf) {
					this.$router.back(-1)
				} else {
					this.isShowDetail = false
					this.appraiseResult = 'bad'
					this.appraiseArr = [0, 0, 0, 0, 0]
					this.getAllVideo()
				}

			},
			/* 搜索 */
			onSearch(val) {
				this.origin = this.originList.filter(i => i.name.indexOf(this.searchVal) > -1)
			},
			/* 获取所有课堂实录数据 */
			async getAllVideo() {
				this.curSas = await this.$tools.getSchoolSas()
				this.origin = []
				this.tableLoading = true
				this.$api.jyzx.getAllVideo({
					"school": this.$store.state.userInfo.schoolCode,
				}).then(res => {
					this.tableLoading = false
					res.classVideos.forEach(i => {
						this.origin.push({
							name: i.teacher.name,
							videoName: i.videos.name,
							group: i.teacher.groupName,
							result: i.videos.score > -1 ? ['不合格', '合格', '优秀'][i.videos.score] :
								'-',
							video: i.videos,
							school: i.school,
							teacher: i.teacher,
							teacherAppraise: '未抽查'
						})
					})
					this.originList = JSON.parse(JSON.stringify(this.origin))

					this.doGroup()
				})
			},
			onGroupFilter(val) {
				if (val === '全部教研组') {
					this.origin = this.originList
				} else {
					this.origin = this.originList.filter(i => i.group === val)
				}
			},
			doGroup() {
				let contactDotb = 0;
				let spanb = [];
				this.origin.forEach((item, index) => {
					if (index === 0) {
						console.log(spanb)
						spanb.push(1)
					} else {
						if (item.name === this.origin[index - 1].name) {
							spanb[contactDotb] += 1;
							spanb.push(0)
						} else {
							contactDotb = index
							spanb.push(1)
						}
					}
				})
				this.spanb = spanb;
			},
			//转分组模式数据结构
			handelGroup() {
				this.teachers.forEach(item => {
					item.groupName = item.groupName || '默认组别'
				})
				let groupRes = this.$jsFn.groupBy(this.teachers, 'groupName')
				this.groupData.length = 0
				for (let index in groupRes) {
					this.groupData.push({
						groupName: groupRes[index][0].groupName || '默认组别',
						groupId: groupRes[index][0].groupId,
						teachers: groupRes[index]
					})
				}
				this.groupData.sort((a, b) => {
					return parseInt(a.groupId) - parseInt(b.groupId)
				})
				this.groupData.unshift({
					groupName: '全部教研组',
					groupId: '-1',
					teachers: []
				})
				this.groupList = this.groupData
				console.log('处理分组数据', this.groupData)
			},
			getPercentGroup(perList){
				let splitArr = [...new Array(10).keys()]
				let result = new Array(10).fill(0)
				perList.forEach(rate => {
					if (rate === 100) {
						result[9]++
					} else if (rate < 10) {
						result[0]++
					} else {
						splitArr.forEach((j, index) => {
							if (rate.toString().slice(0, 1) === j.toString()) {
								result[index]++
							}
						})
					}
				})
				return result
			},
			/* 跳转评审页面 */
			async goReview(data) {
				let curVideoComments = await this.getVideoComments(data)
				this.commentList = []
				this.commentChartData = []
				this.curCommentPerArr = []
				if (curVideoComments.length) {
					this.commentList = curVideoComments.map(i => {
						return {
							name: i.comment.tmdname,
							type: i.comment.tag,
							time: this.transferSecond(i.comment.videoTime),
							second:i.comment.videoTime,
							role: i.roleType,
							content: i.comment.comment
						}
					}).sort((a,b) => a.second - b.second)
					this.curCommentPerArr = curVideoComments.map(i => i.comment.per)
					let perGroup = this.getPercentGroup(this.curCommentPerArr)
					this.commentChartData = [0, ...perGroup]
				}
				this.curData = data
				this.isShowDetail = true
				this.playerOptions.sources[0].src = this.curData.video.url + this.curSas.sas
				this.videoReady = true
				this.$nextTick(() => {
					this.initLineChart()
				})
			},
			/* 获取课堂实录评价数据 */
			getVideoComments(data) {
				return new Promise((r, j) => {
					this.$api.jyzx.saveVideoAppraise({
						"videoId": data.video.id,
						"tmdid": data.teacher.id,
						"opt": "ReadAllComment",
						"roleType": "school",
						"atSchool": data.school
					}).then(res => {
						if (!res.error) {
							if(this.isSelf){
								if(Object.keys(res.schoolAppraise).length){
									this.appraiseArr = res.schoolAppraise.dimensions.map(i => i.star)
									this.curQuickAppraise = res.schoolAppraise.score
								}else{
									this.appraiseArr = [0,0,0,0,0]
									this.curQuickAppraise = -1
								}
							}
							r(res.comments)
						}
					}).catch(e => {
						j(e)
					})
				})
			},
			handleSpan({
				row,
				column,
				rowIndex,
				columnIndex
			}) {
				if (columnIndex === 0) {
					if (this.spanb[rowIndex]) {
						return {
							rowspan: this.spanb[rowIndex],
							colspan: 1
						}
					} else {
						return {
							rowspan: 0,
							colspan: 1
						}
					}
				}

			}
		},
		mounted() {
			// this.$EventBus.$off('goVideoAppraise')
			// this.$EventBus.$on('goVideoAppraise',val => {
			// 	this.$nextTick(() => {
			// 		setTimeout(() => {
			// 			console.log(val)
			// 			this.isShowDetail = true
			// 			console.log(this.isShowDetail)
			// 		},2000)
			// 	})

			// })
		},
		computed: {
			...mapGetters({
				teachers: 'user/getSchoolUserJoined', // 取得已加入此學校的使用者
			}),
			curUserRoles() {
				return JSON.parse(decodeURIComponent(localStorage.userAccess, "utf-8")).roles
			}
		},
	}
</script>
<style lang="less" src="./Video.less"></style>
