<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=" imgUrl + staff.avatar" mode="" @click="previewImage(imgUrl + staff.avatar)">
						</image>
					</view>
					<view class="touxiang_" v-else>
						<image src="/static/imgs/yh.png"></image>
					</view>
					<view class="">
						<view class="name_">{{ staff.nickname }}</view>
						<view class="d_s">
							<view class="tel_">
								<image src="/static/imgs/tel.png" mode=""></image>
							</view>
							<view class="telnum">手机号：{{ staff.mobile }}</view>
						</view>
					</view>
				</view>
				<view class="d_b" v-if="!userId">
					<view class="">姓名</view>
					<input type="text" placeholder="请输入姓名" v-model="staff.nickname" style="text-align: right;" />
				</view>
				<view class="d_b" v-if="!userId">
					<view class="">手机号</view>
					<input type="text" placeholder="请输入手机号" v-model="staff.mobile" 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.age" style="text-align: right;" />
				</view>
				<!-- 新增员工类型选择 -->
				<view class="d_b">
					<view class="">员工类型</view>
					<view class="" @click="showStaffTypePicker = true">
						{{ getStaffTypeLabel(staff.staffType) || '请选择员工类型' }}
					</view>
				</view>
				<view class="d_b">
					<view class="">岗位</view>
					<view class="" @click="showRole = true">
						{{ roleNames.length > 0 ? roleNames.join('、') : '请选择岗位' }}
					</view>
				</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>

		<u-picker :show="showEducation" ref="uPicker" :columns="[educations]" @confirm="chooseEducation"
			@cancel="showEducation = false" keyName="label"></u-picker>

		<qianziyu-select :show="showDriveType" type="checkbox" name="id" :dataLists="driverLicenseType"
			:showSearch=false @cancel="showDriveType = false" :checkboxData="driverLicenseTypeArr" @submit="onsubmit"
			@update:checkboxData="driverLicenseTypeArr = $event">
		</qianziyu-select>

		<u-datetime-picker :show="showJoinedDate" v-model="selectJoinDate" @cancel="showJoinedDate = false"
			@confirm="chooseJoinDate" mode="date" return-type='string'></u-datetime-picker>
		<u-datetime-picker :show="showFormalDate" v-model="selectProbationPeriod" @cancel="showFormalDate = false"
			@confirm="chooseFormalDate" mode="date" return-type='string'></u-datetime-picker>
		<u-datetime-picker :show="showSafeDate" v-model="selectSocialSecurityBuyDate" @cancel="showSafeDate = false"
			@confirm="chooseSafeDate" mode="date" return-type='string'></u-datetime-picker>

		<!-- 岗位选择器 -->
		<qianziyu-select :show="showRole" type="checkbox" name="name" :dataLists="postOptions" :showSearch="false"
			@cancel="showRole = false" @submit="handleRoleSubmit" popupTitle="选择岗位"
			:checkboxData="selectedRoles"></qianziyu-select>

		<!-- 员工类型选择器 -->
		<qianziyu-select :show="showStaffTypePicker" type="radio" name="label" :dataLists="staffTypeOptions"
			:showSearch="false" popupTitle="选择员工类型" @submit="handleStaffTypeSubmit" @cancel="closeStaffTypePicker">
		</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 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: [],
					staffType: null
				},
				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: [],
				postOptions: [], // 岗位选项
				driverLicenseType: [],
				driverLicenseTypeArr: [],
				driverLicenseTypeArrStr: null,
				roleName: null,
				roleNames: [], // 改为存储多个岗位名称
				selectedRoles: [], // 存储已选中的岗位对象
				genderOptions: ['男', '女'],
				genderIndex: 0,
				scrollHeight: 'auto',
				showGenderPicker: false,
				imgUrl: config.baseImageUrlNew,
				ifAdd: null,
				showStaffTypePicker: false,
				// 员工类型选项
				staffTypeOptions: [],
			}
		},
		onLoad(data) {
			console.log('data', data)
			if (data.id) {
				this.titles = '编辑员工'
				this.userId = data.id
				this.getInfoByUserId()
				this.buttonTile = '修改'
			}
			if (data.ifAdd) {
				this.ifAdd = data.ifAdd
			}
			this.getEducation()
			this.getPosts() // 获取岗位列表
			this.getStaffType()
		},
		methods: {
			cancelShow() {
				this.show = !this.cancelShow
			},
			// 获取岗位列表
			async getPosts() {
				let res = await request({
					url: '/system/role/pageByQuery',
					method: 'get',
					params: {
						servicePackageId: 'jiuyuan'
					}
				})
				this.postOptions = res.data
			},
			async getStaffType() {
				let res = await request({
					url: '/rescue/dict/data/type/rescue_staff_type',
					method: 'get',

				}).then((res) => {
					this.staffTypeOptions = res.data
					console.log('staffTypeOptions', res);
				})
			},
			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();
			},
			submit() {
				const roleIds = Array.isArray(this.staff.roleIds) ?
					this.staff.roleIds.map(id => typeof id === 'object' ? id.id : id) : [];
				if (this.userId) {
					this.update()
				} else {
					this.add()
				}
			},
			update() {
				// 验证表单信息
				const flag = this.validData()
				if (!flag) {
					return
				}

				this.staff.userId = this.userId
				const data = {
					...this.staff,
					id: this.staff.driverId,
					fileList: this.fileList1
						.map(item => {
							item.url = item.url.replace(/^https?:\/\/[^/]+\/minio\//, '');
							return item;
						}),
					driverLicenseType: this.driverLicenseTypeArrStr,
					driverLicenseTypeArr: this.driverLicenseTypeArr.map(item => item.id),
					staffType: this.staff.staffType,
					roleIds: this.staff.roleIds,
					phonenumber: this.staff.mobile
				}
				console.log('update data', data)

				request({
					url: '/system/rescueInfo/updateDriverNew',
					method: 'post',
					data: data
				}).then(res => {
					uni.showToast({
						title: "编辑成功"
					})
					this.pageBack()
				})
			},
			async add() {
				// 验证表单信息
				const flag = this.validData()
				if (!flag) {
					return
				}
				let data = {
					realName: this.staff.nickname,
					// phonenumber: this.staff.mobile,
					age: this.staff.age,
					sex: this.staff.sex,
					staffType: this.staff.staffType,
					roleIds: this.staff.roleIds,
					phonenumber: this.staff.mobile
				}
				console.log('add data', data)
				let res = await request({
					url: '/system/rescueInfo/addDriverAppNew',
					method: 'post',
					data: data
				})
				if (res.code == 200) {
					uni.showToast({
						title: "添加成功"
					})
					this.show = false
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 600);
				}
			},
			validData() {
				if (!this.staff.nickname || !this.staff.mobile) {
					uni.showToast({
						title: '姓名和电话不能有空',
						icon: 'none'
					})
					return false
				}
				if (!this.staff.roleIds && !this.userId) {
					uni.showToast({
						title: '请选择岗位',
						icon: 'none'
					})
					return false
				}
				if (!this.staff.staffType) {
					uni.showToast({
						title: '请选择员工类型',
						icon: 'none'
					})
					return false
				}
				return true
			},
			// 打开性别选择器
			openGenderPicker() {
				this.showGenderPicker = true
			},
			// 关闭性别选择器
			closeGenderPicker() {
				this.showGenderPicker = false
			},
			// 处理性别选择提交
			handleGenderSubmit(selectedData) {
				this.genderIndex = selectedData[0].index
				this.staff.sex = this.genderIndex.toString()
				this.closeGenderPicker()
			},
			// 打开员工类型选择器
			openStaffTypePicker() {
				this.showStaffTypePicker = true
			},
			// 关闭员工类型选择器
			closeStaffTypePicker() {
				this.showStaffTypePicker = false
			},
			// 处理员工类型选择提交
			handleStaffTypeSubmit(selectedData) {
				console.log('selectedData', selectedData)
				this.staff.staffType = selectedData.value
				console.log('this.staff.staffType', this.staff.staffType)
				this.closeStaffTypePicker()
			},
			// 获取员工类型标签
			getStaffTypeLabel(value) {
				if (!this.staffTypeOptions || !value) return '';
				const type = this.staffTypeOptions.find(item => item && item.value === value);
				return type ? type.label : '';
			},
			chooseJoinDate(e) {
				this.$nextTick(() => {
					this.staff.joinDate = formatDate(e.value)
					this.selectJoinDate = this.staff.joinDate
				})
				this.showJoinedDate = false
			},
			chooseFormalDate(e) {
				this.$nextTick(() => {
					this.staff.probationPeriod = formatDate(e.value);
					this.selectProbationPeriod = this.staff.probationPeriod
				})
				this.showFormalDate = false;
			},
			chooseSafeDate(e) {
				this.$nextTick(() => {
					this.staff.socialSecurityBuyDate = formatDate(e.value)
					this.selectSocialSecurityBuyDate = this.staff.socialSecurityBuyDate
				})
				this.showSafeDate = false
			},
			getEducation() {
				if (!this.educations || this.educations.length === 0) {
					// this.getEducations()
				}
				const index = this.educations.findIndex(item => item.value === this.staff.education)
				if (index !== -1) {
					return this.educations[index].label
				}
				return ''
			},
			chooseEducation(e) {
				this.$set(this.staff, 'education', e.value[0].label)
				this.staff.educational = e.value[0].label
				this.showEducation = false
			},
			// 处理角色选择提交
			handleRoleSubmit(selectedRoles) {
				// 更新显示和存储选中的角色
				this.roleNames = selectedRoles.map(role => role.name);
				this.staff.roleIds = selectedRoles.map(role => role.id);
				this.selectedRoles = selectedRoles; // 存储选中的角色对象用于回显
				this.showRole = false;
				console.log('选中角色IDs:', this.staff.roleIds);
			},
			goFile() {
				if (!this.userId) {
					uni.showToast({
						title: '请先新建员工',
						icon: 'none'
					})
					return
				}
				if (!this.staff.folderId) {
					request({
						url: '/system/rescueInfo/addFolder',
						method: 'post',
						data: this.userId
					}).then(res => {
						this.staff.folderId = res.data
						uni.navigateTo({
							url: '/pages/internal/rescueManage?type=staff&folderId=' +
								this.staff.folderId
						})
					})
				} else {
					uni.navigateTo({
						url: '/pages/internal/rescueManage?type=staff&folderId=' + this
							.staff.folderId
					})
				}
			},
			// 上传相关方法
			handleUpload() {
				this.$refs.uploadRef.chooseFile();
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					upload({
						url: '/common/upload',
						filePath: url,
					}).then((res) => {
						resolve(res.data.url);
						this.forceRefreshFiles();
					})
				});
			},
			pageBack() {
				console.log("执行 pageBack");
				uni.navigateBack({
					delta: 1
				});
			},
			previewImage(currentUrl) {
				if (!currentUrl) {
					uni.showToast({
						title: '图片无效',
						icon: 'none'
					});
					return;
				}
				uni.previewImage({
					current: currentUrl,
					urls: [currentUrl],
					success: () => console.log('预览成功'),
					fail: (err) => console.error('预览失败:', err)
				});
			},
			// 获取角色信息的方法
			async getInfoByUserId() {
				const res = await request({
					url: '/system/rescueInfo/getOnInternal',
					params: {
						id: this.userId
					},
					method: 'get'
				});

				this.staff = res.data;
				this.genderIndex = parseInt(this.staff.sex || '0');

				// 确保岗位数据已加载后再执行回显
				if (this.postOptions.length === 0) {
					await this.getPosts(); // 等待岗位数据加载
				}

				// 编辑时回显多个岗位
				if (this.staff.roleIds && this.staff.roleIds.length && this.postOptions.length) {
					this.selectedRoles = this.postOptions.filter(role =>
						this.staff.roleIds.includes(role.id)
					);
					this.roleNames = this.selectedRoles.map(role => role.name);
				}
			},
		},
	}
</script>

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

	.container {
		width: 100%;
		background: #f4f5f6;
		box-sizing: border-box;
		padding: 30rpx;
		overflow-y: auto;
		display: flex;
		flex-direction: column;
	}

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

	.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;
		background: linear-gradient(180deg, #054DF3 0%, #55A3FF 100%);
		position: sticky;
		top: 0;
		z-index: 100;

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

	.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>
