<template>
	<!-- 
  注意注意：
  预约单地址过滤： 产品中因为可以进行单个用户数据权限配置，所以不调用getTruckAccessAddressByDriverTel方法进行过滤
  后续项目如果用户是统一的无法进行数据权限配置，可使用getTruckAccessAddressByDriverTel进行地址过滤
 -->

	<view class="exam" v-if="papers.length > 0">
		<!-- 预约单地址过滤 -->
		<!-- 		<view
				:style="filterExamPaper(paper)==='pass' && hasInvalidTime(paper)?'position: relative; padding-top: 32rpx ; margin-top: 24rpx;':''"
				v-for="(paper, index) in papers.filter(val=>truckAccessAddressList.includes(val['address.id']))" :key="index"> -->
		<view
			:style="filterExamPaper(paper) === 'pass' && hasInvalidTime(paper) ? 'position: relative; padding-top: 32rpx ; margin-top: 24rpx;' : ''"
			v-for="(paper, index) in papers" :key="index">
			<img v-if="filterExamPaper(paper) === 'pass' && filterInvalidTime(paper) && hasInvalidTime(paper)"
				src="../../static/img/bg/examInDate.png"
				style="height: 110rpx;width: 100vw;position: absolute;left: -24rpx;top: 0rpx; translate: 0 -24rpx;" />

			<img v-if="filterExamPaper(paper) === 'pass' && !filterInvalidTime(paper) && hasInvalidTime(paper)"
				src="../../static/img/bg/examOutDate.png"
				style="height: 110rpx;width: 100vw;position: absolute;left: -24rpx;top: 0rpx;translate: 0 -24rpx;" />
			<view class="exam_invalid_time" v-if="filterExamPaper(paper) === 'pass' && hasInvalidTime(paper)">
				<view style="color: #FFFFFF; font-size: 32rpx;">
					{{ filterExamPaper(paper) === 'pass' && filterInvalidTime(paper) &&
						hasInvalidTime(paper) ? "考试已通过" : "考试已失效" }}
				</view>
				<view
					:style="filterExamPaper(paper) === 'pass' && filterInvalidTime(paper) && hasInvalidTime(paper) ? 'color: #2E75E6; font-size: 24rpx;' : 'color: #FFA214; font-size: 24rpx;'">
					有效期至：{{ getInvalidTime(paper) }}
				</view>
			</view>
			<view class="exam_paper flex_sb flex_cen flex_center">
				<view class="flex_center">
					<img src="../../static/img/icon/exam_paper.png">
					<view>
						<view class="exam_paper_title">
							{{ paper['address.name'] || '' }}
						</view>
						<view class="exam_paper_content">
							{{ paper['name'] || '' }}
						</view>
					</view>
				</view>
				<view v-if="filterExamPaper(paper) === 'pass' && (filterInvalidTime(paper) || !hasInvalidTime(paper))"
					class="examPaper_resule_score">
					{{ getScore(paper) }}分
				</view>
				<button v-else @click="showRules(paper.id, filterExamPaper(paper), paper.video, paper.examRule)"
					:style="filterExamPaper(paper) ? 'background-color:#66CCCC;' : ''">{{ filterExamPaper(paper) ===
						'watch' ? '观看视频' : '参加考试' }}</button>
			</view>

		</view>
		<template v-if="show">
			<view class="" @touchmove.stop.prevent='touchmoveStop'>
				<u-popup :safeAreaInsetBottom="false" :show="show" mode="center" round="24rpx" @close="closeRules"
					customStyle="width:620rpx;">
					<view class="safe">
						<view class="safeTitle">
							厂内安全违规处罚细则
						</view>
						<scroll-view scroll-y="true" class="safeText">
							<u--textarea border="none" v-model="punishRules" disabled autoHeight maxlength="-1">
							</u--textarea>
						</scroll-view>
						<button :disabled="rulesText.length !== 0" @click="joinExam"
							:style="rulesText.length !== 0 ? 'opacity:.3' : ''">开始考试</button>
						<view style="text-align: center;margin-bottom: 48rpx;color: #F7A64A;">
							{{ rulesText }}
						</view>
					</view>

				</u-popup>

			</view>
		</template>
	</view>
	<view class="exam_empty" v-else>
		<image src="../../static/img/empty/exam_empty.png"></image>

		<view style="margin-top: 40rpx;font-size: 28rpx;color: #BFBFBF;text-align: center;">
			当前没有需要参加的考试
		</view>
	</view>

