<template>
	<view class="default_page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<cus-header title='填写所在团队信息'></cus-header>
		<cus-team-info-fill ref="teamRef" :submitting="creationState.submitting || creationState.completed" @handleConfirm="handleConfirm" :confirmText="confirmText" :qtype="qtype"></cus-team-info-fill>
	</view>
</template>

<script>
	import CusTeamInfoFill from '@/components/CusTeamInfoFill/index.vue'
	import teamBackgroundRules from '@/utils/teamBackgroundFile.js'
	const {
		beginTeamSubmission,
		createTeamCreationState,
		finishTeamSubmission,
		rememberCreatedTeam,
		setTeamSubmissionStage
	} = teamBackgroundRules
	export default {
		components:{ CusTeamInfoFill },
		data(){
			return {
				title:'',
				type:'',
				next:'',
				questionnaireId:'',
				confirmText:'下一步',
				qtype:'',
				creationState:createTeamCreationState()
			}
		},
		onLoad(options) {
			this.title = options.title||'';
			this.type = options.type;
			this.qtype = options.qtype||'';
			this.questionnaireId = options.questionnaireId||'';
			this.confirmText = options.type?'确定':'下一步';
			this.next = options.next;
			if(this.next) this.confirmText = '下一步';
		},
		methods:{
			async handleConfirm(team){
				if(!beginTeamSubmission(this.creationState)) return
				team.questionnaireId = this.questionnaireId;
				try {
					let teamId = this.creationState.createdTeamId
					if(!teamId){
						setTeamSubmissionStage(this.creationState, 'save')
						const { data:res } = await this.$api.post('/core/user/team',team)
						if(res.code!==0){
							this.$showToast(res.msg || '团队保存失败，请重试')
							return
						}
						teamId = res.data && res.data.teamId
						if(!teamId){
							this.$showToast('团队保存未返回团队ID，请重试')
							return
						}
						rememberCreatedTeam(this.creationState, teamId)
					}

					setTeamSubmissionStage(this.creationState, 'upload')
					const uploadResult = await this.$refs.teamRef.flushBackgroundFiles(teamId)
					if(uploadResult.failed > 0 || this.$refs.teamRef.hasUnresolvedBackgroundFiles()){
						await this.$showModal('仍有背景资料未上传成功，请重试后继续；团队已保存，无需再次创建')
						return
					}
					if(this.$refs.teamRef.hasDeferredPcUpload()){
						setTeamSubmissionStage(this.creationState, 'pcSession')
						await this.$refs.teamRef.waitForDeferredPcUpload(teamId)
					}
					setTeamSubmissionStage(this.creationState, this.next ? 'publish' : 'navigate')
					await this.continueAfterTeamCreated(teamId)
					finishTeamSubmission(this.creationState, true)
				} catch(error) {
					this.showStageError(error)
				} finally {
					finishTeamSubmission(this.creationState)
				}
			},
			showStageError(error) {
				const prefix = {
					save:'团队保存失败',
					upload:'背景资料处理失败',
					pcSession:'电脑上传流程失败',
					publish:'问卷发布失败',
					navigate:'后续操作失败'
				}[this.creationState.stage] || '操作失败'
				const message = error && (error.message || error.msg)
				this.$showToast(message ? `${prefix}：${message}` : `${prefix}，请重试`)
			},
			async continueAfterTeamCreated(teamId) {
				if(this.next){
					const response = await this.$api.post('/core/team/questionnaire/publish',{
						answerSetting:1,
						coachId:JSON.parse(uni.getStorageSync('userInfo')).id,
						startTime:new Date().Format('yyyy-MM-dd hh:mm:ss'),
						endTime:new Date(new Date().setDate(new Date().getDate()+30)).Format('yyyy-MM-dd hh:mm:ss'),
						questionnaireId:this.questionnaireId,
						teamId,
						type:1
					})
					const result = response.data
					if(result.code!==0) throw new Error(result.msg || '发布请求失败')
					this.$showToast('保存成功，即将填写问卷')
					setTimeout(()=>{
						uni.removeStorageSync('newUser')
						uni.navigateTo({
							url:`/pagesPublish/questionnaireFill?teamQuestionnaireId=${result.data}&teamId=${teamId}&type=${this.type}&title=${this.title}`
						})
					},1500)
					return
				}
				this.$showToast('团队新增成功')
				setTimeout(()=>{
					this.getOpenerEventChannel().emit('saveTeamInfo')
					uni.navigateBack()
				},1500)
			}
		}
	}
</script>

<style scoped lang="scss">
	.default_page{
		box-sizing: border-box;
	}
</style>
