<template>
	<view class="todo-page">
		<view class="card">
			<uni-card margin="0" :is-shadow="true">
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" ref="wForm"
					errorType="border-bottom">
					<u-form-item label="培训名称：" prop="NAME" borderBottom>
						<u--input v-if="notify" v-model="notify.NAME" disabled disabledColor="#fff" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="开始时间：" prop="NAME" borderBottom>
						<u--input v-if="notify" v-model="notify.TRAIN_START_TIME" disabled disabledColor="#fff"
							border="none" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="结束时间：" prop="NAME" borderBottom>
						<u--input v-if="notify" v-model="notify.TRAIN_END_TIME" disabled disabledColor="#fff"
							border="none" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训地点：" prop="TRAIN_ADDR" borderBottom>
						<u--input v-if="notify" v-model="notify.TRAIN_ADDR" disabled disabledColor="#fff" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="组织部门：" prop="NAME" borderBottom>
						<u--input v-if="notify" v-model="notify.Nav_LaunchDepartment.NAME" disabled disabledColor="#fff"
							border="none" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训老师：" prop="TRAIN_TEACHER" borderBottom>
						<u--input v-if="notify" v-model="notify.TRAIN_TEACHER" disabled disabledColor="#fff"
							border="none" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训学时：" prop="HOURS" borderBottom>
						<u--input v-if="notify" v-model="notify.HOURS" disabled disabledColor="#fff" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="培训内容：" prop="NAME" borderBottom>
						<u--input v-if="notify" v-model="notify.NAME" disabled disabledColor="#fff" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="考试人员：" prop="score" borderBottom>
						<u--input v-model="SelUsrNAME" disabled disabledColor="#fff" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="成绩：" prop="score" borderBottom>
						<u--input v-model="score" disabled disabledColor="#fff" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<view class="video" v-if="this.isViedo&& this.isCourEdit&&this.filepath&&this.filepath.length>1">
						<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='this.filepath'
									controls></video>
							</u--form>
						</uni-card>
					</view>
					<u-form-item v-if="this.isViedo==false&& this.isCourEdit&&this.filepath&&this.filepath.length>1"
						label="课件附件：" borderBottom>
						<full-upload v-model="this.filepathf" :isShowBtn="false"></full-upload>
					</u-form-item>

				</u--form>
			</uni-card>
		</view>
		<u-sticky offset-top="20" v-if="isVideoEnd">
			<view class="sub-form">
				<view class="sub-form-wrap">
					<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom"
						ref="sForm">
						<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
							v-for="(item, index) in perPaper">
							<!-- papers -->
							<u-form-item>
								<view class="uni-flex uni-column">
									<view>{{(index+1)+'. '+ item.Nav_Test.NAME+getType(item.Nav_Test.TYPE)}}</view>
									<view>
										<u-radio-group v-if="item.Nav_Test.TYPE==0" v-model="item.ANSWER"
											placement="column">
											<u-radio :customStyle="{marginBottom: '4px',marginTop: '4px'}"
												v-for="(item1, index1) in radiolist1" :key="item1.value"
												:label="item1.name" :name="item1.value" :disabled="readonly"
												@change="doTrueOrFalse(index1,item)">
											</u-radio>
										</u-radio-group>

										<u-radio-group v-if="item.Nav_Test.TYPE==1" v-model="item.ANSWER"
											placement="column">
											<u-radio :customStyle="{marginBottom: '4px',marginTop: '4px'}"
												v-for="(item2, index2) in radiolist2[item.ID]" :key="item2.name"
												:label="item2.name" :name="item2.value"
												@change="doOptionChange(index2,item)" :disabled="readonly" />
										</u-radio-group>
										<u-checkbox-group v-if="item.Nav_Test.TYPE==2" v-model="item.ANSWER3"
											@change="checkboxChange($event,item,item.ID)" placement="column">
											<u-checkbox :customStyle="{marginBottom: '4px',marginTop: '4px'}"
												v-for="(item3, index3) in radiolist2[item.ID]" :key="item3.name"
												:label="item3.name" :name="item3.value" :disabled="readonly">
											</u-checkbox>
										</u-checkbox-group>
									</view>
								</view>
							</u-form-item>
						</uni-card>
					</u--form>
				</view>
			</view>
		</u-sticky>
		<view class="bottom-button">
			<button type="primary" v-if="tableKey==1" @click="submit">{{this.btnText}}</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup,
		getSelectedOptions,
		getFileShow
	} from '../../../../utils/common'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import config from '../../../../config/common'
	export default {
		data() {
			return {
				model: {
					ORG_ID: "",
				},
				papers: [], //wyw 引入课件后 变成 perPaper 的总和 20260306
				viewAll: false,
				record: null,
				notify: null,
				UserList: [],
				SelUsrID: null,
				configE: null,
				score: 0,
				END_TIME: null,
				readonly: true,
				loading: false,
				tableKey: '0',
				radiolist1: [{
						name: '正确',
						value: 1,
						disabled: false
					},
					{
						name: '错误',
						value: 2,
						disabled: false
					},
				],
				radiolist2: {},
				radiovalue1: "错误",
				checkbox: [],
				TaskID: '',
				EDIT_ID: '',
				SelUsrNAME: '',
				ORG_ID: uni.getStorageSync('orgId'),
				isCourEdit: false, //是否 有课件的考试
				isViedo: false,
				isVideoEnd: true,
				filepath: '',
				filepathf: [],
				btnText: '提交', //'下一题'
				perPaper: [], //每次的答题 wyw 20260306
				listPath: [],
				indexCour: -1 //课件

			}
			// https: //sps.cxtc.com:3199/BT/VIDEO/20251226/251226100216835841.mp4
			// https: //sps.cxtc.com:3199/BT/VIDEO/20251226/12345.mp4 
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.model.ID = option.ID ? option.ID : '';
			this.EDIT_ID = option.ID ? option.ID : '';
			this.tableKey = option.tableKey ? option.tableKey : '0'
			this.loadData();
		},
		methods: {
			loadData() {
				let json = initFilter(this.ORG_ID);
				if (this.TaskID) {
					extendRule(json, 'TEXT_ID', 1, this.model.ID);
				} else {
					extendRule(json, 'RECORD_ID', 1, this.model.ID);
				}
				extendInclude(json, 'Nav_User');
				getRequest(json, "/SE/SETrainRecord/GetUsers").then(res => {
					if (res && res.length > 0) {
						this.UserList = res
						if (this.viewAll) {
							this.SelUsrID = res[0].ID;
							this.getPapers();
						} else {
							let usr = res.find(it => it.ID == uni.getStorageSync('appInfo')?.User?.ID);
							if (usr) {
								this.SelUsrID = usr.ID
								this.SelUsrNAME = usr.NAME
								this.getPapers();
							} else {
								uni.$showMsgFunc('当前用户没有问卷!', () => {}, 'error', 1000)
							}
						}
					}
				});
			},
			getPapers() {
				let SelUsrID = this.SelUsrID;
				this.papers = [];
				if (!SelUsrID) {
					return;
				}
				var scort = 'Nav_Test.TYPE'
				if (!this.TaskID) {
					scort = 'TEXT_ID'
				}
				const json = initFilter(this.ORG_ID, this.TaskID, scort, 1)
				if (this.TaskID) {
					extendRule(json, 'TEXT_ID', 1, this.model.ID);
				} else {
					extendRule(json, 'RECORD_ID', 1, this.model.ID);
				}
				extendRule(json, 'USER_ID', 1, SelUsrID);
				extendInclude(json, 'Nav_Record');
				extendInclude(json, 'Nav_Record.Nav_Notify');
				extendInclude(json, 'Nav_Record.Nav_Notify.Nav_LaunchDepartment');
				extendInclude(json, 'Nav_Record.Nav_Notify.Nav_LaunchUser');
				extendInclude(json, 'Nav_Record.Nav_Notify.Nav_TrainContentList');
				extendInclude(json, 'Nav_Record.Nav_Notify.Nav_TrainType');
				// extendInclude(json, 'Nav_Record.Nav_Notify.Nav_TrainCheckType');
				extendInclude(json, 'Nav_Record.Nav_Notify.Nav_TrainContentList.Nav_Point');
				extendInclude(json, 'Nav_Test');
				extendInclude(json, 'Nav_User');
				getRequest(json, "/SE/SETrainRecord/GetUserPapers").then(res => {
					this.model = res
					if (this.tableKey == '1' && res.listPath != null && res.listPath.length > 0) {
						this.isCourEdit = true //考试 有 课件
						this.listPath = res.listPath
					}
					if (res.listPath.length > 1) {
						this.btnText = '下一题'
					}

					if (res && res.Nav_Papers && res.Nav_Papers.length > 0) {
						let papers = res.Nav_Papers.sort((a, b) => {
							return a.Nav_Test.TYPE - b.Nav_Test.TYPE
						});

						let configE = res.Nav_Config;
						let record = res.Nav_Papers[0].Nav_Record;
						let notify = record ? record.Nav_Notify : null;
						let hasAnswered = false;
						for (let i = 0; i < res.Nav_Papers.length; i++) {
							if (res.Nav_Papers[i].ANSWER !== 0) {
								hasAnswered = true;
							}
						}
						this.papers = papers;
						this.papers.forEach(item => {
							if (item.Nav_Test.TYPE == 2) {
								//查看试卷时 多选的绑定答案做数据处理
								item.ANSWER3 = getSelectedOptions(item.ANSWER)
							}
							let test = {}
							if (item.Nav_Test.TYPE != 0) {
								this.radiolist2[item.ID] = [];
								this.radiolist2[item.ID].push({
									name: item.Nav_Test.OPTION_A,
									value: 1
								}, {
									name: item.Nav_Test.OPTION_B,
									value: 2
								}, {
									name: item.Nav_Test.OPTION_C,
									value: 4
								}, )
								if (item.Nav_Test.OPTION_D != undefined && item.Nav_Test.OPTION_D !=
									"") {
									this.radiolist2[item.ID].push({
										name: item.Nav_Test.OPTION_D,
										value: 8
									})
								}
								if (item.Nav_Test.OPTION_E != undefined && item.Nav_Test.OPTION_E !=
									"") {
									this.radiolist2[item.ID].push({
										name: item.Nav_Test.OPTION_E,
										value: 16
									})
								}
							}
						})
						this.configE = configE;
						this.record = record;
						this.notify = notify;
						this.readonly = hasAnswered;
						this.score = this.papers[0].SCORE;
						if (this.isCourEdit) {
							this.submit()
						} else {
							this.perPaper = this.papers //提供显示
						}
						// this.filepath = res.listPath[0]
						// this.perPaper = this.papers.filter(e => e.FILE_PATH == this.filepath)
						// //如果是课件 对数据进行二次处理
						// if (this.isCourEdit) {
						// 	if (this.filepath.indexOf('/VIDEO/') > -1) {
						// 		this.isViedo = true
						// 		this.isVideoEnd = false
						// 		this.filepath = config.uni_app_web_video_source_url + this.filepath
						// 		this.filepathf = []
						// 	} else {
						// 		this.isViedo = false
						// 		this.filepathf = getFileShow(this.filepath)
						// 	}
						// }

					} else {
						uni.$showMsgFunc('未能成功获取此用户的在线试卷，请稍后重试!', () => {}, 'error', 1000)
					}
				})
			},
			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(type) {
				let ret = '';
				let configE = this.configE;
				switch (type) {
					case 0:
						ret = `【是非题】(${configE && configE.C_TEST_SCORE || 1}分)`;
						break;
					case 1:
						ret = `【单选题】(${configE && configE.S_TEST_SCORE || 1}分)`;
						break;
					case 2:
						ret = `【多选题】(${configE && configE.M_TEST_SCORE || 1}分)`;
						break;
				}
				return ret;
			},
			doTrueOrFalse(index, item) {
				item.ANSWER = (index + 1);
			},
			doOptionChange(index, item) {
				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;
				}
			},
			doCheckChange(index, item) {
				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;
				}
			},
			checkboxChange(arr, item, itemID) {
				let indexArr = this.findCommonElementsIndices(arr, this.radiolist2[itemID]) //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;
					}
				})
			},
			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].value) { //name
							commonElements.push(j);
							break
						}
					}
				}
				return commonElements;
			},
			submit() {
				if (this.indexCour > -1) { //首次加载不进来
					for (let i = 0; i < this.perPaper.length; i++) {
						if (this.perPaper[i].ANSWER == 0) {
							uni.$showMsgFunc(`第${i + 1}题尚未选择答题，请完成所有答题后再进行提交`, () => {}, 'error', 2000)
							return;
						} else if (this.perPaper[i].Nav_Test.TYPE == 2 && (this.perPaper[i].ANSWER == 1 || this.perPaper[i]
								.ANSWER == 2 || this.perPaper[i].ANSWER == 4 || this.perPaper[i].ANSWER == 8 || this
								.perPaper[
									i].ANSWER == 16)) {
							uni.$showMsgFunc(`第${i + 1}题为多选题，请完善答题后再进行提交`, () => {}, 'error', 2000)
							return;
						}
					}
					var replaceModel = {}
					this.papers.forEach(e => {
						replaceModel = this.perPaper.filter(ep => e.ID == ep.ID)
						if (replaceModel != null) {
							e = replaceModel
						}
					})
				}
				if (this.btnText == '提交' && this.indexCour > -1) {
					//提交
					let data = {
						Nav_Config: JSON.parse(JSON.stringify(this.configE)),
						Nav_Papers: JSON.parse(JSON.stringify(this.papers)),
						TaskID: this.TaskID,
						ORG_ID: this.ORG_ID,
						TEXT_ID: this.EDIT_ID, //this.props.data.id
					}
					getRequest(data, "/SE/SETrainRecord/SavePapers").then(res => {
						if (res && res.IsOperateSuccessful) {
							var icon = 'success'
							var duration = 1000
							if (!res.IsPass) {
								icon = 'error'
								duration = 2000
							}
							uni.$showMsgFunc(res.Msg, () => {
								uni.navigateBack()
							}, icon, duration)
						}
					})
				} else {
					this.indexCour++
					//下一题
					if (this.indexCour == this.listPath.length - 1) {
						this.btnText = '提交' //最后一题
					} else {
						this.btnText = '下一题'
					}
					this.filepath = this.listPath[this.indexCour]
					this.perPaper = this.papers.filter(e => e.FILE_PATH == this.filepath)

					if (this.filepath.indexOf('/VIDEO/') > -1) {
						this.isViedo = true
						this.isVideoEnd = false
						this.filepath = config.uni_app_web_video_source_url + this.filepath
						this.filepathf = []
					} else if (this.filepath.indexOf('.mp4') > -1 || this.filepath
						.indexOf('.avi') > -1) {
						//暂时不应该进来 
						this.isViedo = true
						this.isVideoEnd = false
						this.filepath = config.uni_app_web_source_url + this.filepath
						this.filepathf = []
					} else {
						this.isViedo = false
						this.isVideoEnd = true
						this.filepath = this.filepath
						this.filepathf = getFileShow(this.filepath)
					}
				}
			},
			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.isVideoEnd = true
			},
		}
	}
</script>

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

	.todo-page {
		padding: 16px 16px 70px;
	}
</style>