<template>
	<view class="container">
		<image class="cbg" :src="base.imgHost('common_bg.png')"></image>
		<!-- <u-divider>个人信息</u-divider> -->
		<view class="wrap">
			<applyForm ref="applyForm" @backForm="backForm" :course_forms="course_forms"></applyForm>
		</view>

	</view>
</template>

<script>
	import applyForm from "@/components/applyForm/index.vue"
	export default {
		components: {
			applyForm
		},
		data() {
			return {
				course_id: '',

				is_fee: 0, //需不需要缴费这个课程
				form: {},
				apply_form: [],
				course_forms: [],
				sign_id: '', // 报名的id
				opType: 'add', // edit 修改
				isLocked: false,
				change_data:[], // 记录报名表中填写的字段和 form学员信息中不同的
				is_change:0
			}
		},
		onReady() {
			// this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			this.course_id = options.id
			if (options.type === 'edit') {
				this.opType = 'edit'
				this.getCourseDetail(options.id)
				// this.getSignDetail(options.id)
			} else {
				this.getCourseDetail(options.id)
			}
			let user = uni.getStorageSync("stbc1_lifeData") ? uni.getStorageSync("stbc1_lifeData").vuex_user : {}
			this.form = user
			// this.getPosition()
		},
		methods: {
			async getCourseDetail(id) {
				const res = await this.$u.api.courseDetail({
					course_id: id
				})
				if (res.course_forms && res.course_forms.length > 0) {
					res.course_forms.map(item => {
						if (item.belong_user === 1) {
							item.value = this.form[item.field]
						}
						if (item.value === null) {
							item.value = ''
						}
					})
					this.course_forms = res.course_forms.sort((a, b) => (a.sort - b.sort))
				}
				this.is_fee = res.is_fee
				if(this.opType == 'edit'){
					this.getSignDetail(id)
				}
			},
			// 修改
			async getSignDetail(id) {
				const res = await this.$u.api.courseGetSign({
					course_id: id
				})
				this.sign_id = res.detail.id
				if (res.detail.data && res.detail.data.length > 0) {
					res.detail.data.map(item => {
						this.course_forms.map(forms=>{
							if(item.field==forms.field){
								forms.value = item.value?item.value:''
							}
						})
						
						// if (item.value === null) {
						// 	item.value = ''
						// }
					})
					// this.course_forms = res.detail.data.sort((a, b) => (a.sort - b.sort))
				}
			},
			async backForm(e) {
				let _arr = []
				let that = this
				let change_data_arr = []
				e.map(item => {
					// _arr.push({
					// 	name: item.name,
					// 	field: item.field,
					// 	value: item.value ? item.value : ''
					// })
					item.value = item.value ? item.value : ''
					_arr.push(item)
					// 更新学员user表中的字段 学员字段有值
					
					if (item.belong_user === 1 && !this.base.isNull(item.value)) {
						if(this.form[item.field]!=item.value){
							console.log('item.field',item.field)
							change_data_arr.push({[item.field]:item.value})
							
						}
						// this.form[item.field] = item.value
					}
				})
				this.apply_form = _arr
				
				this.change_data = change_data_arr
				console.log("this.apply_form", this.apply_form, this.form,this.change_data)
				// return
				this.is_change = 0
				if(this.change_data.length>0){
					this.is_change = 1
					if (that.isLocked) {
						return
					}
					that.isLocked = true
					uni.showModal({
						title: '提示',
						content:'您当前提交的报名信息与往期数据存在差异，是否确认继续提交报名？',
						confirmText:'提交报名',
						cancelText:'取消',
						success: function(res) {
							if(res.confirm){
								// 比对一下提交的信息和 user表中的数据是否不一样
								//课程报名接口增加is_change字段，是否用户数据发生变化，0否1是
								// change_data字段，传入新修改的用户信息
								
								// return
								// await this.saveUser()
								if (that.opType == 'edit') {
									that.updateApplyCourse()
								} else {
								    that.applyCourse()
								}
							}else{
								that.isLocked = false
								that.change_data = {}
								that.is_change = 0
							}
						}
					})
				}else{
					that.is_change = 0
					if (that.isLocked) {
						return
					}
					that.isLocked = true
					// await this.saveUser()
					
					if (that.opType == 'edit') {
						that.updateApplyCourse()
					} else {
					    that.applyCourse()
					}
				}
				
			},
			async saveUser() {
				let that = this
				this.form.name = this.form.username
				await this.$u.api.saveUser(this.form).then(res => {
					console.log("user")
					// this.$u.api.user().then(res => {
					// 	this.$u.vuex('vuex_user', res.user)
					// })
				}).catch(err => {
					console.log("err", err)
					that.isLocked = false
				})
			},
			async applyCourse() {
				let that = this
				await this.$u.api.courseSign({
					course_id: this.course_id,
					data: this.apply_form,
					change_data:this.change_data,
					is_change:this.is_change
				}).then(res => {
					if (this.is_fee) {
						this.newsSubscription()
					} else {
						that.base.toast("报名已提交", 1500, function() {
							setTimeout(function() {
								uni.redirectTo({
									url: '/packages/mycourse/index'
								})
							}, 1500)
						})
					}

				}).catch(err => {
					console.log("err", err)
					that.isLocked = false
				})
			},
			// 更新报名信息
			async updateApplyCourse() {
				let that = this
				this.$u.api.courseUpdateSign({
					id: this.sign_id,
					data: this.apply_form,
					change_data:this.change_data,
					is_change:this.is_change
				}).then(res => {
					that.base.toast("修改成功", 1500, function() {
						setTimeout(function() {
							uni.navigateBack({
								delta:1
							})
						}, 1500)
					})
				}).catch(err => {
					console.log("err", err)
					that.isLocked = false
				})
			},
			// 订阅缴费

			newsSubscription() {
				let that = this
				uni.getSetting({
					withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
					success(res) {
						console.log("resdfg", res)
						if (res.subscriptionsSetting.mainSwitch) {
							if (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings[
									'6bkRNahvR88pG4Tpk0c2aY81kszvFpdaIV-CdC_ENTM'] === 'accept' &&
								res.subscriptionsSetting.itemSettings[
									'XsR1BJRdE8JtFUC1o3w7DDcscXkCEGu62J8_smMofZI'] === 'accept'
							) {
								console.log("accept")
								// 用户已经订阅该消息模板，执行相应操作
								that.base.toast("报名已提交", 1500, function() {
									setTimeout(function() {
										uni.redirectTo({
											url: '/packages/mycourse/index'
										})
									}, 1500)

								})
							} else {
								// 用户没有订阅该消息模板，显示订阅弹窗
								uni.showModal({
									title: '订阅消息',
									content: '是否需要订阅预约结果消息',
									success(res1) {
										if (res1.confirm) {
											uni.requestSubscribeMessage({
												tmplIds: [
													'6bkRNahvR88pG4Tpk0c2aY81kszvFpdaIV-CdC_ENTM',
													'XsR1BJRdE8JtFUC1o3w7DDcscXkCEGu62J8_smMofZI',
												],
												success(res) {
													that.base.toast("报名已提交", 1500, function() {
														setTimeout(function() {
															uni.redirectTo({
																url: '/packages/mycourse/index'
															})
														}, 1500)

													})
												},
												fail(err) {
													that.base.toast("报名已提交", 1500, function() {
														setTimeout(function() {
															uni.redirectTo({
																url: '/packages/mycourse/index'
															})
														}, 1500)

													})
												}
											})
										} else {
											that.base.toast("报名已提交", 1500, function() {
												setTimeout(function() {
													uni.redirectTo({
														url: '/packages/mycourse/index'
													})
												}, 1500)
											})
										}
									}
								})

							}
						} else {
							console.log("9999")
							that.base.toast("报名已提交", 1500, function() {
								setTimeout(function() {
									uni.redirectTo({
										url: '/packages/mycourse/index'
									})
								}, 1500)

							})
							// 用户尚未开启订阅消息总开关，建议提醒用户开启
						}
					}
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding: 30rpx;
		height: 100vh;

		.cbg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100vh;
		}

		.wrap {
			background-color: #fff;
			padding: 20rpx 50rpx;
			border-radius: 20rpx;
			position: relative;
			height: 100%;
			overflow: scroll;
		}

		.form-btn {
			width: 100%;
			position: fixed;
			left: 0;
			bottom: 0;
			padding: 20rpx 0;

			&>view {
				width: 70%;
				text-align: center;
				margin: 0 auto;
				color: #fff;
				background: linear-gradient(to right, #5e5fbc, #0d0398);
				border-radius: 30rpx;
				padding: 20rpx;
			}
		}
	}
</style>