<template>
	<view class="todo-page" style="padding-bottom: 80px;">
		<view class="background"></view>
		<view class="video" v-if="filepath.length > 0&&isOnline">
			<uni-card margin="0" :is-shadow="true">
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" ref="wForm" errorType="border-bottom">
					<video id="myVideo" @ended="onEnd()" @timeupdate="onTimeUpdate" :src="filepaths" controls></video>
				</u--form>
			</uni-card>
		</view>
		<view v-if="isVodeoEnd" class="card">
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom" ref="sForm" class="demo-ruleForm">
				<view style="position: relative;">
					<view style="position: absolute;left: -10px;color: #3d4b70;top: -3px;">*</view>
				</view>
				
				<view style="font-size: 15px; font-weight: bold;color: #3d4b70;margin-bottom: 10px;">培训教育在线答题</view>
				<view v-for="(item, index) in papers" :key="index" style="border-bottom: #ceccca 1px dashed;margin-bottom: 10px;padding-bottom: 10px;">
					
					<u-form-item>
						<view class="uni-flex uni-column">
							<view style="margin-bottom: 10px;">{{(index + 1) + '. ' + item.Nav_Test.NAME + getType(item)}}
							</view>
							<view>
								<u-radio-group v-if="item.Nav_Test.TYPE == 0" v-model="item.ANSWER1" placement="column">
									<u-radio :customStyle="{marginBottom: '4px',marginTop: '4px'}" v-for="(item1, index1) in radiolist1" :key="index1" :label="item1.name" :name="item1.name"
										@change="doOptionChange(index1, item, 1)" :disabled="readonly" />
								</u-radio-group>
								<u-radio-group v-if="item.Nav_Test.TYPE == 1" v-model="item.ANSWER2" placement="column">
									<u-radio :customStyle="{marginBottom: '4px',marginTop: '4px'}" v-for="(item2, index2) in radiolist2[item.ID]" :key="index2" :label="item2.name" :name="item2.name"
										@change="doOptionChange(index2, item, 1 << index2)" :disabled="readonly" />
								</u-radio-group>
								<u-checkbox-group v-if="item.Nav_Test.TYPE == 2" v-model="item.ANSWER3" @change="checkboxChange($event, item)" placement="column">
									<u-checkbox :customStyle="{marginBottom: '4px',marginTop: '4px'}" v-for="(item3, index3) in radiolist2[item.ID]" :key="index3" :label="item3.name" :name="item3.name"
										:disabled="readonly">
									</u-checkbox>
								</u-checkbox-group>
							</view>
						</view>
					</u-form-item>
				</view>
			</u--form>
		</view>
		<view class="bottom-button">
			<button type="primary" v-if="tableKey == 1" @click="submit" :disabled="!isVodeoEnd">提交问卷</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup,
		formatSeconds
	} from '../../../../utils/common';
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import {
		GetSource,
		SavePapers
	} from '../../../../services/apply/subPages/scWB';
	import config from '../../../../config/common';

	export default {
		data() {
			return {
				model: {
					ORG_ID: "",
				},
				SOURCE_ID: '',
				papers: [],
				res: [],
				viewAll: false,
				filepath: '',
				notify: null,
				UserList: [],
				SelUsrID: null,
				config: null,
				score: 0,
				END_TIME: null,
				readonly: true,
				loading: false,
				tableKey: '0',
				isHaseV: true,
				isVodeoEnd: false, //是否显示题目
				radiolist1: [{
						name: '正确',
						disabled: false
					},
					{
						name: '错误',
						disabled: false
					},
				],
				radiolist2: {},
				radiovalue1: "错误",
				checkbox: [],
				TaskID: '',
				SelUsrNAME: '',
				ORG_ID: uni.getStorageSync('orgId'),
				JOBID: '',
				progress: 0,
				currentTime: '',
				allTime: '',
				lastTime: 0
			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.model.ID = option.ID ? option.ID : '';
			this.JOBID = option.ID ? option.ID : '';
			this.tableKey = option.tableKey ? option.tableKey : '0'
			this.loadData();
		},
		methods: {
			loadData() {
				let json = initFilter(this.ORG_ID, this.model.ID);
				extendRule(json, 'ID', 1, this.model.ID);
				GetSource(json).then(ret => {
					if (ret) {
						var filepath = ''
						var isOnline = false
						var papers = []
						var SOURCE_ID = ''
						var readonly = true
						var isVodeoEnd = true
						this.res = ret

						ret.Nav_ListUserPaper.forEach(ele => {
							if ((SOURCE_ID == '') && (ele.ANSWER == null || ele.ANSWER == 0)) {
								SOURCE_ID = ele.SOURCE_ID
								readonly = false
								isVodeoEnd = false
							}
							if (SOURCE_ID.length > 0 && ele.SOURCE_ID == SOURCE_ID) {
								papers.push(ele)
								isOnline = ele.IS_ONLINE
								if (isOnline == true && filepath == '') {
									filepath = ele.FILE_PATH
								}
							}
						});

						if (SOURCE_ID == "") {
							papers = ret.Nav_ListUserPaper
						}
						if (filepath == null || filepath == "") {
							isVodeoEnd = true
						}

						this.papers = papers
						this.isOnline = isOnline
						this.readonly = readonly
						this.SOURCE_ID = SOURCE_ID
						this.filepath = filepath
						this.filepaths = config.uni_app_web_source_url + filepath
						this.isVodeoEnd = isVodeoEnd

						this.papers.forEach(item => {
							let test = {}
							if (item.Nav_Test.TYPE != 0) {
								this.radiolist2[item.ID] = [];
								this.radiolist2[item.ID].push({
									name: item.Nav_Test.OPTION_A
								}, {
									name: item.Nav_Test.OPTION_B
								}, {
									name: item.Nav_Test.OPTION_C
								}, )
								if (item.Nav_Test.OPTION_D != undefined && item.Nav_Test.OPTION_D != "") {
									this.radiolist2[item.ID].push({
										name: item.Nav_Test.OPTION_D
									})
								}
								if (item.Nav_Test.OPTION_E != undefined && item.Nav_Test.OPTION_E != "") {
									this.radiolist2[item.ID].push({
										name: item.Nav_Test.OPTION_E
									})
								}
							}
						})
					}
				});
			},
			preventFastForward(e) {
				const currentTime = e.detail.currentTime;
				if (currentTime > this.lastTime + 1) {
					uni.$showErrorInfo('禁止快进');
					const videoContext = uni.createVideoContext('myVideo', this)
					videoContext.seek(this.lastTime);
				} else {
					this.lastTime = currentTime;
				}
			},
			findSelectedOptions(num, OPTION_A, OPTION_B, OPTION_C, OPTION_D, OPTION_E) {
				var optionVars = {
					'A': {
						value: 1,
						variable: OPTION_A
					},
					'B': {
						value: 2,
						variable: OPTION_B
					},
					'C': {
						value: 4,
						variable: OPTION_C
					},
					'D': {
						value: 8,
						variable: OPTION_D
					},
					'E': {
						value: 16,
						variable: OPTION_E
					}
				};
				var selectedVars = [];
				for (var key in optionVars) {
					if ((num & optionVars[key].value) === optionVars[key].value) {
						selectedVars.push(optionVars[key].variable);
					}
				}
				return selectedVars;
			},
			getType(paper) {
				let ret = '';
				let config = this.config;
				switch (paper.Nav_Test.TYPE) {
					case 0:
						ret = `【是非题】(${paper.SCOREVAL}分)`;
						break;
					case 1:
						ret = `【单选题】(${paper.SCOREVAL}分)`;
						break;
					case 2:
						ret = `【多选题】(${paper.SCOREVAL}分)`;
						break;
				}
				return ret;
			},
			doOptionChange(index, item, mask) {
				if (item.Nav_Test.TYPE === 2) {
					item.ANSWER |= mask;
				} else {
					item.ANSWER = mask;
				}

				if (item.ANSWER == item.Nav_Test.ANSWER) {
					item.SCORE = item.SCOREVAL
				} else {
					item.SCORE = 0
				}
			},
			checkboxChange(arr, item) {
				let indexArr = this.findCommonElementsIndices(arr, this.radiolist2[item.ID])
				item.ANSWER3 = arr;
				item.ANSWER = 0;
				indexArr.forEach(index => {
					if (index == 0) {
						item.ANSWER += 1;
					} else if (index == 1) {
						item.ANSWER += 2;
					} else if (index == 2) {
						item.ANSWER += 4;
					} else if (index == 3) {
						item.ANSWER += 8;
					} else if (index == 4) {
						item.ANSWER += 16;
					} else if (index == 5) {
						item.ANSWER += 32;
					}
				})
				if (item.ANSWER == item.Nav_Test.ANSWER) {
					item.SCORE = item.SCOREVAL
				} else {
					item.SCORE = 0
				}
			},
			findCommonElementsIndices(arr1, arr2) {
				const commonElements = [];
				for (let i = 0; i < arr1.length; i++) {
					for (let j = 0; j < arr2.length; j++) {
						if (arr1[i] === arr2[j].name) {
							commonElements.push(j);
						}
					}
				}
				return commonElements;
			},
			onTimeUpdate(e) {
				const currentTime = e.detail.currentTime;
				if (currentTime > this.lastTime + 1) {
					uni.$showErrorInfo('禁止快进');
					const videoContext = uni.createVideoContext('myVideo', this)
					videoContext.seek(this.lastTime);
				} else {
					this.lastTime = currentTime;
				}
			},
			//播放结束
			onEnd() {
				this.isVodeoEnd = true
			},
			submit() {
				if (this.tableKey != 1) {
					return
				}
				let data = JSON.parse(JSON.stringify(this.papers));
				var ALLSCORE = 0
				var PASSSCORE = 0
				for (let i = 0; i < data.length; i++) {
					if (data[i].ANSWER == 0) {
						uni.$showErrorInfo(`第${i + 1}题尚未选择答题，请完成所有答题后再进行提交`)
						return;
					}
					if (data[i].Nav_Test.TYPE === 2 && ([0, 1, 2, 4, 8].indexOf(data[i].ANSWER) !== -1)) {
						uni.$showErrorInfo(`第${i + 1}题为多选题，请选择至少两个选项`)
						return;
					}
					ALLSCORE += data[i].SCORE
					if (PASSSCORE == 0) {
						PASSSCORE = data[i].Nav_Source.PASSSCORE
					}
				}

				//没过线继续考
				if (ALLSCORE < PASSSCORE) {
					uni.$showErrorInfo(`分数不通过，请检查后再提交（得分${ALLSCORE}通过分数为${PASSSCORE}分)！`)
					return false;
				} else {
					// 判断是静态切换 还是直接提交
					let dataS = this.res;
					let SOURCE_ID = this.SOURCE_ID;
					if (SOURCE_ID != dataS.Nav_ListUserPaper[dataS.Nav_ListUserPaper.length - 1].SOURCE_ID) {
						// 切换试题
						var filepath = ''
						var isOnline = false
						var papers = []
						var SOURCE_IDNext = ''
						var readonly = true
						dataS.Nav_ListUserPaper.forEach(ele => {
							if ((SOURCE_IDNext == '') && (ele.ANSWER == null || ele.ANSWER == 0)) {
								SOURCE_IDNext = ele.SOURCE_ID
								readonly = false
							}
							if (SOURCE_IDNext.length > 0 && ele.SOURCE_ID == SOURCE_IDNext) {
								papers.push(ele)
								isOnline = ele.IS_ONLINE
								if (isOnline == true && filepath == '') {
									filepath = ele.FILE_PATH
								}
							}
						});
						if (filepath && filepath.length > 1) {
							this.isVodeoEnd = false //继续看视频
							this.filepath = filepath
							this.filepaths = config.uni_app_web_source_url + filepath
						}

						this.papers = papers
						this.isOnline = isOnline
						this.readonly = readonly
						this.SOURCE_ID = SOURCE_IDNext

						this.papers.forEach(item => {
							let test = {}
							if (item.Nav_Test.TYPE != 0) {
								this.radiolist2[item.ID] = [];
								this.radiolist2[item.ID].push({
									name: item.Nav_Test.OPTION_A
								}, {
									name: item.Nav_Test.OPTION_B
								}, {
									name: item.Nav_Test.OPTION_C
								}, )
								if (item.Nav_Test.OPTION_D != undefined && item.Nav_Test.OPTION_D != "") {
									this.radiolist2[item.ID].push({
										name: item.Nav_Test.OPTION_D
									})
								}
								if (item.Nav_Test.OPTION_E != undefined && item.Nav_Test.OPTION_E != "") {
									this.radiolist2[item.ID].push({
										name: item.Nav_Test.OPTION_E
									})
								}
							}
						})

					} else {
						//提交答卷
						var modelR = this.res
						if (this.TaskID != '')
							modelR.TaskID = this.TaskID
						SavePapers(modelR).then(ret => {
							uni.$showMsgFunc('操作成功!', () => {
								uni.navigateBack()
							}, 'success', 1000)
						}).catch(err => {
							if (err.length > 0) {
								uni.$showErrorInfo(err[0].message)
							} else {
								uni.$showErrorInfo('校验失败！')
							}
						})
					}
				}
			},
		}
	}
</script>

<style scoped>
	@import url("../../../../style/css/newTemplate.css");
</style>