<template>
	<view class="survey-page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<cus-header :title="pageTitle"></cus-header>
		<view v-if="loading" class="survey-loading adfacjc">
			<u-loading-icon size="42"></u-loading-icon>
			<text>背景调研加载中...</text>
		</view>
		<template v-else-if="currentQuestion">
			<view class="survey-progress">
				<view class="survey-progress-row adfacjb">
					<text>答题进度</text>
					<text><span>{{currentIndex + 1}}</span>/{{survey.questionCount}}</text>
				</view>
				<view class="survey-progress-track">
					<view class="survey-progress-current" :style="{width:progressPercent+'%'}"></view>
				</view>
			</view>

			<scroll-view class="survey-content" scroll-y>
				<view class="question-card">
					<view class="question-sequence">第 {{currentIndex + 1}} 题</view>
					<view class="question-cn">{{currentQuestion.question}}</view>
					<view class="question-en" v-if="currentQuestion.questionEnglish">{{currentQuestion.questionEnglish}}</view>
					<view class="option-list">
						<view
							v-for="option in currentQuestion.options"
							:key="option.code"
							class="option-item adf"
							:class="{active:selectedCode===option.code}"
							@click="selectOption(option)"
						>
							<view class="option-radio adfacjc">
								<view v-if="selectedCode===option.code"></view>
							</view>
							<text class="option-text">{{option.text}}</text>
						</view>
					</view>
					<textarea
						v-if="selectedOption && selectedOption.customAllowed"
						v-model="customText"
						class="custom-input"
						maxlength="500"
						placeholder="请填写您的理解"
						placeholder-style="color:#B3BFC8"
					></textarea>
				</view>
			</scroll-view>

			<view class="survey-actions adfacjb">
				<view class="survey-btn secondary" :class="{disabled:currentIndex===0}" @click="previous">上一题</view>
				<view class="survey-btn primary" :class="{disabled:saving}" @click="next">
					{{currentIndex === survey.questionCount - 1 ? completeText : '下一题'}}
				</view>
			</view>
		</template>
		<view v-else class="survey-empty adfacjc">背景调研题库暂无题目</view>
	</view>
</template>

