<template>
	<view class="interview-container">
		<!-- 顶部导航栏 -->
		<!-- 面试信息 -->
		<!-- <view class="interview-info">
      <view class="info-item">
        <text class="label">面试岗位:</text>
        <text class="value">前端岗位</text>
      </view>
      <view class="info-item">
        <text class="label">面试岗位:</text>
        <text class="value">2024年06月28日 14:48</text>
      </view>
      <view class="info-item">
        <text class="value">2024年06月28日 16:47</text>
      </view>
      <view class="info-item">
        <text class="label">公司全称:</text>
        <text class="value">敏龙科技集团有限公司</text>
      </view>
    </view> -->

		<!-- 职位列表 -->
		<view class="job-list-container" v-if="!userInfoFilled">
			<view class="job-list-title">可选职位列表</view>
			<view class="job-list">
				<view v-for="(job, index) in jobList" :key="index" class="job-item"
					:class="{'job-selected': selectedJobId === job.id}" @click="selectJob(job)">
					<view class="job-name">{{job.title}}</view>
					<view class="job-details">
						<text class="job-salary">{{job.publish_date}}</text>
						<text class="job-location">{{job.location}}</text>
					</view>
				</view>
			</view>

			<button class="apply-btn" :disabled="!selectedJobId" @click="applyForJob">申请面试</button>
		</view>

		<!-- 表单信息 -->
		<view class="form-container" v-if="userInfoFilled">
			<view class="form-title">填写报名信息</view>
			<view class="form-subtitle">如确认报名（此次面试），请填写以下信息</view>

			<view class="form-item">
				<text class="form-label">姓名 <text class="required">*</text></text>
				<input type="text" v-model="formData.name" placeholder="请输入姓名" />
			</view>

			<view class="form-item">
				<text class="form-label">性别 <text class="required">*</text></text>
				<view class="radio-group">
					<view class="radio-item" @click="formData.gender = '男'">
						<view class="radio-circle" :class="{'radio-selected': formData.gender === '男'}"></view>
						<text class="radio-text">男</text>
					</view>
					<view class="radio-item" @click="formData.gender = '女'">
						<view class="radio-circle" :class="{'radio-selected': formData.gender === '女'}"></view>
						<text class="radio-text">女</text>
					</view>
				</view>
			</view>

			<view class="form-item">
				<text class="form-label">身份证号 <text class="required">*</text></text>
				<input type="text" v-model="formData.idCard" placeholder="请输入有效身份证号" maxlength="18" />
			</view>

			<view class="form-item">
				<text class="form-label">手机号 <text class="required">*</text></text>
				<input type="number" v-model="formData.phone" placeholder="请输入手机号" maxlength="11" />
			</view>

			<view class="form-item">
				<text class="form-label">紧急联系人 <text class="required">*</text></text>
				<input type="text" v-model="formData.emergencyContact" placeholder="请输入紧急联系人姓名" />
			</view>

			<view class="form-item">
				<text class="form-label">紧急联系人电话 <text class="required">*</text></text>
				<input type="number" v-model="formData.emergencyPhone" placeholder="请输入紧急联系人电话" maxlength="11" />
			</view>

			<view class="form-item">
				<text class="form-label">与紧急联系人关系 <text class="required">*</text></text>
				<picker @change="relationChange" :value="relationIndex" :range="relationOptions">
					<view class="picker-view">
						<text>{{formData.relation || '请选择关系'}}</text>
						<text class="picker-arrow">▼</text>
					</view>
				</picker>
			</view>

			<view class="agreement">
				<checkbox :checked="isAgreed" @tap="toggleAgreement" color="#6c5ce7" />
				<text class="agreement-text">
					我已阅读并同意
					<text class="agreement-link">《身份验证服务协议》</text>
					<text class="agreement-link">《隐私保护政策》</text>
					<text class="agreement-link">《网络安全协议》</text>
				</text>
			</view>

			<button class="submit-btn" :disabled="!canSubmit" @click="submitForm">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		fillUserInfo,
		getUserInfo,
		getJobList,
		applyJob
	} from '@/api/user';
	export default {
		data() {
			return {
				formData: {
					name: '',
					gender: '',
					phone: '',
					email: '',
					idCard: '',
					emergencyContact: '',
					emergencyPhone: '',
					relation: ''
				},
				relationOptions: ['父母', '配偶', '子女', '兄弟姐妹', '朋友', '其他'],
				relationIndex: 0,
				isAgreed: false,
				userInfoFilled: false,
				jobList: [],
				selectedJobId: null,
				selectedJob: null
			}
		},
		onLoad() {
			this.checkUserInfo();
			this.fetchJobList();
		},
		computed: {
			canSubmit() {
				return this.formData.name.trim() &&
					this.formData.gender &&
					this.formData.phone.trim() &&
					(/^1\d{10}$/.test(this.formData.phone)) &&
					(!this.formData.email || /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.formData.email)) &&
					this.formData.idCard.trim() &&
					this.formData.emergencyContact.trim() &&
					this.formData.emergencyPhone.trim() &&
					(/^1\d{10}$/.test(this.formData.emergencyPhone)) &&
					this.formData.relation &&
					this.isAgreed;
			}
		},
		methods: {
			goHome() {
				uni.navigateBack({
					delta: 1
				});
			},
			toggleAgreement() {
				this.isAgreed = !this.isAgreed;
			},
			relationChange(e) {
				this.relationIndex = e.detail.value;
				this.formData.relation = this.relationOptions[this.relationIndex];
			},
			checkUserInfo() {
				uni.showLoading({
					title: '加载中...'
				});
				console.log('id:', JSON.parse(uni.getStorageSync('userInfo')).id);
				getUserInfo(JSON.parse(uni.getStorageSync('userInfo')).id)
					.then(res => {
						uni.hideLoading();

						if (res.code === 200 && res.data) {
							const userData = res.data;

							if (userData.name && userData.phone) {
								this.userInfoFilled = true;

								this.formData.name = userData.name || '';
								this.formData.gender = userData.gender || '';
								this.formData.phone = userData.phone || '';
								this.formData.idCard = userData.id_card || '';
								this.formData.emergencyContact = userData.emergency_contact || '';
								this.formData.emergencyPhone = userData.emergency_phone || '';
								this.formData.relation = userData.relation || '';

								if (userData.relation) {
									const index = this.relationOptions.findIndex(item => item === userData.relation);
									if (index !== -1) {
										this.relationIndex = index;
									}
								}

								uni.navigateTo({
									url: '/pages/success/success'
								});
							}
						}
					})
					.catch(err => {
						uni.hideLoading();
						console.error('获取用户信息失败:', err);
						uni.showToast({
							title: '获取用户信息失败',
							icon: 'none'
						});
					});
			},
			fetchJobList() {
				uni.showLoading({
					title: '加载职位列表...'
				});

				getJobList()
					.then(res => {
						uni.hideLoading();
						console.log(res);
						this.jobList = res;

					})
					.catch(err => {
						uni.hideLoading();
						console.error('获取职位列表失败:', err);
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					});
			},
			selectJob(job) {
				this.selectedJobId = job.id;
				this.selectedJob = job;
			},
			applyForJob() {
				if (!this.selectedJobId) {
					uni.showToast({
						title: '请选择一个职位',
						icon: 'none'
					});
					return;
				}

				// 保存所选职位信息
				uni.setStorageSync('selectedJob', JSON.stringify(this.selectedJob));
				applyJob({
					job_id: this.selectedJobId,
					tenant_id: 1,
					openid: JSON.parse(uni.getStorageSync('userInfo')).openid
				}).then(res => {
					uni.navigateTo({
				  url: '/pages/interview-notice/interview-notice',
				  fail: (err) => {
				    console.error('页面跳转失败:', err);
				    uni.showToast({
				      title: '页面跳转失败',
				      icon: 'none'
				    });
				  }
				});
				}).catch(err => {
					console.error('申请职位失败:', err);
				});
				
				// 显示填写个人信息表单
				// this.userInfoFilled = true;
			},
			submitForm() {
				if (!this.formData.name.trim()) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.gender) {
					uni.showToast({
						title: '请选择性别',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.phone.trim()) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}

				if (!/^1\d{10}$/.test(this.formData.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

				if (this.formData.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.formData.email)) {
					uni.showToast({
						title: '请输入正确的邮箱',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.idCard.trim()) {
					uni.showToast({
						title: '请输入身份证号',
						icon: 'none'
					});
					return;
				}

				const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
				if (!idCardReg.test(this.formData.idCard)) {
					uni.showToast({
						title: '请输入正确的身份证号',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.emergencyContact.trim()) {
					uni.showToast({
						title: '请输入紧急联系人',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.emergencyPhone.trim()) {
					uni.showToast({
						title: '请输入紧急联系人电话',
						icon: 'none'
					});
					return;
				}

				if (!/^1\d{10}$/.test(this.formData.emergencyPhone)) {
					uni.showToast({
						title: '请输入正确的紧急联系人电话',
						icon: 'none'
					});
					return;
				}

				if (!this.formData.relation) {
					uni.showToast({
						title: '请选择与紧急联系人关系',
						icon: 'none'
					});
					return;
				}

				if (!this.isAgreed) {
					uni.showToast({
						title: '请阅读并同意相关协议',
						icon: 'none'
					});
					return;
				}

				const submitData = {
					openid: JSON.parse(uni.getStorageSync('userInfo')).openid || '',
					name: this.formData.name,
					phone: this.formData.phone,
					id_card: this.formData.idCard,
					status: 1,
					source: 'mini',
					examine: 0,
					tenant_id: '1',
					emergency_contact: this.formData.emergencyContact,
					emergency_phone: this.formData.emergencyPhone,
					relation: this.formData.relation,
					age: '20',
					job_id: this.selectedJobId
				};

				uni.showLoading({
					title: '提交中...'
				});

				fillUserInfo(submitData)
					.then(res => {
						uni.hideLoading();
							this.updateLocalUserInfo();

							uni.showToast({
								title: '提交成功',
								icon: 'success',
								duration: 1500,
								success: () => {
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/success/success',
											fail: (err) => {
												console.error('页面跳转失败:', err);
												uni.showToast({
													title: '页面跳转失败',
													icon: 'none'
												});
											}
										});
									}, 1500);
								}
							});
						// } else {
						// 	uni.showToast({
						// 		title: res.msg || '提交失败，请重试',
						// 		icon: 'none'
						// 	});
						// }
					})
					.catch(err => {
						uni.hideLoading();
						console.error('提交表单失败:', err);
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					});
			},
			updateLocalUserInfo() {
				getUserInfo()
					.then(res => {
						if (res.code === 200 && res.data) {
							let userInfo = {};
							try {
								userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
							} catch (e) {
								console.error('解析本地存储用户信息失败:', e);
								userInfo = {};
							}

							const updatedUserInfo = {
								...userInfo,
								...res.data
							};

							uni.setStorageSync('userInfo', JSON.stringify(updatedUserInfo));
						}
					})
					.catch(err => {
						console.error('更新本地用户信息失败:', err);
					});
			}
		}
	}
</script>

<style>
	.interview-container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f5f7fa;
	}

	.nav-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #6c5ce7;
		color: #fff;
	}

	.scan-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #ff9f43;
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
	}

	.interview-info {
		background-color: #6c5ce7;
		color: #fff;
		padding: 20rpx 30rpx 40rpx;
	}

	.info-item {
		margin: 10rpx 0;
		font-size: 28rpx;
	}

	.label {
		margin-right: 10rpx;
	}

	.form-container {
		flex: 1;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		margin-top: -20rpx;
		padding: 40rpx 30rpx;
	}

	.form-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.form-subtitle {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 40rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}

	.required {
		color: #ff4757;
	}

	input {
		width: 100%;
		height: 80rpx;
		border: 1px solid #eee;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}

	.submit-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #6c5ce7;
		color: #fff;
		border-radius: 45rpx;
		font-size: 32rpx;
		margin-top: 60rpx;
	}

	.agreement {
		display: flex;
		align-items: flex-start;
		margin-top: 20rpx;
	}

	.agreement-text {
		font-size: 24rpx;
		color: #666;
		line-height: 1.5;
		margin-left: 10rpx;
	}

	.agreement-link {
		color: #6c5ce7;
	}

	.submit-btn[disabled] {
		background-color: #b2b2b2;
		color: #fff;
	}

	.radio-group {
		display: flex;
		flex-direction: row;
		margin-top: 10rpx;
	}

	.radio-item {
		display: flex;
		align-items: center;
		margin-right: 60rpx;
	}

	.radio-circle {
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		border: 2rpx solid #999;
		margin-right: 10rpx;
		position: relative;
	}

	.radio-selected {
		border-color: #6c5ce7;
	}

	.radio-selected:after {
		content: '';
		position: absolute;
		width: 24rpx;
		height: 24rpx;
		background-color: #6c5ce7;
		border-radius: 50%;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.radio-text {
		font-size: 28rpx;
	}

	.picker-view {
		width: 100%;
		height: 80rpx;
		border: 1px solid #eee;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.picker-arrow {
		font-size: 24rpx;
		color: #999;
	}

	/* 职位列表样式 */
	.job-list-container {
		flex: 1;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		margin-top: -20rpx;
		padding: 40rpx 30rpx;
	}

	.job-list-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
	}

	.job-list {
		max-height: 800rpx;
		overflow-y: auto;
	}

	.job-item {
		padding: 30rpx;
		border-radius: 12rpx;
		background-color: #f8f9fa;
		margin-bottom: 20rpx;
		border: 2rpx solid transparent;
	}

	.job-selected {
		border-color: #6c5ce7;
		background-color: rgba(108, 92, 231, 0.1);
	}

	.job-name {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.job-details {
		display: flex;
		justify-content: space-between;
		font-size: 24rpx;
		color: #666;
	}

	.job-salary {
		color: #ff6b6b;
	}

	.apply-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #6c5ce7;
		color: #fff;
		border-radius: 45rpx;
		font-size: 32rpx;
		margin-top: 40rpx;
	}

	.apply-btn[disabled] {
		background-color: #b2b2b2;
		color: #fff;
	}
</style>