<template>
	<view class="default_page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
		<cus-header title='编辑团队' :interceptBack="true" @back="requestBack"></cus-header>
		<cus-team-info-fill ref="teamRef" :teamId="id" :submitting="saving" @handleConfirm="handleConfirm" :confirmText="confirmText"></cus-team-info-fill>
		<view class="dialog adffcacjc" v-if="show">
			<view class="dbox">
				<view class="dbox-title">温馨提示</view>
				<view class="dbox-content">本次团队配置修改将在本团队<span>所有激活状态下的PERILL团队发展动态评估问卷中</span>生效，确定提交吗？</view>
				<view class="dbox-btns adfacjb">
					<view class="zt_btn" @click="editConfirm">确定</view>
					<view class="qx_btn" @click="show=false">取消</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import CusTeamInfoFill from '@/components/CusTeamInfoFill/index.vue'
	import teamBackgroundRules from '@/utils/teamBackgroundFile.js'
	const { createTeamPayloadSnapshot, createTeamSubmitPayload } = teamBackgroundRules
	export default {
		components:{ CusTeamInfoFill },
		data(){
			return {
				id:'',
				teamInfo:null,
				confirmText:'确定',
				scaleName:'',
				hierarchyName:'',
				submitDto:null,
				show:false,
				saving:false,
				saveSucceeded:false,
				savedPayloadSnapshot:'',
				saveStage:'idle',
				navigationTimer:null,
				navigationReject:null,
				pageUnloaded:false
			}
		},
		onLoad(options) {
			this.pageUnloaded = false
			this.id = options.id;
			this.scaleName = options.scaleName;
			this.hierarchyName = options.hierarchyName;
			this.getDetail()
		},
		onShow() {
			if (!this.id) return
			this.$nextTick(() => {
				const background = this.$refs.teamRef && this.$refs.teamRef.$refs.backgroundRef
				if (background) background.refreshFiles(this.id).catch(error => {
					this.$showToast(error && (error.message || error.msg) || '资料列表刷新失败')
				})
			})
		},
		onUnload() {
			this.pageUnloaded = true
			this.cancelPendingRedirect(new Error('页面已离开'))
		},
		methods:{
			hasPendingBackgroundFiles(){
				const team = this.$refs.teamRef
				return Boolean(team && (team.hasUnresolvedBackgroundFiles()
					|| team.isBackgroundUploadActive()))
			},
			requestBack(){
				if(this.saving) return this.$showToast('团队正在保存，请稍候')
				if(!this.hasPendingBackgroundFiles()) return uni.navigateBack()
				uni.showModal({
					title:'背景资料尚未完成',
					content:'仍有背景资料正在上传或等待重试，返回将丢弃待处理队列；已发出的上传可能仍会完成。确定返回吗？',
					confirmText:'仍然返回',
					confirmColor:'#FD4F66',
					success: result => {
						if(result.confirm) uni.navigateBack()
					}
				})
			},
			getDetail(){
				this.$api.get(`/core/user/team/${this.id}`).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					this.teamInfo = res.data;
					this.$refs.teamRef.setTeamInfo(res.data)
					this.$refs.teamRef.teamInfo.functionIds = res.data.functions.map(f=>f.id);
					this.$refs.teamRef.teamInfo.orgIds = res.data.organizations.map(o=>o.id);
					this.$refs.teamRef.areaText = res.data.provinceName+res.data.cityName;
					this.$refs.teamRef.industryText = res.data.industryName;
					this.$refs.teamRef.functionTypeText = res.data.functions.map(f=>f.functionName).join('、');
					this.$refs.teamRef.architectureTypeText = res.data.organizations.map(f=>f.orgName).join('、');
					this.$refs.teamRef.teamScaleText = this.scaleName;
					this.$refs.teamRef.teamLevelText = this.hierarchyName;
				})
			},
			handleConfirm(data){
				this.submitDto = createTeamSubmitPayload(data);
				this.show = true;
			},
			async editConfirm(){
				if(this.saving) return
				this.saving = true
				const payload = createTeamSubmitPayload(this.submitDto)
				const payloadSnapshot = createTeamPayloadSnapshot(payload)
				try {
					if(!this.saveSucceeded || this.savedPayloadSnapshot !== payloadSnapshot) {
						this.saveStage = 'save'
						const { data:res } = await this.$api.put('/core/user/team',payload)
						if(res.code!==0){
							this.$showToast(res.msg)
							return
						}
						this.saveSucceeded = true
						this.savedPayloadSnapshot = payloadSnapshot
						this.show = false
						this.$showToast('编辑成功')
					}
					this.saveStage = 'navigate'
					await this.runDelayedRedirect(({ success, fail }) => {
						uni.redirectTo({
							url:'/pagesMy/team',
							success,
							fail
						})
					})
				} catch(error) {
					if(!this.pageUnloaded) {
						const fallback = this.saveStage === 'navigate' ? '页面跳转失败，请重试' : '团队编辑失败，请重试'
						const message = error && (error.message || error.msg)
						this.$showToast(message && this.saveStage === 'navigate' ? `页面跳转失败：${message}` : message || fallback)
					}
				} finally {
					this.saving = false
				}
			},
			runDelayedRedirect(invokeRedirect) {
				return new Promise((resolve, reject) => {
					if(this.pageUnloaded) {
						reject(new Error('页面已离开'))
						return
					}
					let settled = false
					const settle = (callback, value) => {
						if(settled) return
						settled = true
						this.navigationTimer = null
						this.navigationReject = null
						callback(value)
					}
					this.navigationReject = error => settle(reject, error)
					this.navigationTimer = setTimeout(() => {
						this.navigationTimer = null
						if(this.pageUnloaded) {
							settle(reject, new Error('页面已离开'))
							return
						}
						try {
							invokeRedirect({
								success: result => {
									if(this.pageUnloaded) settle(reject, new Error('页面已离开'))
									else settle(resolve, result)
								},
								fail: error => settle(reject, new Error(error && (error.errMsg || error.message) || '跳转失败'))
							})
						} catch(error) {
							settle(reject, error)
						}
					},1500)
				})
			},
			cancelPendingRedirect(error) {
				if(this.navigationTimer) clearTimeout(this.navigationTimer)
				this.navigationTimer = null
				const reject = this.navigationReject
				this.navigationReject = null
				if(reject) reject(error || new Error('跳转已取消'))
			}
		}
	}
</script>

<style scoped lang="scss">
	.default_page{
		box-sizing: border-box;
	}
	.dialog{
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, .4);
		z-index: 1000;
		.dbox{
			width: calc(100% - 150rpx);
			background: #FFFFFF;
			border-radius: 32rpx;
			padding: 48rpx 30rpx;
			box-sizing: border-box;
			&-title{
				font-family: PingFang-SC, PingFang-SC;
				font-weight: bold;
				font-size: 34rpx;
				color: #002846;
				line-height: 48rpx;
				text-align: center;
			}
			&-content{
				padding: 0 14rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 32rpx;
				color: #002846;
				line-height: 54rpx;
				text-align: center;
				margin-top: 30rpx;
				span{
					font-weight: bold;
				}
			}
			&-btns{
				margin-top: 56rpx;
				&>view{
					width: calc(50% - 20rpx);
				}
			}
		}
	}
</style>
