<template>
	<view class="content">
		<view class="page-top" :style='{ justifyContent: "center" }'>
			<view class='go-back-page' @click='pageBack'>返回</view>
			<view class="other-title-class">
				{{ titles }}
			</view>
		</view>
		<view class="container">

			<view class="box_">
				<view class="d_s" style="margin-bottom: 10px;" v-if="userId">
					<view class="touxiang_" v-if="staff.avatar">
						<!-- <image src="/static/imgs/yh.png" mode=""></image> -->
						<image :src=" imgUrl + staff.avatar" mode="" @click="previewImage(imgUrl + staff.avatar)">
						</image>
					</view>
					<view class="touxiang_" v-else>
						<!-- <image src="/static/imgs/yh.png" mode=""></image> -->
						<image src="/static/imgs/yh.png"></image>
					</view>
					<view class="">
						<view class="name_">{{ staff.name }}</view>
						<view class="d_s">
							<view class="tel_">
								<image src="/static/imgs/tel.png" mode=""></image>
							</view>
							<view class="telnum">手机号：{{ staff.phone }}</view>
						</view>
					</view>
				</view>
				<view class="d_b" v-if="!userId">
					<view class="">姓名</view>
					<input type="text" placeholder="请输入姓名" v-model="staff.name" style="text-align: right;" />
				</view>
				<view class="d_b" v-if="!userId">
					<view class="">手机号</view>
					<input type="text" placeholder="请输入手机号" v-model="staff.phone" style="text-align: right;" />
				</view>
				<view class="d_b">
					<view class="">学员编号</view>
					<input type="text" placeholder="请输入学员编号" v-model="staff.drivingStudentCode"
						style="text-align: right;" />
				</view>
				<view class="d_b">
					<view class="">身份证号</view>
					<input type="text" placeholder="请输入身份证号" v-model="staff.idCard" style="text-align: right;" />
				</view>
				<view class="d_b">
					<view class="">年龄</view>
					<input type="text" placeholder="请输入年龄" v-model="staff.age" style="text-align: right;" />
				</view>
				<view class="d_b">
					<view class="">性别</view>
					<picker :range="genderOptions" @change="onGenderChange" :value="genderIndex">
						<view class="picker">
							{{ genderOptions[genderIndex] }}
						</view>
					</picker>
				</view>
				<!-- <view class="d_b">
					<view class="">来源</view>
					<input type="text" placeholder="暂无数据" v-model="staff.source" disabled style="text-align: right;" />
				</view> -->
				<view class="d_b">
					<view>来源</view>
					<text style="text-align: right;">{{ getSourceText(staff.source) }}</text>
				</view>

				<view class="d_b_1">
					<view class="label">户籍地址</view>
					<textarea placeholder="请输入户籍地址" v-model="staff.regAddress" class="multiline-input"></textarea>
				</view>
				<view class="d_b_1">
					<view class="label">家庭住址</view>
					<textarea placeholder="请输入家庭住址" v-model="staff.address" class="multiline-input"></textarea>
				</view>



				<view class="d_b" @click="goFile" v-if="userId">
					<view class="">附件</view>
					<view class="lan_">查看附件
						<image src="/static/imgs/add.png" mode=""></image>
					</view>
				</view>

				<view class="anniu" @click="submit">
					{{ buttonTile }}
				</view>
			</view>
		</view>

		<!-- <qianziyu-select :show="showGenderPicker" type="radio" name="label" :dataLists="genderOptions"
			:showSearch="false" popupTitle="选择性别" @submit="chooseGender" @cancel="showGenderPicker = false">
		</qianziyu-select> -->
		<qianziyu-select :show="showGenderPicker" type="radio" name="label" :dataLists="genderOptions"
			:showSearch="false" popupTitle="选择性别" @submit="handleGenderSubmit" @cancel="closeGenderPicker">
		</qianziyu-select>

	</view>
</template>