</template>

<script>
import {
	pathToBase64
} from 'image-tools'
import {
	BASEURL
} from '../../publicConfig/config.js'
import {
	formatGMT
} from '../../utils/util.js'
import {
	GetDriverExamPaper,
	GetDriverExamResult,
	userMobileOperation,
	GetTruckAccessAddressByDriverTel
} from '../../api/apiList.js'
import { TokenPrefix } from '../../publicConfig/config.js'
export default {
	data() {
		return {
			papers: [],
			show: false,
			punishRules: '',
			rulesText: '',
			timer: null,
			second: 5,
			pageNum: 1,
			userInfo: {},
			examResult: [],
			currentPaper: '',
			truckAccessAddressList: []
		};
	},
	onLoad() {

	},
	onShow() {
		this.clearTimer()
		this.pageNum = 1
		this.papers = []
		this.getDriverExamPaper()
		this.getDriverExamResult()

	},
	methods: {
		touchmoveStop() {

		},
		async pathToBase64(path) {
			console.log(await pathToBase64(path))
			return await pathToBase64(path)
		},
		joinExam() {
			uni.navigateTo({
				url: `/subpkg/exam/examPaper/examPaper?id=${this.currentPaper}`
				// url: '/subpkg/exam/examResult/examResult'
				// url: '/subpkg/exam/examVideo/examVideo'
			})
			this.show = false
		},
		closeRules() {
			this.show = false
			this.clearTimer()
		},
		showRules(id, statu, video, rule) {


			if (statu === 'watch') {
				uni.navigateTo({
					url: `/subpkg/exam/examVideo/examVideo?id=${id}&video=${video.split('=')[1]}`

				})
			} else if (statu === 'pass') {

			} else {
				if (rule) {


					uni.request({

						//#ifdef MP
						url: BASEURL.url + '/api/doc/download/' + rule.split('=')[1], //下载资源的 url 
						//#endif

						//#ifdef H5
						url: '/api/doc/download/' + rule.split('=')[1], //H5使用代理
						//#endif		
						header: {
							'Cookie': 'XSRF-TOKEN=' + uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
							"X-XSRF-TOKEN": uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
							"Authorization": uni.getStorageSync(`${TokenPrefix}_token`) || '',
						},
						success: (res) => {
							this.punishRules = res.data
							this.currentPaper = id
							this.show = true
							this.clearTimer()
							this.second = 5
							this.rulesText = `阅读 ${this.second} 秒后可进行操作`
							this.second--
							this.timer = setInterval(() => {
								if (this.second) {
									this.rulesText = `阅读 ${this.second} 秒后可进行操作`
									this.second--
								} else {
									this.rulesText = ''
									this.clearTimer()
								}

							}, 1000)
						}
					})

				} else {
					this.currentPaper = id
					this.joinExam()
				}

			}

		},
		clearTimer() {
			if (this.timer) clearTimeout(this.timer)

		},
		getDriverExamPaper() {
			GetDriverExamPaper({
				"args": {
					"pageNum": this.pageNum,
					"pageSize": 20,
				},
			}).then(res => {
				uni.stopPullDownRefresh()
				res.data.data.datas.map(val => {
					if (val.isTakeExam) {
						this.papers.push(val)
					}
				})
				this.pageNum += 1

			})
		},
		getDriverExamResult() {
			userMobileOperation('getUserInfo').then(res => {
				const data = res.data.data
				this.userInfo = {
					...data
				}
				this.examResult = []
				// this.getTruckAccessAddressByDriverTel()
				GetDriverExamResult({
					"args": {
						"pageNum": 1,
						"pageSize": 10000,
						"restrictions": [{
							"field": "driverTel",
							"type": "EQ",
							"value": this.userInfo.userExt.mobile
						}, {
							"field": "driverName",
							"type": "EQ",
							"value": this.userInfo.name
						}]
					},
				}).then(res => {
					uni.stopPullDownRefresh()
					res.data.data.datas.map(val => {
						this.examResult.push({
							name: val['examPaper.name'],
							passed: val.passed,
							watched: val.watched,
							examTime: val.examTime,
							invalidTime: val.invalidTime,
							score: val.score
						})
					})
				})
			})

		},
		filterExamPaper(paper) {
			for (const result of this.examResult) {
				if (result.name === paper.name) {
					if (!result.watched && paper.isTakeVideo) return 'watch'
					else if (result.passed) return 'pass'
					else return 'exam'
				}
			}
			if (paper.isTakeVideo) return 'watch'
			return 'exam'
		},
		filterInvalidTime(paper) {
			for (const result of this.examResult) {
				if (result.name === paper.name) {
					if (result.invalidTime && new Date(new Date(result.invalidTime).toLocaleDateString()) > new Date(new Date().toLocaleDateString())) return true
					else return false
				}
			}
			return false
		},
		hasInvalidTime(paper) {
			for (const result of this.examResult) {
				if (result.name === paper.name) {
					if (result.invalidTime) return true
					else return false
				}
			}
			return false
		},
		getScore(paper) {
			for (const result of this.examResult) {
				if (result.name === paper.name) {
					return result.score
				}
			}
			return 0
		},
		getInvalidTime(paper) {
			for (const result of this.examResult) {
				if (result.name === paper.name) {
					return formatGMT(result.invalidTime, 'D')
				}
			}
		},
		getTruckAccessAddressByDriverTel() {
			GetTruckAccessAddressByDriverTel({
				"aux": { 'driverTel': this.userInfo.userExt.mobile }
				// "aux": {'driverTel':''}

			}).then(res => {
				this.truckAccessAddressList = res.data.data

			})
		}
	},
	onPullDownRefresh() {
		this.clearTimer()
		this.pageNum = 1
		this.papers = []
		this.getDriverExamPaper()
		this.getDriverExamResult()
	},

}
</script>

