<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.TaskID && this.TaskID.length > 0">
						<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='https://sps.cxtc.com:3199/BT/VIDEO/20251226/251226100216835841.mp4'
									controls></video>
							</u--form>
							<u--form labelPosition="left" labelWidth="auto" labelAlign="center" ref="wForm"
								errorType="border-bottom">
								<video id="myVideo" @ended="onEnd()" @timeupdate="onTimeUpdate"
									src='https://sps.cxtc.com:3199/BT/VIDEO/20251226/12345.mp4' controls></video>
							</u--form>
						</uni-card>
					</view>
				</u--form>
			</uni-card>
		</view>
		<u-sticky offset-top="20">
			<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 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.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="doTrueOrFalse(index1,item)"
												: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)" :disabled="readonly" />
										</u-radio-group> -->
										<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">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup,
		getSelectedOptions
	} from '../../../../utils/common'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import config from '../../../../config/common'
	export default {
		data() {
			return {
				model: {
					ORG_ID: "",
				},
				papers: [],
				viewAll: false,
				record: null,
				notify: null,
				UserList: [],
				SelUsrID: null,
				config: 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'),
				filepath: 'https://sps.cxtc.com:3199/BT/VIDEO/20251226/251226100216835841.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, "", 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 (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 config = 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
									})
								}
							}
							// if (item.Nav_Test.TYPE == 0) {
							// 	if (item.ANSWER == 1) {
							// 		item.ANSWER = "正确";
							// 	} else if (item.ANSWER == 2) {
							// 		item.ANSWER = "错误";
							// 	}
							// 	if (item.Nav_Test.ANSWER == 1) {
							// 		item.Nav_Test.ANSWER = "正确";
							// 	} else if (item.ANSWER == 2) {
							// 		item.Nav_Test.ANSWER = "错误";
							// 	}
							// } else if (item.Nav_Test.TYPE == 1) {
							// 	switch (item.ANSWER) {
							// 		case 1:
							// 			item.ANSWER = item.Nav_Test.OPTION_A;
							// 			break;
							// 		case 2:
							// 			item.ANSWER = item.Nav_Test.OPTION_B;
							// 			break;
							// 		case 4:
							// 			item.ANSWER = item.Nav_Test.OPTION_C;
							// 			break;
							// 		case 8:
							// 			item.ANSWER = item.Nav_Test.OPTION_D;
							// 			break;
							// 		case 16:
							// 			item.ANSWER = item.Nav_Test.OPTION_E;
							// 			break;
							// 	}
							// } else if (item.Nav_Test.TYPE == 2) {
							// 	item.ANSWER = this.findSelectedOptions(item.ANSWER, item.Nav_Test.OPTION_A,
							// 		item.Nav_Test.OPTION_B, item.Nav_Test.OPTION_C, item.Nav_Test
							// 		.OPTION_D, item.Nav_Test.OPTION_E);
							// }
						})
						this.config = config;
						this.record = record;
						this.notify = notify;
						this.readonly = hasAnswered;
						this.score = this.papers[0].SCORE;

					} 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 config = this.config;
				switch (type) {
					case 0:
						ret = `【是非题】(${config && config.C_TEST_SCORE || 1}分)`;
						break;
					case 1:
						ret = `【单选题】(${config && config.S_TEST_SCORE || 1}分)`;
						break;
					case 2:
						ret = `【多选题】(${config && config.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() {
				let data = {
					Nav_Config: JSON.parse(JSON.stringify(this.config)),
					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
				}
				for (let i = 0; i < data.Nav_Papers.length; i++) {
					if (data.Nav_Papers[i].ANSWER == 0) {
						uni.$showMsgFunc(`第${i + 1}题尚未选择答题，请完成所有答题后再进行提交`, () => {}, 'error', 2000)
						return;
					}
				}
				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)
					}
				})
			},
			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
			},
		}
	}
</script>

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

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