<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" @handleConfirm="handleConfirm" :confirmText="confirmText" :qtype="qtype"></cus-team-info-fill>
	</view>
</template>

<script>
	import CusTeamInfoFill from '@/components/CusTeamInfoFill/index.vue'
	export default {
		components:{ CusTeamInfoFill },
		data(){
			return {
				title:'',
				type:'',
				next:'',
				questionnaireId:'',
				confirmText:'下一步',
				qtype:''
			}
		},
		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){
				team.questionnaireId = this.questionnaireId;
				try {
					const { data:res } = await this.$api.post('/core/user/team',team)
					if(res.code!==0) return this.$showToast(res.msg)
					const teamId = res.data && res.data.teamId
					if(!teamId) return this.$showToast('团队保存失败，请重试')
					const uploadResult = await this.$refs.teamRef.flushBackgroundFiles(teamId)
					if(uploadResult.failed > 0){
						await this.$showModal(`${uploadResult.failed}个背景资料上传失败，可重试后继续`)
					}
					if(this.$refs.teamRef.hasDeferredPcUpload()){
						await this.$refs.teamRef.waitForDeferredPcUpload(teamId)
					}
					await this.continueAfterTeamCreated(teamId)
				} catch(error) {
					this.$showToast(error && (error.message || error.msg) || '团队保存失败，请重试')
				}
			},
			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) return this.$showToast(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>
