<template>
	<view>
		<cu-custom ref="cuCustom" bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true" :backUrl="backUrl">
			<block slot="backText">返回</block>
			<block slot="content">我的考试</block>
		</cu-custom>
		<view class="select-fixed top-fixed">
			<view class="cu-bar search bg-white">
				<picker @change="statusChange" :value="sindex" :range="statusList" range-key="name">
					<view class="saixuan">
						<text>考试进度：</text>
						<text>{{ examText }}</text>
						<text class="cuIcon-triangledownfill"></text>
					</view>
				</picker>
			</view>
			<view class="line"></view>
		</view>
		<scroll-view class="dy-scroll" @scrolltolower="scrolltolower" scroll-y :style="'top:'+sTop+'px;height:calc(100vh - '+totalHeight+'px)'">
			<view v-if="list.length>0">
				<view class="dy-list">
					<view v-for="(item,index) of list" :key="index" :data-id="item.STAGEEXAMPAPER_ID" class="dy-list-item p20">
						<view class="dy-title-flex align-center">
							<text>试卷名称:{{item.EXAMNAME}}</text>
						</view>
						<view class="dy-subtitle-flex">
							<text>考试状态:{{item.EXAMSTATENAME}}</text>
						</view>
						<view class="dy-subtitle-flex">
							<text>开考时间:{{item.EXAMTIME}}</text>
						</view>
						<view class="dy-subtitle-flex">
							<text>答卷时间:{{item.ANSWERSHEETTIME}}分钟</text>
						</view>
						<view class="dy-subtitle-flex">
							<text>考试成绩:
								<span v-if="item.STAGEEXAMSTATE == '3'">{{item.STAGEEXAMSCORE}}分</span>
								<span v-else-if="item.STAGEEXAMSTATE == '4'">-</span>
							</text>
						</view>
						<view class="dy-subtitle-flex">
							<text>是否及格:{{item.STAGEEXAMSTATE == '4'?'-':(item.STAGEEXAMSTATE == '3'?(item.STAGEEXAMSCORE>=60?'是':'否'):'')}}</text>
						</view>
						<view v-if="item.STAGESTEP === '1'" class="dy-subtitle-flex">
							<text>{{ item.LASTTIME }}</text>
						</view>
						<view v-else-if="item.STAGESTEP === '2'" class="dy-subtitle-flex">
							<text class="red">剩余：{{ item.LASTTIME }}</text>
							<button class="cu-btn bg-green round sm" @click="$noMultipleClicks(goToExam, item)"><text class="cuIcon-playfill"></text>开始考试</button>
						</view>
					</view>
				</view>
			</view>
			<view v-else-if="dataFlag=='noData'" class="dy-null">
				<view class="dy-null-img">
					<image :src="background[dataFlag].url" mode=""></image>
				</view>
				<view class="dy-null-title">
					{{background[dataFlag].msg}}
				</view>
			</view>
			<view class="cu-tabbar-height"></view>
		</scroll-view>
	</view>
</template>

