<template>
	<view class="default_page adffc" :style="{'height':h+'px', 'padding-top':mt+'px'}">
		<cus-header title='填写问卷'></cus-header>
		<view class="top">
			<view class="top-title">{{title||''}}</view>
			<view class="top-progress adfac">
				<view class="top-progress-text">测评进度</view>
				<view class="top-progress-box">
					<view class="top-progress-box-current" :style="{'width':(answerCount/list.length*100)+'%'}"></view>
				</view>
				<view class="top-progress-num"><span>{{answerCount}}</span>/{{list.length}}</view>
			</view>
		</view>
		<!-- <view class="memo adfac" v-if="turnType==='questionnaire'" @click="noticeShow=true">
			<text>问卷答题说明</text>
			<image :src="imgBase+'icon_memo.png'"></image>
		</view> -->
		<scroll-view class="list" scroll-y="true" :scroll-top="scrollTop">
			<view v-if="isLoading" class="loading-container adfacjc">
				<view class="adfac">
					<u-loading-icon size="42"></u-loading-icon>
					<text style="margin-left: 10rpx; font-size: 34rpx; color: #666666">问卷加载中...</text>
				</view>
			</view>
			<template v-else>
				<view>
					<view class="l_item" v-for="(item, index) in list" :key="item.id" :id="'question-' + index">
						<question-item :item="item" :index="index" @change="handleAnswerChange"></question-item>
					</view>
				</view>
			</template>
		</scroll-view>
		<!-- <view class="list">
			<view class="l_item" v-for="(item, index) in list" :key="item.id" :id="'question-' + index">
				<question-item :item="item" :index="index" @change="handleAnswerChange"></<question-item>
			</view>
		</view> -->
		<view class="bottom adfacjb">
			<view class="bottom-left adffcac" @click="showTeamInfo" v-if="type==1">
				<image :src="imgBase+'questionnaire_info.png'"></image>
				<text>团队信息</text>
			</view>
			<view class="bottom-left adffcac" @click="showTeamUser" v-else-if="turnType==='questionnaire'">
				<image :src="imgBase+'questionnaire_users.png'"></image>
				<text>团队人员</text>
			</view>
			<view class="bottom-right" :class="{'questionnaire':turnType==='questionnaire'}" @click="confirmSubmit">提交问卷</view>
		</view>
		<cus-notice :show="noticeShow" @close="noticeShow=false" @handleKnow="noticeShow=false"></cus-notice>
		<cus-team-info :show="teamShow" :teamInfo="teamInfo" @close="teamShow=false"></cus-team-info>
		<cus-team-user :show="userShow" :canEdit="false" :list="teamUserList" @close="userShow=false"></cus-team-user>
	</view>
</template>