<style lang="scss">
.exam_empty {
	height: 100vh;
	width: 100vw;

	image {
		margin-top: 167rpx;
		margin-left: 60rpx;
	}
}

.exam {
	min-height: 100vh;
	background-color: #FAFAFA;
	padding: 24rpx;

	.exam_paper_date {
		background-image: url('../../static/img/bg/examInDate.png');
	}

	&_paper {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		margin-top: 24rpx;
		padding: 24rpx;

		image {
			width: 104rpx;
			height: 104rpx;
			margin-right: 16rpx;
		}

		img {
			width: 104rpx;
			height: 104rpx;
			margin-right: 16rpx;
		}

		button {
			width: 216rpx;
			height: 72rpx;
			margin-right: 0;
			border-radius: 36rpx;
			line-height: 72rpx;
			background-color: #2E75E6;
			color: #FFFFFF;

			&::after {
				border: none;

			}
		}

		&_title {
			font-size: 31rpx;
			color: #434343;
			font-weight: bolder;
		}

		&_content {
			font-size: 28rpx;
			color: #8C8C8C;
			margin-top: 8rpx;
		}
	}

	.safe {
		padding: 0 24rpx;

		.safeTitle {
			color: #434343;
			font-size: 36rpx;
			font-weight: bolder;
			text-align: center;
			margin-top: 32rpx;
			margin-bottom: 24rpx;

		}

		.safeText {
			max-height: 600rpx;
		}

		/deep/.u-textarea {
			padding: 0;
		}

		/deep/.u-textarea--disabled {
			background-color: #FFFFFF;
		}

		button {
			margin-top: 48rpx;
			margin-bottom: 24rpx;
			width: 572rpx;
			height: 80rpx;
			border-radius: 40rpx;
			line-height: 80rpx;
			background-image: linear-gradient(90deg, #2E75E6, #5E58EE), linear-gradient(90deg, #2E75E6, #5E58EE);
			color: #FFFFFF;

			&::after {
				border: none;
			}
		}
	}

	.examPaper_resule_score {
		color: #27C488;
		font-size: 48rpx;
		width: 216rpx;
		margin-right: 0;
		margin-left: auto;
		text-align: center;
	}

	.exam_invalid_time {
		position: absolute;
		top: -24rpx;
		height: 110rpx;
		padding-left: 24rpx;
		padding-right: 24rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

}
</style>
