<template>
	<view class="page flex-col">
		<view style="width: 100%;background: #f4f5f6;box-sizing: border-box;padding-top: 88px;">
			<headers titles="考试结果录入">
				<uni-icons type="left" color="#000000" size="22px"></uni-icons>
			</headers>
		</view>
		<view class="block_2 flex-col">
			<scroll-view class="scroll-view" scroll-y :style="{ height: scrollHeight + 'px' }" refresher-enabled
				@refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered">
				<view class="box_5 flex-col" v-for="(item, index) in examList" :key="index"
					:style="{ height: ((item.subject != 2 && item.subject != 3) || (getButtonInfo(item).text === '1' || getButtonInfo(item).text === '2')) ? '230rpx' : 'auto' }">
					<view class="block_3 flex-row justify-between">
						<view class="text-group_1 flex-col justify-between">

							<text class="text_2"
								v-if="item.subject == 1 || item.subject == 4">{{ formatDate(item.examTime) }}
							</text>
							<text class="text_2" v-else>{{ formatDate(item.startTime) }}</text>
							<text class="text_3">{{ item.courseName }}</text>
						</view>
						<view class="text-group_2 flex-col justify-between">
							<text class="text_4" v-if="item.examScore != null">{{ item.examScore }}</text>
							<text class="text_4" v-else>{{ '--' }}</text>
							<text class="text_5"
								v-if="item.ifPassStatus === '9'">{{ getStatusText(item.ifPassStatus) }}</text>
							<text class="text_5" v-else>{{ getStatusText(item.examStatus) }}</text>
						</view>
					</view>
					<view class="block_4 flex-row justify-between">
						<view class="text-wrapper_1 flex-col">
							<text class="text_6">{{ getCourseTypeText(item.subject) }}</text>
						</view>
						<view class="text-wrapper_2 flex-col">
							<text class="text_7">{{ item.courseType }}</text>
						</view>
					</view>
					<view class="text-wrapper_3 flex-row justify-between" v-if="item.subject == 2 || item.subject == 3">
						<text class="text_8">考试地址：</text>
						<text class="text_9">{{ item.addr }}</text>
					</view>
					<view class="block_5 flex-row"
						v-if="(item.subject == 2 || item.subject == 3) && (getButtonInfo(item).text !== '1' && getButtonInfo(item).text !== '2')">
						<view class="text-wrapper_4 flex-col" @click="handleButtonClick(item)">
							<text class="text_10">{{ getButtonInfo(item).text }}</text>
						</view>
					</view>
				</view>

			</scroll-view>
		</view>
		<view class="block_8 flex-col">
			<view class="text-wrapper_8 flex-col" @click="onEnterScoreClick()">

				<text class="text_19">笔试成绩录入</text>
				<u-picker :show="pickerShow" :columns="[pickerColumns]" keyName="label" @confirm="onPickerConfirm"
					@cancel="pickerShow = false" />
			</view>
		</view>
	</view>