<script>
	import QuestionItem from '@/components/QuestionItem/index3.vue'
	import CusNotice from '@/components/CusNotice/index2.vue'
	import CusTeamInfo from '@/components/CusTeamInfo/index.vue'
	import CusTeamUser from '@/components/CusTeamUser/index.vue'
	export default {
		components:{ CusNotice, QuestionItem, CusTeamInfo, CusTeamUser },
		data(){
			return {
				title:'',
				type:'',
				turnType:'',
				questionnaireId:'',
				noticeShow:false,
				teamShow:false,
				userShow:false,
				teamUserList:[],
				teamQuestionnaireId: '',
				list: [],
				questionnaire: null,
				isLoading: true,
				isSubmitting: false,
				scrollTop: 0, // scroll-view 的滚动位置
				oldScrollTop: 0, // 辅助值，确保即使滚动到相同位置也能触发
				userAnswerTemp: [],
				teamId:'',
				teamInfo:{},
				teamScaleData:[],
				teamLevelData:[],
				answerCount:0,
				categoryData:[]
			}
		},
		onLoad(options) {
			this.title = options.title||'';
			this.type = options.type;
			this.turnType = options.turnType;
			this.teamQuestionnaireId = options.teamQuestionnaireId;
			this.teamId = options.teamId;
			this.getList();
		},
		methods:{
			handleAnswerChange(e) {
				const item = this.list[e.index];
				if (item) {
					// 检查这道题在更新前是否已经回答完整
					const wasAnswered = item.answer.filter(a => a?.value).length === this.userAnswerTemp.length;
		
					let answer = JSON.parse(JSON.stringify(item.answer));
					answer.forEach(a => {
						a.value = a.assessmentMethod == e.assessmentMethod ? e.value : a.value
					});
					this.$set(item, 'answer', answer);
		
					// 检查这道题在更新后是否回答完整
					const isAnsweredNow = item.answer.filter(a => a?.value).length === this.userAnswerTemp.length;
		
					// 只有当题目从“未答完”变为“已答完”时，才增加计数
					if (!wasAnswered && isAnsweredNow) {
						this.answerCount++;
					}
		
					if (item.warn) {
						this.$set(item, 'warn', false);
					}
				}
				this.$nextTick(() => {
					this.setQuestionnaireCache();
				});
			},
			getList() {
				let questionnaire = null;
				try {
					const cacheStr = uni.getStorageSync('questionnaire');
					if (cacheStr) {
						questionnaire = JSON.parse(cacheStr);
					}
				} catch (e) {
					console.error('解析问卷缓存失败:', e);
					uni.removeStorageSync('questionnaire');
				}
			
				this.isLoading = true;
				this.$api
					.get('/core/team/member/answer/listByUser/' + this.teamQuestionnaireId)
					.then((res) => {
						if (res.data.code !== 0) return this.$showToast(res.data.msg);
						if(res.data.data.length===0) return this.$showToast('暂无问卷');
						const answerMap = new Map();
						if (questionnaire && this.teamQuestionnaireId == questionnaire.key) {
							questionnaire.list.forEach((q) => answerMap.set(q.id, q.answer));
						}
						
						this.userAnswerTemp = res.data.data[0].userAnswer.map(u=>{
							return {
								assessmentMethod:u.assessmentMethod,
								value:''
							}
						}) 
						let uaTemp = JSON.parse(JSON.stringify(this.userAnswerTemp))
						this.list = res.data.data.map(item => {
							let _a = answerMap.get(item.id);
							return {
								...item,
								answer:_a?uaTemp.map(u=>{
									return {
										assessmentMethod:u.assessmentMethod,
										value:_a.find(a=>a.assessmentMethod==u.assessmentMethod)?.value||''
									}
								}):this.userAnswerTemp,
								warn: false
							}
						});
						this.list.forEach(l=>{
							let _a = answerMap.get(l.id);
							l.userAnswer.forEach(u=>{
								u.answer = _a?(_a.find(a=>a.assessmentMethod==u.assessmentMethod)?.value||''):''
							})
						})
						
						this.answerCount = this.list.filter(l => l?.answer.filter(a => a?.value).length == this.userAnswerTemp.length).length;
						this.isLoading = false;
					})
					.catch(() => {
						this.isLoading = false;
						this.$showToast('获取异常，请稍后重试');
					})
					.finally(() => {
						this.isLoading = false;
					});
			},
			scrollToQuestion(index) {
				const query = uni.createSelectorQuery().in(this);
				const targetId = `#question-${index}`;
				query.select(targetId).boundingClientRect();
				query.select('.list').scrollOffset(); // 获取 scroll-view 的滚动信息
				query.select('.list').boundingClientRect(); // 获取 scroll-view 自身的位置信息
				query.exec((res) => {
					// 增加安全校验
					if (!res || !res[0] || !res[1] || !res[2]) {
						return;
					}
			
					// res[0]: 目标元素 (#question-N) 的位置信息
					const itemRect = res[0];
					// res[1]: 滚动容器 (.list) 的滚动信息
					const scrollViewScroll = res[1];
					// res[2]: 滚动容器 (.list) 自身的位置信息
					const scrollViewRect = res[2];
			
					// 计算目标滚动位置 = 当前滚动距离 + (目标元素顶部 - 滚动容器顶部) - 预留间距
					const targetPosition = scrollViewScroll.scrollTop + itemRect.top - scrollViewRect.top - 10; // 减10px作为顶部留白
			
					// 通过先设置为旧值，再在 nextTick 中设置为新值的方式，确保滚动能够触发
					this.scrollTop = this.oldScrollTop;
					this.$nextTick(() => {
						this.scrollTop = targetPosition;
						this.oldScrollTop = targetPosition;
					});
				});
			},
			async getUserCategoryData(){
				return new Promise((resolve,reject)=>{
					this.$api.get('/getListByType/UserCategory').then(({data:res})=>{
						if(res.code!==0) return this.$showToast(res.msg)
						this.categoryData = res.data.map(d=>({name:d.dictLabel,id:d.dictValue}))
						resolve()
					})
				})
			},
			async showTeamUser(){
				await this.getUserCategoryData()
				this.$api.get(`/core/member/listByQueTeamId/${this.teamQuestionnaireId}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamUserList = res.data;
					this.teamUserList.forEach(l=>{
						l.emailTM = this.$reg.desensitizeContent(l.email);
						l.mobileTM = this.$reg.desensitizeContent(l.mobile,2);
						l.categoryName = this.categoryData.find(c=>c.id==l.category)?.name;
					})
					this.userShow = true
				})
			},
			confirmSubmit() {
				if (this.isSubmitting) return;
			
				let firstUnansweredIndex = -1;
				this.list.forEach((l, i) => {
					const isAnswered = l.answer.filter(a => a?.value).length==this.userAnswerTemp.length?true:false;
					this.$set(l, 'warn', !isAnswered);
					if (!isAnswered && firstUnansweredIndex === -1) {
						firstUnansweredIndex = i;
					}
				});
			
				if (firstUnansweredIndex > -1) {
					uni.showModal({
						title: '提示',
						content: `第 ${firstUnansweredIndex + 1} 项未选择答案，请选择。`,
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								// 调用新的滚动方法
								this.scrollToQuestion(firstUnansweredIndex);
							}
						}
					});
					return; // 终止提交
				}
			
				const submitList = this.list.map((l) => {
					let {answer,userAnswer,warn,...other} = JSON.parse(JSON.stringify(l));
					userAnswer.forEach(u=>{
						u.questionOption.forEach(q=>{
							q.userAnswer=answer.find(a=>a.assessmentMethod==u.assessmentMethod)?.value==q.questionOption;
						})
					})
					return {
						...other,
						isAnswer: '1',
						userAnswer
					};
				});
				
				let that = this;
				uni.showModal({
					title:'温馨提示',
					content:'是否确认提交问卷？提交后不可修改。',
					success: (res) => {
						if(res.confirm){
							that.isSubmitting = true;
							that.$api
								.post('/core/team/member/answer/submit', submitList)
								.then((res) => {
									if (res.data.code !== 0) {
										that.isSubmitting = false;
										return that.$showToast(res.data.msg);
									}
									uni.removeStorageSync('questionnaire');
									let url = '/pagesPublish/questionnaireResult'
									if(that.type == 2) url = '/pagesPublish/submitResult'
									uni.navigateTo({ url })
								})
								.catch((err) => {
									that.$showToast('网络异常，请稍后重试');
								})
								.finally(() => {
									that.isSubmitting = false;
								});
						}
					}
				})
			},
			setQuestionnaireCache() {
				const answeredList = this.list.filter((l) => l.answer.filter(a => a?.value).length>0).map((l) => ({ id: l.id, answer: l.answer }));
				if (answeredList.length === 0) {
					uni.removeStorageSync('questionnaire');
					return;
				}
			
				const qinfo = {
					key: this.teamQuestionnaireId,
					list: answeredList
				};
				uni.setStorageSync('questionnaire', JSON.stringify(qinfo));
			},
			async getTeamScaleData(){
				return new Promise((resolve,reject)=>{
					this.$api.get('/getListByType/team_scale').then(({data:res})=>{
						if(res.code!==0) return this.$showToast(res.msg)
						this.teamScaleData = res.data.map(d=>({name:d.dictLabel,id:d.dictValue}))
						resolve()
					})
				})	
			},
			async getTeamHierarchyData(){
				return new Promise((resolve,reject)=>{
					this.$api.get('/getListByType/team_hierarchy').then(({data:res})=>{
						if(res.code!==0) return this.$showToast(res.msg)
						this.teamLevelData = res.data.map(d=>({name:d.dictLabel,id:d.dictValue}))
						resolve()
					})
				})	
			},
			async showTeamInfo(){
				await this.getTeamScaleData()
				await this.getTeamHierarchyData()
				this.$api.get(`/core/user/team/${this.teamId}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamInfo = res.data;
					this.teamInfo.functionsName = res.data.functions.map(f=>f.functionName).join('、');
					this.teamInfo.organizationsName = res.data.organizations.map(f=>f.orgName).join('、');
					this.teamInfo.address = res.data.provinceName+res.data.cityName;
					this.teamInfo.scaleName = this.teamScaleData.find(d=>d.id==res.data.scale)?this.teamScaleData.find(d=>d.id==res.data.scale).name:'';
					this.teamInfo.hierarchyName = this.teamLevelData.find(d=>d.id==res.data.hierarchy)?this.teamLevelData.find(d=>d.id==res.data.hierarchy).name:'';
					this.teamShow = true;
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.loading-container {
		width: 100%;
		height: 100%;
	}
	.default_page{
		padding: 0 0 40rpx;
		background: #FFFFFF;
		box-sizing: border-box;
		height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		
		.top{
			padding: 30rpx 24rpx 20rpx;
			&-title{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 40rpx;
				color: #002846;
				line-height: 51rpx;
			}
			&-progress{
				margin-top: 25rpx;
				&-text{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 30rpx;
					color: #002846;
					line-height: 30rpx;
				}
				&-box{
					flex: 1;
					width: 100%;
					height: 14rpx;
					margin: 0 20rpx;
					background: #F0F2F8;
					border-radius: 8rpx;
					position: relative;
					&-current{
						height: 14rpx;
						background: #FFD750;
						border-radius: 8rpx;
						position: absolute;
						left: 0;
						top: 0;
					}
				}
				&-num{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #667E90;
					line-height: 26rpx;
					span{
						font-size: 36rpx;
						color: #199C9C;
						line-height: 36rpx;
					}
				}
			}
		}
		
		.memo{
			margin: -20rpx 0 30rpx 24rpx;
			text{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #536387;
				line-height: 30rpx;
			}
			image{
				width: 24rpx;
				height: 24rpx;
				margin-left: 9rpx;
			}
		}
	
		.list{
			width: 100%;
			padding: 0 24rpx 20rpx;
			box-sizing: border-box;
			flex: 1;
			overflow-y: auto;
		}
	
		.bottom{
			width: 100%;
			background: #FFFFFF;
			box-shadow: 0rpx -2rpx 6rpx 0rpx rgba(0,0,0,0.07);
			padding: 20rpx 40rpx 24rpx;
			box-sizing: border-box;
			&-left{
				image{
					width: 42rpx;
					height: 42rpx;
				}
				text{
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #536387;
					line-height: 40rpx;
					margin-top: 2rpx;
				}
				&-pre{
					&:last-child{
						margin-left: 40rpx;
					}
				}
			}
			&-right{
				width: 448rpx;
				height: 88rpx;
				background: linear-gradient( 90deg, #33A7A7 0%, #64BBBB 100%);;
				border-radius: 44rpx;
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 88rpx;
				text-align: center;
				letter-spacing: 2rpx;
				&.questionnaire{
					width: 383rpx;
				}
			}
		}
	}
</style>