<script>
  import { decryptAes } from "@/common/aesUtil";
	import {
		basePath,
		corpinfoId,
		deptId,
		loginSession,
		formatDate,
		loginUser
	} from '@/common/tool.js';
	import tkiTree from "@/components/select-tree/select-tree.vue"
	export default {
		components: {
			tkiTree
		},
		data() {
			return {
				backUrl: '/pages/application/onlinexxks/home',
				showRight: false,
				dataFlag: 'noData',
				sTop: 0,
				totalHeight: 0,
				list: [], //返回数据
				page: 1, //分页参数--页数
				rows: 10, //分页参数--每页数据条数
				totalCount: 0, //分页参数--初始化页数
				isEnd: false, //防止多次刷新
				totalPage: 0, //分页参数--分页数量
				noClick: true,
				statusList: [{
						id: '',
						name: '请选择'
					},
					{
						id: '1',
						name: '未开始'
					},
					{
						id: '2',
						name: '进行中'
					},
					{
						id: '4',
						name: '已结束'
					}
				],
				sindex: -1,
				examState: '',
				examText: '请选择'
			}
		},
		onReady() {
			let that = this;
			let CustomBar = this.CustomBar;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let titleH = uni.createSelectorQuery().select(".top-fixed"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data => {
						that._data.sTop = data.height //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
						that.totalHeight = data.height + CustomBar
					}).exec()
				}
			})
		},
		onLoad() { //页面第一次加载时触发，从跳转页面返回时不能触发，可以传递参
			//页面显示或从后台跳回小程序时显示此页面时触发，从跳转页面返回时触发，不能传递参数
			var _this = this;
			_this.background = require('@/common/background.json');
			_this.showCount = -1;
			_this.currentPage = 1;
			_this.list = [];
			_this.isEnd = false;
			_this.getData();
			loginSession();
		},
		onBackPress() {
			this.$refs.cuCustom.BackPage()
			return true
		},
		onShow() {
		},
		beforeDestroy() {
			// 清除定时器
			this.list.forEach((ele) => {
				if (ele.STAGEEXAMSTATE === '1' && ele.STAGEEXAMPAPER_ID != null) {
					clearInterval(ele.countDown)
				}
			})
		},
		methods: {
			statusChange(e) {
				console.info(e.detail.value)
				console.info(this.statusList[this.sindex])
				this.sindex = e.detail.value;
				this.examState = this.statusList[this.sindex].id;
				this.examText = this.statusList[this.sindex].name
				this.getQuery();
			},
			getQuery() { //搜索按钮事件
				var _this = this;
				_this.showCount = -1;
				_this.currentPage = 1;
				_this.list = [];
				_this.isEnd = false;
				_this.getData();
			},
			// 滑动到底方法
			scrolltolower() {
				var _this = this;
				_this.showCount = -1;
				_this.currentPage = _this.currentPage + 1;
				_this.isEnd = false;
				if (_this.totalPage >= _this.currentPage) {
					_this.getData(); //开始分页查询
				}
			},
			getData() {
				var _this = this;
				if (_this.isEnd) {
					return
				} else {
					this.isEnd = true;
				}
				uni.showLoading({
					title: "加载中..."
				}); //加载中动画
				uni.request({
					url: basePath + '/app/stagestudentrelation/pageDataByUser?showCount=' + _this.showCount + '&currentPage=' +
						_this.currentPage,
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						tm: new Date().getTime(),
						EXAMSTATE: _this.examState, //关键字模糊查询
            CORPINFO_ID:loginUser.CORPINFO_ID,
            USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
            res.data = decryptAes(res.data);
						uni.hideLoading(); //结束加载中动画
						if (res.data != null) {
							_this.totalPage = res.data.page.totalPage
							// 从后端获取的数据，将这一步骤放到异步获取后端数据的地方，对后端返回的数据进行处理
							res.data.varList.forEach((ele) => {
								// 调用定时器传递
								_this.timeInterval(ele)
								// 如果数据不更新的话，增加下面代码
								// res.data.varList.splice(1, 0)
							})
							if (_this.list.length == 0) {
								// console.info('1')
								_this.list = res.data.varList;
								// console.info(_this.list)
							} else {
								if (res.data.varList != null) {
									_this.list2 = res.data.varList;
									// console.info(_this.list2)
									_this.list = _this.list.concat(_this.list2);
									// console.info(_this.list)
								}
							}
						}

					}
				})
			},
			// 倒计时定时器
			timeInterval(row) {
				if (row.STAGEEXAMSTATE === '1' && row.STAGEEXAMPAPER_ID != null) {
					// 绑定定时器
					row.countDown = setInterval(() => {
						const nowDate = new Date().getTime()
						// 计算剩余时间戳
						const beginTime = new Date(row.EXAMTIME.replace(/-/g,'/') + ':00').getTime()
						const endTime = beginTime + row.ANSWERSHEETTIME * 60 * 1000
						if (beginTime - nowDate > 0) {
							// 对每行的剩余时间进行设置
							row.lastTime = beginTime - nowDate
							row.stagestep = '1' // 未考试
							row.EXAMSTATENAME = '未开始'
							this.$set(row, 'LASTTIME', this.timeFormat(row.lastTime))
							this.$set(row, 'STAGESTEP', row.stagestep)
							if((beginTime-nowDate) == 5000) {
								uni.showModal({
									title: '',
									content: '<<'+row.EXAMNAME+'>>离开考时间还有五分钟！',
									showCancel: false,
									confirmText: '确定',
									success: res => {}
								})
							}
						} else if (beginTime <= nowDate && nowDate <= endTime) {
							if (row.EXAMSTATE == '0') {
								// 考试时间开始后，锁定试卷
								this.$set(row, 'EXAMSTATE', '1')
								uni.request({
									url: basePath + '/app/stageexampaper/updateExamState',
									method: 'POST',
									dataType: 'json',
									header: {
										'Content-type': 'application/x-www-form-urlencoded'
									},
									data: {
										USERNAME: loginUser.USERNAME,
										EXAMSTATE: '1',
										STAGEEXAMPAPER_ID: row.STAGEEXAMPAPER_ID,
                    CORPINFO_ID:loginUser.CORPINFO_ID,
                    USER_ID:loginUser.USER_ID,
									},
									success: (res) => {}
								})
							}
							// 对每行的剩余时间进行设置
							row.lastTime = endTime - nowDate
							row.stagestep = '2' // 已开考
							row.EXAMSTATENAME = '进行中'
							this.$set(row, 'LASTTIME', this.timeFormat(row.lastTime))
							this.$set(row, 'STAGESTEP', row.stagestep)
						} else {
							row.stagestep = '3' // 已结束
							row.EXAMSTATENAME = '已结束'
							row.STAGEEXAMSTATE = '4'
							this.$set(row, 'STAGESTEP', row.stagestep)
							// 清除定时器
							if(row.countDown) {
								clearInterval(row.countDown)
								row.countDown = null
							}
							if (row.STAGEEXAMSTATE == '1') { // 到时后自动更新学员状态为未参加考试
								uni.request({
									url: basePath + '/app/stagestudentrelation/updateStudentState',
									method: 'POST',
									dataType: 'json',
									header: {
										'Content-type': 'application/x-www-form-urlencoded'
									},
									data: {
										USERNAME: loginUser.USERNAME,
										// TYPE: '3',
										STAGEEXAMSTATE: '4',
										STAGESTUDENTRELATION_ID: row.STAGESTUDENTRELATION_ID,
                    CORPINFO_ID:loginUser.CORPINFO_ID,
                    USER_ID:loginUser.USER_ID,
									},
									success: (res) => {}
								})
							}
							if (row.EXAMSTATE == '0') { // 考试超期的做未参加处理，试卷做锁定
								this.$set(row, 'EXAMSTATE', '1')
								uni.request({
									url: basePath + '/app/stageexampaper/updateExamState',
									method: 'POST',
									dataType: 'json',
									header: {
										'Content-type': 'application/x-www-form-urlencoded'
									},
									data: {
										USERNAME: loginUser.USERNAME,
										EXAMSTATE: '1',
										STAGEEXAMPAPER_ID: row.STAGEEXAMPAPER_ID,
                    CORPINFO_ID:loginUser.CORPINFO_ID,
                    USER_ID:loginUser.USER_ID,
									},
									success: (res) => {}
								})
							}
						}
					}, 1000)
				} else if (row.STAGEEXAMSTATE === '3' || row.STAGEEXAMSTATE === '4') {
					row.EXAMSTATENAME = '已结束'
					this.$set(row, 'STAGESTEP', '3')
				}
			},
			// 剩余时间格式化
			timeFormat(times) {
				if (times > 0) {
					const days = this.addZero(
						Math.floor(times / 1000 / 60 / 60 / 24)
					) // 天
					const hours = this.addZero(
						Math.floor((times / 1000 / 60 / 60) % 24)
					) // 时
					const minutes = this.addZero(
						Math.floor((times / 1000 / 60) % 60)
					) // 分
					const seconds = this.addZero(Math.floor((times / 1000) % 60)) // 秒
					var html = days !== '00' ? days + '天' : ''
					html += hours !== '00' ? hours + '小时' : ''
					html += minutes !== '00' ? minutes + '分钟' : ''
					html += seconds + '秒'
					return html
				} else {
					return '已超时'
				}
			},
			// 个位补零
			addZero(d) {
				return parseInt(d) < 10 ? '0' + d : d
			},
			goToExam(item) {
				uni.redirectTo({
					url: '/pages/application/onlinexxks/my-exam-stage?STAGEEXAMPAPER_ID=' + item.STAGEEXAMPAPER_ID +
						'&STAGESTUDENTRELATION_ID=' + item.STAGESTUDENTRELATION_ID
				});
			}
		}
	}