<script>
	import CusHeader from '@/components/CusHeader/index.vue'
	import backgroundSurveyRules from '@/utils/backgroundSurvey.js'
	const {
		selectedOption,
		validateBackgroundAnswer,
		createBackgroundAnswerPayload,
		perillIntroUrl
	} = backgroundSurveyRules

	export default {
		components:{ CusHeader },
		data(){
			return {
				mode:'coach',
				teamId:'',
				teamQuestionnaireId:'',
				surveyId:'',
				title:'',
				type:'',
				turnType:'',
				survey:null,
				currentIndex:0,
				selectedCode:'',
				customText:'',
				loading:true,
				saving:false,
				allowBack:false,
				completed:false
			}
		},
		computed:{
			pageTitle(){
				return this.mode === 'coach' ? '团队背景调研' : '团队背景调研'
			},
			completeText(){
				return this.mode === 'coach' ? '完成调研' : '下一阶段'
			},
			currentQuestion(){
				return this.survey && this.survey.questions
					? this.survey.questions[this.currentIndex]
					: null
			},
			selectedOption(){
				return selectedOption(this.currentQuestion, this.selectedCode)
			},
			progressPercent(){
				if(!this.survey || !this.survey.questionCount) return 0
				return ((this.currentIndex + 1) / this.survey.questionCount) * 100
			}
		},
		onLoad(options){
			this.mode = options.mode || 'coach'
			this.teamId = options.teamId || ''
			this.teamQuestionnaireId = options.teamQuestionnaireId || ''
			this.surveyId = options.surveyId || ''
			this.title = options.title || ''
			this.type = options.type || ''
			this.turnType = options.turnType || ''
			this.loadSurvey()
		},
		onBackPress(){
			if(this.allowBack || this.completed || !this.survey || this.survey.status === 'COMPLETED') return false
			uni.showModal({
				title:'背景调研尚未完成',
				content:'当前答案已保存为草稿，仍要退出吗？',
				confirmText:'仍然退出',
				confirmColor:'#FD4F66',
				success: result => {
					if(result.confirm){
						this.allowBack = true
						uni.navigateBack()
					}
				}
			})
			return true
		},
		methods:{
			async loadSurvey(){
				this.loading = true
				try {
					let response
					if(this.surveyId){
						response = await this.$api.get(`/core/background/survey/${this.surveyId}`)
					}else if(this.mode === 'coach' && this.teamQuestionnaireId){
						response = await this.$api.get(`/core/background/survey/coach/team-questionnaire/${this.teamQuestionnaireId}`)
					}else if(this.mode === 'coach'){
						response = await this.$api.post('/core/background/survey/coach/draft',{teamId:this.teamId})
					}else{
						response = await this.$api.get(`/core/background/survey/member/team-questionnaire/${this.teamQuestionnaireId}`)
					}
					const res = response.data
					if(res.code!==0) throw new Error(res.msg || '背景调研加载失败')
					this.applySurvey(res.data)
					const eventChannel = this.getOpenerEventChannel()
					if(eventChannel) eventChannel.emit('backgroundSurveyReady',{
						surveyId:this.survey.id,
						status:this.survey.status
					})
				} catch(error) {
					this.$showToast(error && (error.message || error.msg) || '背景调研加载失败')
				} finally {
					this.loading = false
				}
			},
			applySurvey(survey){
				this.survey = survey || { questions:[], questionCount:0 }
				this.surveyId = this.survey.id || this.surveyId
				if(this.currentIndex >= this.survey.questionCount) this.currentIndex = 0
				this.loadCurrentAnswer()
			},
			loadCurrentAnswer(){
				const question = this.currentQuestion
				this.selectedCode = question && question.optionCode || ''
				this.customText = question && question.customText || ''
			},
			selectOption(option){
				this.selectedCode = option.code
				if(!option.customAllowed) this.customText = ''
			},
			previous(){
				if(this.currentIndex===0 || this.saving) return
				this.currentIndex--
				this.loadCurrentAnswer()
			},
			async saveCurrent(){
				const error = validateBackgroundAnswer(
					this.currentQuestion, this.selectedCode, this.customText)
				if(error) throw new Error(error)
				const response = await this.$api.put(
					`/core/background/survey/${this.survey.id}/answer`,
					createBackgroundAnswerPayload(
						this.currentQuestion, this.selectedCode, this.customText))
				const res = response.data
				if(res.code!==0) throw new Error(res.msg || '答案保存失败')
				this.applySurvey(res.data)
			},
			async next(){
				if(this.saving) return
				this.saving = true
				try {
					await this.saveCurrent()
					if(this.currentIndex < this.survey.questionCount - 1){
						this.currentIndex++
						this.loadCurrentAnswer()
						return
					}
					const response = await this.$api.post(
						`/core/background/survey/${this.survey.id}/complete`,{})
					const res = response.data
					if(res.code!==0) throw new Error(res.msg || '背景调研提交失败')
					this.applySurvey(res.data)
					this.completed = true
					if(this.mode === 'coach'){
						const eventChannel = this.getOpenerEventChannel()
						if(eventChannel) eventChannel.emit('backgroundSurveyCompleted',{
							surveyId:this.survey.id,
							status:this.survey.status
						})
						this.$showToast('团队背景调研已完成')
						setTimeout(()=>{
							this.allowBack = true
							uni.navigateBack()
						},500)
						return
					}
					uni.redirectTo({
						url:perillIntroUrl({
							teamQuestionnaireId:this.teamQuestionnaireId,
							teamId:this.teamId,
							type:this.type,
							turnType:this.turnType,
							title:this.title
						})
					})
				} catch(error) {
					this.$showToast(error && (error.message || error.msg) || '背景调研处理失败')
				} finally {
					this.saving = false
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.survey-page{
		background:#F7F7F7;
		box-sizing:border-box;
		padding-bottom:170rpx;
	}
	.survey-loading,.survey-empty{
		height:60vh;
		color:#667E90;
		font-size:30rpx;
		text{margin-left:12rpx;}
	}
	.survey-progress{
		background:#FFFFFF;
		padding:28rpx 32rpx;
		&-row{
			font-size:28rpx;
			color:#667E90;
			span{font-size:36rpx;color:#199C9C;}
		}
		&-track{
			height:14rpx;
			margin-top:20rpx;
			border-radius:8rpx;
			background:#F0F2F8;
			overflow:hidden;
		}
		&-current{
			height:100%;
			background:#FFD750;
			border-radius:8rpx;
			transition:width .2s;
		}
	}
	.survey-content{
		height:calc(100vh - 360rpx);
		padding:24rpx;
		box-sizing:border-box;
	}
	.question-card{
		background:#FFFFFF;
		border-radius:24rpx;
		padding:32rpx 24rpx;
	}
	.question-sequence{font-size:26rpx;color:#199C9C;margin-bottom:20rpx;}
	.question-cn{font-size:34rpx;color:#002846;line-height:52rpx;font-weight:500;}
	.question-en{font-size:26rpx;color:#667E90;line-height:40rpx;margin-top:16rpx;}
	.option-list{margin-top:30rpx;}
	.option-item{
		padding:24rpx 20rpx;
		background:#F7F8FA;
		border:2rpx solid transparent;
		border-radius:18rpx;
		margin-top:18rpx;
		align-items:flex-start;
		&.active{background:#F0FAFA;border-color:#33A7A7;}
	}
	.option-radio{
		width:34rpx;
		height:34rpx;
		border:2rpx solid #B3BFC8;
		border-radius:50%;
		margin:4rpx 18rpx 0 0;
		flex:none;
		view{width:20rpx;height:20rpx;border-radius:50%;background:#199C9C;}
	}
	.option-item.active .option-radio{border-color:#199C9C;}
	.option-text{font-size:28rpx;color:#335368;line-height:42rpx;white-space:pre-line;}
	.custom-input{
		width:100%;
		height:180rpx;
		background:#F7F8FA;
		border-radius:18rpx;
		padding:24rpx;
		box-sizing:border-box;
		font-size:28rpx;
		line-height:42rpx;
		color:#335368;
		margin-top:22rpx;
	}
	.survey-actions{
		position:fixed;
		left:0;
		right:0;
		bottom:0;
		padding:24rpx 32rpx 44rpx;
		background:#FFFFFF;
		box-shadow:0 -2rpx 10rpx rgba(0,0,0,.06);
		z-index:10;
	}
	.survey-btn{
		width:calc(50% - 12rpx);
		padding:26rpx 0;
		border-radius:48rpx;
		text-align:center;
		font-size:30rpx;
		&.secondary{background:#F0F2F8;color:#667E90;}
		&.primary{background:linear-gradient(90deg,#33A7A7,#64BBBB);color:#FFFFFF;}
		&.disabled{opacity:.5;}
	}
</style>
