<template>
	<view class="content">
		<u-list @scrolltolower="scrolltolower" v-if="trainList.length > 0">
			<u-list-item v-for="(item, index) in trainList" :key="index">
				<view class="container_item">
					<view class="container_item_name">
						<text>{{ item.name }}</text>
					</view>

					<view class="container_item_content">
						<view class="content_text">
							<view>
								<text class="content_label">所属单位: </text>
								<text class="content_value">{{ item.corpinfoName }}</text>
							</view>
						</view>
						<view class="content_text">
							<view>
								<text class="content_label">培训开始时间: </text>
								<text class="content_value">{{ item.startTime }}</text>
							</view>
						</view>
						<view class="content_text">
							<view>
								<text class="content_label">培训结束时间: </text>
								<text class="content_value">{{ item.endTime }}</text>
							</view>
						</view>
						<view class="content_text">
							<view class="content_bottom">
								<view> <text class="content_label">任务状态: </text>{{ handleCalcTaskStatus(item.state) }} </view>
								<view class="action-row">
									<u-button size="mini" type="primary" text="签到信息" :disabled="item.userSignPath === '0'" @click="signInInformation(item.classId)" />
									<u-button v-if="item.examination === '1'" size="mini" type="primary" text="考试记录" :disabled="item.stageexamstate === '1' || item.stageexamstate === '4'" @click="ExamRecord(item)" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-list-item>
		</u-list>

		<empty v-else></empty>
	</view>
</template>

<script>
import store from '@/store/index'
import {getClassInfoByParams, getClassList, getExamExercises} from "../../api";
import {getStudentInfoApi} from "../../api/api";

export default {
	data() {
		return {
			pageSize: 10,
			currentPage: 1,
			totalPage: 0,
			trainList: [],
			taskStatusMap: {
				1: '待完善',
				4: '待开班',
				5: '培训中',
				6: '培训结束'
			}
		}
	},

	/* 监听页面显示，页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面 */
	async onShow() {
		await this.getUserFaceCompleted()
		await this.resetList()
	},

	methods: {
		async resetList() {
			this.pageSize = 10
			this.currentPage = 1
			this.trainList = []
			await this.getData()
		},
		async getData() {
			// verification --> 0: 未完成人脸认证
			// verification --> 1: 已完成人脸认证
			if (store.getters.getVerification === '1') {
				let resData = await getClassList({
					showCount: this.pageSize,
					currentPage: this.currentPage
				})
				this.trainList = [...this.trainList, ...resData.page.list]
				this.totalPage = resData.page.totalPage
			}
		},
		scrolltolower() {
			this.currentPage++
			if (this.totalPage >= this.currentPage) this.getData()
		},
    handleGetClassInfoByParams(classId) {
			return new Promise(async (resolve, reject) => {
				const userInfo = store.getters.getUserInfo
				await getClassInfoByParams({
					classId,
					userId: userInfo.USER_ID
				})
					.then((resData) => {
						resolve(resData.classInfo)
					})
					.catch(() => {
						uni.$u.toast('网络开小差了,请稍后尝试')
						reject()
					})
			})
		},
		/**
		 * 右上角自定义扫码图标触发事件
		 */
		onNavigationBarButtonTap(e) {
			// 只允许通过手机相机扫码
			uni.scanCode({
				// scanType: ['qrCode'], // 仅支持二维码扫码
				onlyFromCamera: false, // 是否只能从相机扫码，允许从相册选择图片
				hideAlbum: false, // 显示相册,允许从相册选择图片
				success:async (response) => {
					const { stageexampaperinputId, classId, type } = JSON.parse(response.result)
          // 调用获取学员信息的方法
          await this.getStudentInfoFunc(classId);
					const classInfo = await this.handleGetClassInfoByParams(classId);
					if (type === '2') {
						// 签到二维码方式进入, [type: 2 --> 签到二维码方式进入]
						if (classInfo) {
              if (classInfo.studystate === "3") {
                uni.$u.toast("您已经入班签到，无需再次签到！")
                return;
              }
							uni.$u.route({
								url: '/pages/train_management/realname_info_auth',
								params: {
									type: 'scan_face',
									classId
								}
							})
						} else {
							uni.$u.toast('您未在培训计划内，无法入班签到，请联系教师')
						}
					} else if (type === '3') {
						// 考试二维码方式进入 [type: 3 --> 考试二维码方式进入]
						if (classInfo) {
              console.log('classInfo :>> ', classInfo);
              if (classInfo.studystate !== "3") {
                uni.$u.toast("您还未入班签到，无法考试！")
                return;
              }
              if (classInfo.stageexamstate === "3") {
                uni.$u.toast("您已经考试通过，无需再次考试！")
                return;
              }
              const resData = await getExamExercises({
                stageexampaperinputId,
                classId,
              })
              if (resData.numberofexams <= 0) {
                uni.$u.toast("您的考试次数已用尽，无法再次考试！")
                return;
              }
							uni.$u.route({
								url: '/pages/train_management/face_authentication',
								params: {
									type: 'learning_certification',
									stageexampaperinputId,
									classId,
								}
							})
						} else {
							uni.$u.toast('您未在培训计划内，无法进行考试，请联系教师')
						}
					}
				},
				fail: function (error) {
					console.log('error :>> ', error)
				},
				complete: function (result) {
					console.log('扫码完成,正在跳转功能页!')
				}
			})
		},
		/**
		 * 使用网络接口获取学员信息
		 */
		async getStudentInfoFunc(classId) {
			const resData = await getStudentInfoApi({classId})
			await this.$store.dispatch('setStudentInfo', resData.studentInfo)
		},
		/**
		 * 获取是否已经完成上传人脸信息
		 */
		async getUserFaceCompleted() {
			// verification --> 0: 未完成人脸认证
			// verification --> 1: 已完成人脸认证
			if (store.getters.getVerification === '0') {
				uni.showModal({
					title: '温馨提示',
					content: '检测到您还未完成人脸信息读取，请先完成人脸信息认证!',
					success: function (res) {
						if (res.confirm) {
							uni.$u.route({
								url: '/pages/train_management/face_authentication',
								params: {
									type: 'facial_input'
								}
							})
						}
						if (res.cancel) {
							uni.navigateBack({ delta: 1 })
						}
					}
				})
			}
		},
		handleCalcTaskStatus(type) {
			return this.taskStatusMap[type]
		},
		/**
		 * 签到信息
		 */
		signInInformation(classId) {
			uni.$u.route({
				url: '/pages/train_management/sign_information',
				params: {
					classId
				}
			})
		},
		/**
		 * 考试记录
		 */
		ExamRecord(record) {
			const { stagestudentrelationId, classId } = record
			uni.$u.route({
				url: '/pages/train_management/exam_record',
				params: {
					classId,
					stagestudentrelationId
				}
			})
		}
	}
}
</script>

<style scoped lang="scss">
.container_item {
	padding-left: 16rpx;

	.container_item_name {
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
	}

	.container_item_content {
		display: flex;
		flex-direction: column;
		gap: 8rpx;

		.content_text {
			color: #acafb3;
			font-size: 30rpx;

			.content_label {
				display: inline-block;
				width: 220rpx;
			}

			.content_value {
				display: inline-block;
				transform: translateY(8rpx);
				padding: 0;
				width: 452rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			.content_bottom {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.action-row {
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 16rpx;
			}
		}
	}
}
</style>