<script>
	// import headersVue from '../../components/header/headers.vue';
	import request from "@/utils/request";
	import {
		formatDate
	} from "@/utils/utils";
	import upload from "@/utils/upload";
	import config from "@/config";
	import QianziyuSelect from '@/components/qianziyu-select/qianziyu-select.vue'
	export default {
		components: {
			QianziyuSelect
		},
		data() {
			return {
				titles: "新增员工",
				staff: {
					joinDate: null,
					probationPeriod: null,
					socialSecurityBuyDate: null,
					roleIds: []
				},
				fileList1: [],
				selectJoinDate: new Date().toString(),
				selectProbationPeriod: new Date().toString(),
				selectSocialSecurityBuyDate: new Date().toString(),
				buttonTile: '保存',
				show: false,
				showRole: false,
				status: 'loading',
				userId: undefined,
				showEducation: false,
				showJoinedDate: false,
				showFormalDate: false,
				showSafeDate: false,
				showDriveType: false,
				educations: [],
				roles: [],
				driverLicenseType: [],
				driverLicenseTypeArr: [],
				driverLicenseTypeArrStr: null,
				roleName: null,
				genderOptions: ['男', '女'], // 用于显示
				genderIndex: 0,
				scrollHeight: 'auto',
				showGenderPicker: false,
				imgUrl: config.imagesUrl,
			}
		},
		onLoad(data) {
			if (data.id) {
				this.titles = '编辑学员'
				this.userId = data.id
				this.getInfoByUserId()
				this.buttonTile = '修改'
			}

		},
		mounted() {
			// 动态计算高度
			this.calculateHeight()
		},
		methods: {
			cancelShow() {
				this.show = !this.cancelShow
			},
			onsubmit(selectedData) {
				selectedData.map(item => item.id);
				this.driverLicenseTypeArr = selectedData;
				this.driverLicenseTypeArrStr = selectedData.map(item => item.id).join(',');
				this.showDriveType = false; // 提交后关闭弹窗
			},

			onGenderChange(e) {
				this.genderIndex = e.detail.value;
				this.staff.sex = e.detail.value.toString(); // '0' 或 '1'
			},
			/* submit() {
				//判断是否是修改
				if (this.userId) {
					this.update()
				} else {
					this.add()
				}
			}, */
			async submit() {
				if (this.userId) {
					try {
						uni.showLoading({
							title: '提交中...',
							mask: true
						});

						const result = await this.update();
						console.log('接口返回数据：', result);

						if (result.code === 200) {
							uni.showToast({
								title: '修改成功',
								icon: 'success',
								duration: 1500
							});
							setTimeout(() => this.pageBack(), 1500);
						} else {
							throw new Error(result.msg || '操作失败');
						}
					} catch (error) {
						uni.showToast({
							title: error.message || '修改失败，请重试',
							icon: 'none',
							duration: 2000
						});
					} finally {
						uni.hideLoading();
					}
				} else {
					this.add();
				}
			},

			async update() {
				if (!this.validData()) {
					return Promise.reject(new Error('请填写完整信息'));
				}

				const data = {
					...this.staff,
					userId: this.userId,
					fileList: this.fileList1.map(item => ({
						...item,
						url: item.url.replace(/^https?:\/\/[^/]+\/minio\//, '')
					})),
					driverLicenseType: this.driverLicenseTypeArrStr,
					driverLicenseTypeArr: this.driverLicenseTypeArr.map(item => item.id)
				};

				const response = await request({
					url: '/admin-api/base/dl-drive-school-student/update',
					method: 'put',
					data: data
				});

				if (!response) {
					throw new Error('请求无响应');
				}

				return response;
			},
			/* update() {
				// 验证表单信息
				const flag = this.validData()
				if (!flag) {
					return
				}

				this.staff.userId = this.userId
				const data = {
					...this.staff,
					fileList: this.fileList1
						.map(item => {
							item.url = item.url.replace(/^https?:\/\/[^/]+\/minio\//, '');
							return item;
						}), // 去除域名和 minio/
					driverLicenseType: this.driverLicenseTypeArrStr,
					driverLicenseTypeArr: this.driverLicenseTypeArr.map(item => item.id)
				}

				// request({
				// 	url: '/admin-api/base/dl-drive-school-student/update',
				// 	method: 'put',
				// 	data: data
				// }).then(res => {

				// 	uni.showToast({
				// 		title: "编辑成功"
				// 	})
				// 	// uni.navigateBack()
				// 	this.pageBack()
				// })
				const res = request({
					url: '/admin-api/base/dl-drive-school-student/update',
					method: 'put',
					data: data
				});

				// 检查响应是否成功
				if (res.code !== 0) {
					throw new Error(res.message || '服务器返回错误');
				}

				return res;
			}, */
			calculateHeight() {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync()
				// 计算可用高度（可根据实际情况调整）
				this.scrollHeight = `${systemInfo.windowHeight - 130}px`
			},

			// 打开性别选择器
			openGenderPicker() {
				this.showGenderPicker = true
			},

			// 关闭性别选择器
			closeGenderPicker() {
				this.showGenderPicker = false
			},
			// 处理性别选择提交
			handleGenderSubmit(selectedData) {
				this.genderIndex = selectedData[0].index
				this.staff.sex = this.genderIndex.toString()
				this.closeGenderPicker()
			},
			/* async add() {
				// 验证表单信息
				const flag = this.validData()
				if (!flag) {
					return
				}
				let data = {
					nickname: this.staff.nickname,
					mobile: this.staff.mobile,
					username: this.staff.mobile,
					status: 0,
					userType: '01',
					roleId: this.staff.roleId,
					name: this.nickname,
					joinDate: this.staff.joinDate,
					idCard: this.staff.idNumber,
					age: this.staff.age,
					sex: this.staff.sex,
					educational: this.staff.educational,
					probationPeriod: this.staff.probationPeriod,
					socialSecurityBuyDate: this.staff.socialSecurityBuyDate,
					driverLicenseTypeArr: this.driverLicenseTypeArr.map(item => item.id),
					password: '123456',
					regAddress: this.staff.regAddress,
					address: this.staff.address,
					seniority: this.staff.seniority,
					instructorDesc: this.staff.instructorDesc
				}
				let res = await request({
					url: '/admin-api/base/dl-drive-school-coach/saveNew',
					method: 'post',
					data: data
				})
				if (res.code == 200) {
					console.log('角色', res)
					let resp = await request({
						url: '/admin-api/system/permission/assign-user-role',
						method: 'post',
						data: {
							userId: res.data,
							roleIds: this.staff.roleIds
						}
					})
					uni.showToast({
						title: "添加成功"
					})
					this.show = false
					this.getindex()
					uni.navigateBack()
				}
			}, */
			validData() {
				if (!this.staff.name || !this.staff.phone) {
					uni.showToast({
						title: '姓名和电话不能有空',
						icon: 'none'
					})
					return false
				}
				return true
			},



			goFile() {
				if (!this.userId) {
					uni.showToast({
						title: '请先新建员工',
						icon: 'none'
					})
					return
				}
				if (!this.staff.folderId) {
					console.log('当前员工没有文件夹')
					//给当前员工创建一个文件夹
					request({
						url: '/admin-api/inspectionStaff/addFolder',
						method: 'post',
						data: this.userId
					}).then(res => {
						this.staff.folderId = res.data
						uni.navigateTo({
							url: '/pages/internalManagement/dataManagement/deviceManage?type=staff&folderId=' +
								this.staff.folderId
						})
					})
				} else {
					uni.navigateTo({
						url: '/pages/internalManagement/dataManagement/deviceManage?type=staff&folderId=' + this
							.staff.folderId
					})
				}

			},
			previewImage(currentUrl) {
				if (!currentUrl) {
					uni.showToast({
						title: '图片无效',
						icon: 'none'
					});
					return;
				}
				uni.previewImage({
					current: currentUrl, // 当前图片 URL
					urls: [currentUrl], // 所有图片的 URL 数组（如果是单张图片，直接传数组）
					success: () => console.log('预览成功'),
					fail: (err) => console.error('预览失败:', err)
				});
			},

			pageBack() {
				uni.navigateBack({
					delta: 1 // delta值为1时表示返回的页面层数
				});
			},

			getSourceText(code) {
				const map = {
					'01': '驾校统招',
					'02': '教练自招',
					'03': '自来客户'
				};
				return map[code] || '-';
			},

			// 获取角色信息的方法
			async getInfoByUserId() {
				const res = await request({
					url: '/admin-api/base/dl-drive-school-student/getByUserId',
					params: {
						id: this.userId
					},
					method: 'get'
				});

				this.staff = res.data;
				console.log('staff', this.staff)
				this.genderIndex = parseInt(this.staff.sex || '0');
			}

		},
	}
</script>

<style scoped lang="scss">
	.content {
		background: #f4f5f6;
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.container {
		/* width: 100%;
		background: #f4f5f6;
		box-sizing: border-box;
		padding: 30rpx;
		// padding-top: 200rpx;
		padding-bottom: 28px; */
		flex: 1;
		overflow-y: auto;
		width: 100%;
		background: #f4f5f6;
		box-sizing: border-box;
		padding: 30rpx;
		padding-bottom: 28px;
	}

	.box_ {
		background: #FFFFFF;
		width: 100%;
		box-sizing: border-box;
		padding: 30rpx;
		border-radius: 8rpx;
	}

	.d_s {
		display: flex;
		align-items: center;

	}

	.d_b {
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 30rpx 0rpx;
		border-top: 2rpx solid #F5F6F9;
		font-size: 28rpx;
		color: #8D90A6;

	}

	.textarea {
		flex: 1;
		text-align: right;
		font-size: 28rpx;
		color: #333;
		padding: 10rpx;
		border: none;
		background-color: transparent;
		resize: none;
		overflow: hidden;
		/* 防止滚动条 */
		min-height: 60rpx;
	}

	.touxiang_ {
		width: 90rpx;
		height: 90rpx;
		margin-right: 20rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.tel_ {
		width: 30rpx;
		height: 30rpx;
		margin-right: 20rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.name_ {
		font-size: 32rpx;
		color: #101A3E;
		margin-bottom: 5px;
	}

	.telnum {
		font-size: 24rpx;
		color: #366FFF;
	}

	.lan_ {
		font-size: 28rpx;
		color: #327DFB;
		display: flex;
		align-items: center;

		image {
			width: 36rpx;
			height: 36rpx;
			margin-left: 15rpx;
		}
	}

	.hui_box {
		width: 100%;
		background: #F5F6F9;
		border-radius: 16rpx;
		box-sizing: border-box;
		padding: 30rpx;
		display: flex;
		align-items: center;

		image {
			width: 90rpx;
			height: 90rpx;
			margin-right: 15rpx;
		}
	}

	.big_ {
		font-size: 28rpx;
		color: #101A3E;
	}

	.sm_ {
		font-size: 22rpx;
		color: #8D90A6;
	}

	.anniu {
		width: 622rpx;
		height: 78rpx;
		background: #427FFE;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		margin-top: 80rpx;
	}

	.page-top {
		flex-shrink: 0;
		width: 100%;
		height: 160rpx;
		display: flex;
		align-items: center;
		color: white;
		flex-shrink: 0;
		background: linear-gradient(180deg, #054DF3 0%, #55A3FF 100%);

		.go-back-page {
			position: absolute;
			left: 20rpx;
		}
	}

	.container::-webkit-scrollbar {
		display: none;
		/* 隐藏滚动条 */
	}

	.d_b_1 {
		display: flex;
		align-items: flex-start;
		/* 改为顶部对齐 */
		justify-content: space-between;
		box-sizing: border-box;
		padding: 30rpx 0;
		border-top: 2rpx solid #F5F6F9;
		font-size: 28rpx;
		color: #8D8D8D;
	}

	.label {
		width: 150rpx;
		/* 给标签固定宽度 */
		flex-shrink: 0;
		/* 防止标签被压缩 */
	}

	.multiline-input {
		text-align: right;
		width: 400rpx;
		max-height: 110rpx;
		min-height: 100rpx;
		border: none;
		resize: none;
		line-height: 1.5;
		font-size: 28rpx;
		padding: 0;
	}

	.multiline-textarea {
		text-align: right;
		width: 400rpx;
		max-height: 200rpx;
		min-height: 120rpx;
		border: none;
		resize: none;
		line-height: 1.5;
		font-size: 28rpx;
		padding: 0;
	}
</style>