</script>

<style>
	.dy-card {
		background-color: #fff;
		border-radius: 10upx;
		margin: 30upx
	}

	.dy-card-title {
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #eee;
		min-height: 80upx;
		line-height: 80upx;
		padding: 0 30upx;
	}

	.dy-card-content {
		padding: 0upx 30upx 30upx;

	}

	.dy-card-content-item {
		margin-top: 20upx;
	}

	.dy-card-content-item .title {
		display: flex;
		align-items: center;
	}

	.dy-card-content-item .title .l {
		width: 10upx;
		height: 30upx;
		border-radius: 20upx;
		background-color: #666;
		margin-right: 10upx;
	}

	.dy-card-content-item .content {
		background-color: #F1F1F1;
		padding: 10upx 14upx;
		margin-top: 14upx;
		line-height: 1.6;
	}

	.dy-card-content-item .name text {
		background-color: #F1F1F1;
		padding: 10upx 14upx;
		margin-top: 14upx;
		line-height: 1.6;
		display: inline-block;
	}

	.dy-card-foot {
		border-top: 1px solid #eee;
		padding: 30upx;
	}
	.dy-br{
		width: 200upx;
		text-align: right;
	}
	.dy-br .cu-btn{
		white-space: normal;
	}
	.red{
		color: #ff0000;
	}
</style>