</template>
<script>
	import {
		getLocalUserInfo
	} from '../../utils/auth';
	import request from '@/utils/request.js'
	import headers from "@/components/header/headers.vue";

	export default {
		components: {
			headers
		},
		data() {
			return {
				loopData0: [{
						lanhutext0: '2025-01-20',
						lanhutext1: '考试名称',
						lanhutext2: '60分',
						lanhufontColor2: 'rgba(251,66,59,1.000000)',
						lanhutext3: '考试未通过',
						lanhufontColor3: 'rgba(251,66,59,1.000000)',
						lanhutext4: '科目二',
						lanhutext5: 'C2',
						lanhutext6: '考试地址：',
						lanhutext7: '山东省济南市历下区'
					},
					{
						lanhutext0: '2025-01-20',
						lanhutext1: '考试名称',
						lanhutext2: '--',
						lanhufontColor2: 'rgba(51,51,51,1.000000)',
						lanhutext3: '待审批',
						lanhufontColor3: 'rgba(51,51,51,1.000000)',
						lanhutext4: '科目二',
						lanhutext5: 'C2',
						lanhutext6: '考试地址：',
						lanhutext7: '山东省济南市历下区'
					}
				],
				userInfo: {},
				examList: {},
				examTwoList: {},
				scrollHeight: 0,
				constants: {},
				courseList: [],
				pickerShow: false,
				pickerColumns: [],
				curNow: 0,
				isTriggered: false,
			};
		},
		onLoad() {
			this.userInfo = getLocalUserInfo()
			this.getExamList()
			this.getCourseList()
			// 监听刷新事件
			uni.$on('refresh', () => {
				this.getExamList()
			})
		},
		onShow() {
			this.getExamList()
			this.getCourseList()
		},
		onReady() {
			// 动态计算滚动区域高度
			this.calculateScrollHeight();
		},
		methods: {
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			/**
			 * 下拉刷新数据
			 */
			onRefresherrefresh() {
				this.isTriggered = true
				this.pageNo = 1
				this.total = 0
				this.examList = []
				this.getExamList()

			},

			// 点击笔试成绩录入的时候 检查是否已报名课程
			onEnterScoreClick() {
				if (this.courseList.length > 0) {
					console.log('123123123', this.courseList)
					this.pickerColumns = this.courseList.map(item => ({
						label: item.courseName,
						value: item.courseId
					}));
					this.pickerShow = true;
				} else {
					this.$u.toast("暂无课程信息");
				}
			},

			// 选择课程后检查是否有课程进度信息
			onPickerConfirm(e) {
				const selectedCourseId = e.value[0];
				const selectedCourse = this.courseList.find(item => item.courseId === selectedCourseId.value);

				if (selectedCourse) {
					this.getProcess(selectedCourse.courseId).then(processData => {
						if (!processData || processData.length === 0) {
							uni.showToast({
								title: '暂无课程进度信息',
								icon: 'none'
							});
							return;
						}

						// 检查是否存在科目1或科目4的数据
						const hasSubject1Or4 = processData.some(item =>
							item.subject === 1 || item.subject === 4
						);

						if (hasSubject1Or4) {
							this.goToScoreEntry(selectedCourse);
						} else {
							uni.showToast({
								title: '未找到考试信息',
								icon: 'none'
							});
						}
					});
				}

				this.pickerShow = false;
			},

			// 跳转成绩录入界面
			goToScoreEntry(course) {
				console.log('course', course)
				/* uni.navigateTo({
				  url: `/pagesA/examinationAdd/index?courseId=${course.value}&courseType=${course.courseType}&userId=${course.userId}&tenantId=${course.tenantId}&coachId=${course.coachUserId}`
				}); */
				this.$u.route({
					url: '/pagesA/examinationAdd/index',
					params: {
						courseId: course.courseId,
						courseType: course.courseType,
						userId: course.userId,
						tenantId: course.tenantId,
						coachId: course.coachUserId,
					}
				});
			},

			// 获取课程进度
			getProcess(courseId) {
				return new Promise((resolve, reject) => {
					request({
						url: '/app-api/process/getAllByUserIdAndCourseId',
						method: 'GET',
						params: {
							userId: this.userInfo.id,
							courseId: courseId,
						}
					}).then(res => {
						this.processList = res.data;
						resolve(res.data);
					}).catch(err => {
						console.error('查询失败:', err);
						reject(err);
					});
				});
			},

			// 获取考试信息
			getExamList() {
				request({
					url: '/app-api/process/getExamListByUserId',
					method: 'GET',
					params: {
						userId: this.userInfo.id,
					}
				}).then(res => {
					// this.examList = res.data
					console.log('res', res)
					// 先按 subject 升序，subject 相同时按 createTime 升序
					this.examList = res.data.sort((a, b) => {
						if (a.subject !== b.subject) {
							return a.subject - b.subject;
						} else {
							return new Date(a.createTime) - new Date(b.createTime);
						}
					});
					this.isTriggered = false
				})
			},
			/* getExamTwoList() {
			  request({
			    url: '/app-api/examBatch/selectExamByUserIdAndCoachId',
			    method: 'GET',
			    params: {
			      userId: this.userInfo.id,
			    }
			  }).then(res => {
			    this.examTwoList = res.data
			    console.log('examTwoList', this.examTwoList)
			    console.log('resTwo', res)
			  })
			}, */

			// 获取课程信息
			getCourseList() {
				request({
					url: '/app-api/small/drive/school-course-order/getCourseByLoginUser',
					method: 'GET'
				}).then(res => {
					console.log('课程', res)
					this.courseList = res.data
				})
			},

			// 转换考试状态
			getStatusText(status) {
				const statusMap = {
					0: '未通过',
					1: '已通过',
					9: '已送考',
					'null': '未送考',
					'true': '已通过',
					'false': '未通过',
				};
				return statusMap[status] || '未知状态';
			},

			// 转换科目
			getCourseTypeText(status) {
				const statusMap = {
					'1': '科目一',
					'2': '科目二',
					'3': '科目三',
					'4': '科目四',
				};
				return statusMap[status] || '未知状态';
			},

			// 格式化时间
			formatDate(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			calculateScrollHeight() {
				// 获取屏幕高度
				const screenHeight = uni.getSystemInfoSync().windowHeight;
				// 获取顶部区域高度
				const topHeight = 88;
				// 计算滚动区域高度
				this.scrollHeight = screenHeight - topHeight;
			},


			getButtonInfo(item) {
				if (item.fraction == null) {
					return {
						text: '成绩录入',
						type: 'input'
					}
				} else if (!item.ifPass && !item.ifEvaluate) {
					return {
						text: '开始评价',
						type: 'evaluate'
					}
				} else if (!item.ifPass) {
					return {
						text: '2',
						type: 'failed'
					}
				} else if (!item.ifEvaluate) {
					return {
						text: '开始评价',
						type: 'evaluate'
					}
				} else {
					return {
						text: '1',
						type: 'evaluate'
					}
				}
				// else if (item.ifEvaluate) {
				//     return { text: '查看评价', type: 'view' }
				//   }
			},

			// 
			handleButtonClick(item) {
				const buttonInfo = this.getButtonInfo(item)

				switch (buttonInfo.type) {
					case 'input':
						this.goScoreInput(item)
						break
					case 'evaluate':
						this.goEvaluate(item)
						break
					case 'view':
						this.goViewEvaluation(item)
						break
					default:

				}
			},

			// 跳转到成绩录入页面
			goScoreInput(item) {
				uni.navigateTo({
					url: `/pagesA/examinationAdd/index?id=${item.batchItemId}&batchId=${item.batchId}&batchId=${item.batchId}&tenantId=${item.tenantId}&courseType=${item.courseType}&subject=${item.subject}&courseId=${item.courseId}&coachId=${item.coachId}`
				});
			},
			// 跳转到开始评价页面
			goEvaluate(item) {
				item = JSON.stringify(item)
				uni.navigateTo({
					url: `/pagesA/evaluateAdd/index?data=${item}&type=kaoshi&controls=add`
				})
			},

			// 跳转到查看评价页面
			goViewEvaluation(item) {
				uni.navigateTo({
					url: `/pagesA/evaluationDetail/index?evaluateId=${item.evaluateId}`
				})
			}

		}
	};
</script>
<style lang='scss'>
	@import '../common/common.scss';
	@import './assets/style/index.rpx.scss';
</style>