<template>
	<view class="container">
		<image class="cbg" :src="base.imgHost('common_bg.png')"></image>
		<!-- <u-divider>个人信息</u-divider> -->
		<view class="wrap">
			<u-form :model="form" :label-width="140" ref="uForm" :label-align="'left'" :error-type="['message']">
				<u-form-item label="姓名" prop="username" required>
					<u-input v-model="form.username" placeholder="请输入姓名" />
				</u-form-item>
				<u-form-item label="性别" prop="sex" required>
					<u-input @click="showSex = true" placeholder="请选择性别" v-model="form.sex" type="select" />
				</u-form-item>
				<!-- <u-form-item label="身份证号" prop="idcard" required>
					<u-input type="idcard" placeholder="请输入身份证号" v-model="form.idcard" /></u-form-item> -->
				<u-form-item label="联系方式" prop="mobile" required>
					<u-input type="number" placeholder="请输入联系方式" v-model="form.mobile" />
				</u-form-item>
				<u-form-item label="出生日期" prop="birthday" required>
					<u-input @click="dateShow=true" placeholder="请选择出生日期" v-model="form.birthday"
						type="select" /></u-form-item>
				<u-form-item label="邮箱" prop="email" required>
					<u-input v-model="form.email" placeholder="请输入邮箱" /></u-form-item>
				<u-form-item label="公司名称" prop="company_name">
					<u-input v-model="form.company_name" placeholder="请输入公司名称" />
				</u-form-item>
				<u-form-item label="职务" prop="company_position">
					<u-input @click="showPosition = true" v-model="form.company_position" type="select"
						placeholder="请选择职务" /></u-form-item>
			</u-form>
			<!-- <u-divider>报名信息</u-divider> -->
			<applyForm ref="applyForm" @backForm="backForm" :course_forms="course_forms"></applyForm>
		</view>

		<!-- <view class="form-btn">
			<view @click="submit" type="primary">提交</view>
		</view> -->
		<u-picker @confirm="selectSex" v-model="showSex" :range="sexList" range-key="value" mode="selector"></u-picker>
		<u-picker @confirm="dateConfirm" mode="time" v-model="dateShow" :params="dateParams"></u-picker>
		<u-picker @confirm="selectPosition" v-model="showPosition" :range="positionList" range-key="value"
			mode="selector"></u-picker>

	</view>
</template>

<script>
	import applyForm from "@/components/applyForm/index.vue"
	export default {
		components: {
			applyForm
		},
		data() {
			return {
				course_id: '',
				showPosition: false,
				positionList: [],
				dateShow: false,
				is_fee: 0, //需不需要缴费这个课程
				dateParams: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				form: {},
				apply_form: [],
				course_forms: [],
				showSex: false,
				sexList: [{
					label: '男',
					value: '男'
				}, {
					label: '女',
					value: '女'
				}],
				rules: {
					username: [{
						required: true,
						message: '请输入姓名',
						trigger: ['blur'],
					}],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: ['change', 'blur'],
					}],
					birthday: [{
						required: true,
						message: '请选择出生日期',
						trigger: ['change', 'blur'],
					}],

					mobile: [{
						required: true,
						message: '请输入联系方式',
						trigger: ['blur'],
					}, {
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['blur'],
					}],
					// idcard: [{
					// 	required: true,
					// 	message: '请输入身份证号',
					// 	trigger: ['blur'],
					// }, {
					// 	validator: (rule, value, callback) => {
					// 		return this.$u.test.idCard(value);
					// 	},
					// 	message: '身份证号不正确',
					// 	trigger: ['blur'],
					// }],
					email: [{
						required: true,
						message: '请输入邮箱',
						trigger: ['blur'],
					}, {
						validator: (rule, value, callback) => {
							return this.$u.test.email(value);
						},
						message: '邮箱不正确',
						trigger: ['blur'],
					}],
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			this.course_id = options.id
			this.getCourseDetail(options.id)
			let user = uni.getStorageSync("stbc1_lifeData") ? uni.getStorageSync("stbc1_lifeData").vuex_user : {}
			this.form = user
			this.getPosition()
		},
		methods: {
			selectSex(e) {
				console.log("e", e)
				this.form.sex = this.sexList[e[0]]['value']
			},
			selectPosition(e) {
				this.form.company_position = this.positionList[e[0]]['value']

			},
			// 日期
			dateConfirm(e) {
				this.form.birthday = e.year + '-' + e.month + '-' + e.day
			},
			getPosition() {
				this.$u.api.getparameter({
					number: 'company_position'
				}).then(res => {
					this.positionList = res.detail
				})
			},
			async getCourseDetail(id) {
				const res = await this.$u.api.courseDetail({
					course_id: id
				})
				if (res.course_forms && res.course_forms.length > 0) {
					this.course_forms = res.course_forms
				}
				this.is_fee = res.is_fee

			},
			backForm(e) {
				let _arr = []
				e.map(item => {
					_arr.push({
						name: item.name,
						field: item.field,
						value: item.value ? item.value : ''
					})
					// 更新扩展字段
					if (item.belong_user === 1) {
						this.form[item.field] = item.value
					}
				})
				this.apply_form = _arr
				console.log("this.apply_form", this.apply_form, this.form)
				// return
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.saveUser()
						this.applyCourse()
					} else {
						console.log('验证失败');
						// this.base.toast("验证失败")
					}
				});

			},
			async saveUser() {
				let that = this
				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)
					// })
				})
			},
			async applyCourse() {
				let that = this
				// let that = this
				await this.$u.api.courseSign({
					course_id: this.course_id,
					data: this.apply_form
				}).then(res => {
					if (this.is_fee) {
						this.newsSubscription()
					} else {
						that.base.toast("报名成功",1500,function(){
							setTimeout(function(){
								uni.redirectTo({
									url: '/packages/mycourse/index'
								})
							},1500)
						})
					}

				})
			},
			// 订阅缴费
			
			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>