<template>
	<view class="container">
		<view class="content">
			<view class="summary-section">
				<view class="summary-header">
					<view class="summary-indicator"></view>
					<text class="summary-title">基础信息</text>
				</view>
				<view class="list">
					<view class="info-item">
						<view class="label">头像</view>
						<view class="right">
							<image class="head" :src="formData.avatar||'https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/my_heads_icon.png'"></image>
							<button class="wx-head" type="balanced" open-type="chooseAvatar"
								@chooseavatar="onChooseAvatar"></button>
						</view>
					</view>
					<view class="info-item">
						<view class="label">姓名</view>
						<view class="right">
							<input type="nickname" @input="onNicknameInput" v-model="formData.nickname"
								placeholder="请输入昵称" class="input" />
						</view>
					</view>
					<view class="info-item" @click="toSelectGender">
						<view class="label">性别</view>
						<view class="right">
							<text class="txt">{{formData.sex==1?'男':'女'}}</text>
							<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
				</view>

				<view class="summary-header">
					<view class="summary-indicator"></view>
					<text class="summary-title">岗位信息</text>
				</view>
				<view class="list">
					<view class="info-item" @click="toSelect('dept')">
						<view class="label">部门</view>
						<view class="right">
							<text class="txt" :class="{ash:!formData.deptName}">{{formData.deptName||'请选择部门'}}</text>
							<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
					<view class="info-item" @click="toSelect('post')">
							<view class="label">岗位</view>
							<view class="right">
								<text class="txt" :class="{ash:!formData.postNames}">{{formData.postNames||'请选择岗位'}}</text>
								<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_my_more.png" mode=""></image>
							</view>
						</view>
					<view class="info-item" @click="toSelect('product')">
						<view class="label">产品</view>
						<view class="right">
							<text class="txt" :class="{ash:!formData.productNames}">{{formData.productNames||'请选择产品'}}</text>
							<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
					<view class="info-item" @click="toSelect('superior')">
						<view class="label">直属上级</view>
						<view class="right">
							<text class="txt"
								:class="{ash:!formData.supervisorName}">{{formData.supervisorName||'请选择'}}</text>
							<image class="icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_my_more.png" mode=""></image>
						</view>
					</view>

					<view class="form-section">
						<view class="form-label">
							<text>证明材料</text>
							<text class="tip">工作证、OA信息截图、个人名片等</text>
						</view>


						<view class="upload-proof" @click="chooseProofImages">
							<view v-if="formData.proofImages && formData.proofImages.length > 0" class="uploaded-images">
								<view v-for="(image, index) in formData.proofImages" :key="index"
									class="uploaded-image-item">
									<image :src="image" mode="aspectFill"></image>
									<view class="image-delete" @click.stop="deleteProofImage(index)">×</view>
								</view>
								<view class="upload-placeholder">
									<image src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_camera.png" mode="aspectFill"></image>
								</view>
							</view>
							<view v-else class="upload-placeholder">
								<image src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_camera.png" mode="aspectFill"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="btn-box">
			<view class="sub-btn" @click="submit()">保存</view>
		</view>

		<u-picker :show="showPicker" :columns="[pickerList]" keyName="title" @confirm="onPickerConfirm"
			@cancel="showPicker=false"></u-picker>

		<!-- 多选弹窗 -->
		<u-popup :show="showMultiSelectPopup" mode="bottom" round="20rpx" :closeable="false">
			<view class="u-popup-content">
				<view class="popup-header">
					<text class="popup-title">{{ multiSelectTitle }}</text>
					<text class="popup-close" @click="closeMultiSelectPopup">×</text>
				</view>
				<view class="popup-body">
					<view class="tag-group">
						<view v-for="(item, index) in multiSelectData" :key="index" class="tag-item"
							:class="{ active: selectedItems.includes(item) }" @click="toggleItem(item)">
							{{ item }}
						</view>
					</view>
				</view>
				<view class="popup-footer">
					<view class="popup-btn cancel-btn" @click="closeMultiSelectPopup">取消</view>
					<view class="popup-btn confirm-btn" @click="confirmMultiSelect">确定</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getUserInfo,
		updateUserInfo,
		getDeptList,
		getPostList,
		getProductList,
		getCompanyUserList
	} from '@/api/user'

	export default {
		data() {
				return {
					userInfo: {},
					formData: {
						proofImages: [],
						avatar: '',
						nickname: '',
						sex: '',
						deptId: '',
						deptName: '',
						postId: '',
						postName: '',
						postIds: [],
						productId: '',
				productName: '',
				productCode: '',
				productCodes: [],
				productNames: '',
				supervisorId: '',
						supervisorName: ''
					},
					showPicker: false,
				pickerList: [],
				pickerType: '',
				// 多选相关
				showMultiSelectPopup: false,
				multiSelectTitle: '',
				multiSelectData: [],
				selectedItems: [],
				currentMultiSelectType: '',
				dataCache: {
						deptList: null,
						postList: null,
						productList: null,
						userList: null
					}
				}
		},
		onLoad() {
			// 先获取用户信息
			this.getUserInfo();
			// 统一请求所有需要的数据
			this.loadAllData();
		},
		onShow() {
		},
		methods: {
			// 统一加载所有数据
			loadAllData() {
				// 加载部门列表
				this.loadData('dept', getDeptList, 'deptId', 'deptName', '');
				// 加载岗位列表
				this.loadData('post', getPostList, 'postId', 'postName', '');
				// 加载上级列表
				this.loadData('superior', getCompanyUserList, 'userId', 'nickName', '');
				// 加载产品列表
				this.loadData('product', getProductList, 'productCode', 'productName', 'productCode');
			},
			// 加载指定类型的数据
			async loadData(type, api, idField, nameField, codeField) {
				try {
					if (api) {
						const res = await api();
						if (res.code === 200 && res.data && res.data.length > 0) {
							let filteredData = res.data;
							// 剔除当前用户本人
							if (type === 'superior' && this.userInfo && this.userInfo.userId) {
								filteredData = res.data.filter(item => item.userId !== this.userInfo.userId);
							}
							const list = filteredData.map(item => ({
								id: item[idField],
								title: item[nameField],
								code: item[codeField] || ''
							}));
							this.dataCache[type + 'List'] = list;
						}
					}
				} catch (err) {
					console.error(`获取${type}列表失败:`, err);
				}
			},
			// 从缓存中获取数据，不再发起接口请求
			getDataList(type) {
				return this.dataCache[type + 'List'] || [];
			},

			onNicknameInput(e) {
				this.formData.nickname = e.detail.value;
			},

			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail;
				uni.showLoading({
					title: '上传中...'
				});
				const baseUrl = uni.getStorageSync('requestPath');
				uni.uploadFile({
					url: `${baseUrl}/system/file/upload`,
					filePath: avatarUrl,
					name: 'file',
					formData: {
						bizType: 'USER_INFO'
					},
					header: {
						'AppToken': uni.getStorageSync('AppToken')
					},
					success: (uploadFileRes) => {
						const data = JSON.parse(uploadFileRes.data);
						if (data.code === 200) {
							this.formData.avatar = data.data.fileUrl;
						} else {
							uni.showToast({
								icon: 'none',
								title: data.message || '上传失败'
							});
						}
						uni.hideLoading();
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '上传失败'
						});
					}
				});
			},

			submit() {
					// 打印 postIds 的值和类型
					console.log('postIds 值:', this.formData.postIds);
					console.log('postIds 类型:', typeof this.formData.postIds);
					console.log('postIds 是否为数组:', Array.isArray(this.formData.postIds));
					
					// 确保 postIds 是数组
				let postIdsArray = this.formData.postIds;
				if (!Array.isArray(postIdsArray)) {
					if (postIdsArray) {
						postIdsArray = [postIdsArray];
					} else {
						postIdsArray = [];
					}
				}
				console.log('转换后 postIds 值:', postIdsArray);
				console.log('转换后 postIds 类型:', typeof postIdsArray);
				console.log('转换后 postIds 是否为数组:', Array.isArray(postIdsArray));
				
				// 确保 productCodes 是数组
				let productCodesArray = this.formData.productCodes;
				if (!Array.isArray(productCodesArray)) {
					if (productCodesArray) {
						productCodesArray = [productCodesArray];
					} else {
						productCodesArray = [];
					}
				}
				console.log('转换后 productCodes 值:', productCodesArray);
				
				const params = {
					avatar: this.formData.avatar,
					nickName: this.formData.nickname,
					sex: this.formData.sex,
					deptId: this.formData.deptId,
					postIds: postIdsArray,
					productCode: productCodesArray.join(','),
					supervisorId: this.formData.supervisorId,
					certificationMaterials: this.formData.proofImages.join(',') || ''
				};

				uni.showLoading({
					title: '保存中...'
				});
				updateUserInfo(params).then(res => {
					uni.hideLoading();
					if (res.code === 200) {
						uni.showToast({
							icon: 'success',
							title: '修改成功'
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg || '保存失败'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '网络错误，请重试'
					});
				});
			},

			async getUserInfo() {
					try {
						const res = await getUserInfo();
						if (res.code === 200 && res.user) {
							const user = res.user;
							// 设置用户信息
							this.userInfo = user;
							this.post = res.post;

							// 设置表单数据
							this.formData.avatar = user.avatar || '';
							this.formData.nickname = user.userName || '';
							this.formData.sex = user.sex || '';
							this.formData.deptId = user.deptId || '';
							this.formData.deptName = user.deptName || '';
							this.formData.deptIds = user.deptId ? [user.deptId] : [];
							this.formData.deptNames = user.deptName || '';
							// 处理岗位数据
							this.formData.postIds = user.postIds || [];
							this.formData.postNames = res.post ? res.post.join(', ') : '';
							// 处理产品数据
							this.formData.productCode = user.productCode || '';
							this.formData.productCodes = user.productCode ? user.productCode.split(',') : [];
							// 从productList中获取产品名称
							if (user.productList && user.productList.length > 0) {
								const productNames = user.productList.map(item => item.name).join(', ');
								this.formData.productNames = productNames;
								// 设置第一个产品作为默认值
								this.formData.productId = user.productList[0].code;
								this.formData.productName = user.productList[0].name;
							} else {
								this.formData.productNames = '';
								this.formData.productId = '';
								this.formData.productName = '';
							}
							this.formData.supervisorId = user.supervisorId || '';
							this.formData.supervisorName = user.supervisorName || '';
							this.formData.proofImages = user.certificationMaterials ? user.certificationMaterials.split(
								',') : [];
							uni.setStorageSync('userInfo', user);
							// 加载产品数据
							this.loadData('product', null, 'code', 'name', 'code');
							// 加载岗位数据
							this.loadData('post', null, 'id', 'title', '');
						}
					} catch (err) {
						console.error('获取用户信息失败:', err);
						uni.showToast({
							icon: 'none',
							title: '获取用户信息失败'
						});
				}
			},

			chooseProofImages() {
				uni.chooseImage({
					count: 9,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.uploadImages(res.tempFilePaths);
					}
				});
			},

			async uploadImages(tempFilePaths) {
				try {
					uni.showLoading({
						title: '上传中...'
					});
					const uploadedImages = [];
					const baseUrl = uni.getStorageSync('requestPath');

					for (const tempFilePath of tempFilePaths) {
						const uploadRes = await new Promise((resolve, reject) => {
							uni.uploadFile({
								url: `${baseUrl}/system/file/upload`,
								filePath: tempFilePath,
								name: 'file',
								formData: {
									bizType: 'USER_INFO'
								},
								header: {
									'AppToken': uni.getStorageSync('AppToken')
								},
								success: (res) => {
									const data = JSON.parse(res.data);
									if (data.code === 200) {
										resolve(data.data);
									} else {
										reject(new Error(data.message || '上传失败'));
									}
								},
								fail: (err) => {
									reject(err);
								}
							});
						});
						uploadedImages.push(uploadRes.fileUrl);
					}

					this.formData.proofImages = [...this.formData.proofImages, ...uploadedImages];
					uni.hideLoading();
					uni.showToast({
						icon: 'success',
						title: '上传成功'
					});
				} catch (e) {
					console.error('上传失败:', e);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					});
				}
			},

			deleteProofImage(index) {
				this.formData.proofImages.splice(index, 1);
			},

			toSelect(type) {
				const typeNames = {
					dept: '部门',
					post: '岗位',
					product: '产品',
					superior: '业务员'
				};

				const list = this.getDataList(type);
				if (list && list.length > 0) {
					if (type === 'dept' || type === 'post' || type === 'product') {
						// 部门、岗位和产品使用多选弹窗
						this.multiSelectData = list.map(item => item.title);
						this.multiSelectTitle = typeNames[type];
						this.currentMultiSelectType = type;

						// 初始化已选项
						if (type === 'dept') {
							this.selectedItems = this.formData.deptNames ? this.formData.deptNames.split(', ') : [];
						} else if (type === 'post') {
							this.selectedItems = this.formData.postNames ? this.formData.postNames.split(', ') : [];
						} else if (type === 'product') {
							this.selectedItems = this.formData.productNames ? this.formData.productNames.split(', ') : [];
						}

						// 显示多选弹窗
						this.showMultiSelectPopup = true;
					} else {
						// 其他使用单选picker
						this.pickerList = list;
						this.pickerType = type;
						this.showPicker = true;
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: `暂无${typeNames[type]}数据`
					});
				}
			},

			onPickerConfirm(e) {
				const selectedItem = e.value[0];
				console.log('selectedItem 值:', selectedItem);
				
				const fieldMap = {
					product: {
						id: 'productId',
						name: 'productName',
						code: 'productCode'
					},
					superior: {
						id: 'supervisorId',
						name: 'supervisorName'
					},
					gender: {
						id: 'sex'
					}
				};

				if (this.pickerType === 'gender') {
					this.formData.sex = selectedItem.id;
				} else {
					const fields = fieldMap[this.pickerType];
					this.formData[fields.id] = selectedItem.id;
					this.formData[fields.name] = selectedItem.title;
					if (fields.code) {
						this.formData[fields.code] = selectedItem.code || selectedItem.id;
					}
				}

				this.showPicker = false;
			},

			toSelectGender() {
				this.pickerList = [{
						id: '1',
						title: '男'
					},
					{
						id: '0',
						title: '女'
					}
				];
				this.pickerType = 'gender';
				this.showPicker = true;
			},

			// 多选相关方法
			// 切换选项
			toggleItem(item) {
				const index = this.selectedItems.indexOf(item);
				if (index > -1) {
					// 取消选择
					this.selectedItems.splice(index, 1);
				} else {
					// 添加选择
					this.selectedItems.push(item);
				}
			},

			// 关闭多选弹窗
			closeMultiSelectPopup() {
				this.showMultiSelectPopup = false;
			},

			// 确认多选结果
			confirmMultiSelect() {
				const selectedNames = this.selectedItems.join(', ');
				const list = this.getDataList(this.currentMultiSelectType);

				// 根据选中的名称获取对应的id
				const selectedIds = list
					.filter(item => this.selectedItems.includes(item.title))
					.map(item => item.id);

				if (this.currentMultiSelectType === 'dept') {
					this.formData.deptNames = selectedNames;
					this.formData.deptIds = selectedIds;
					if (selectedIds.length > 0) {
						this.formData.deptId = selectedIds[0];
						this.formData.deptName = this.selectedItems[0];
					} else {
						this.formData.deptId = '';
						this.formData.deptName = '';
					}
				} else if (this.currentMultiSelectType === 'post') {
					this.formData.postNames = selectedNames;
					// 岗位数据使用对应的postId数组
					this.formData.postIds = selectedIds;
				} else if (this.currentMultiSelectType === 'product') {
					this.formData.productNames = selectedNames;
					// 获取选中的产品代码
					const selectedCodes = list
						.filter(item => this.selectedItems.includes(item.title))
						.map(item => item.code || item.id);
					this.formData.productCodes = selectedCodes;
					if (selectedIds.length > 0) {
						this.formData.productId = selectedIds[0];
						this.formData.productName = this.selectedItems[0];
						this.formData.productCode = selectedCodes[0];
					} else {
						this.formData.productId = '';
						this.formData.productName = '';
						this.formData.productCode = '';
					}
				}

				this.showMultiSelectPopup = false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #ffffff;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		position: relative;

		.content {
			width: 100%;
			height: 100%;
			position: relative;
			z-index: 2;

			.summary-section {
				padding: 32rpx 24rpx;
				display: flex;
				flex-direction: column;

				.summary-header {
					display: flex;
					align-items: center;
					margin-bottom: 24rpx;

					.summary-indicator {
						width: 6rpx;
						height: 32rpx;
						background: #388BFF;
						border-radius: 40rpx;
						margin-right: 16rpx;
					}

					.summary-title {
						font-size: 36rpx;
						font-weight: bold;
						color: #333;
					}
				}
			}

			.list {
				margin-bottom: 40rpx;

				.info-item {
					height: 104upx;
					padding: 0 30upx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1px solid #F5F6FA;

					&:last-child {
						border-bottom: none;
					}

					.label {
						font-size: 30upx;
						font-family: PingFang SC;
						font-weight: 400;
						color: #0F1826;
					}

					.right {
						display: flex;
						align-items: center;
						justify-content: center;

						.txt {
							font-size: 28rpx;
							color: #333333;
							margin-right: 8rpx;
						}

						.ash {
							color: #C8C9CC;
						}

						.icon {
							width: 36rpx;
							height: 36rpx;
						}

						.head {
							border-radius: 50%;
							width: 80upx;
							height: 80upx;
						}

						.wx-head {
							position: absolute;
							width: 80upx;
							height: 80upx;
							opacity: 0;
						}

						.input {
							text-align: right;
							font-size: 30upx;
							font-family: PingFang SC;
							font-weight: 400;
							color: #0F1826;
						}
					}
				}

				.form-section {
					background: #fff;
					border-radius: 16rpx;
					padding: 24rpx;
					margin-bottom: 24rpx;

					.form-label {
						display: flex;
						align-items: center;
						font-size: 28rpx;
						color: #333;

						.tip {
							font-size: 24rpx;
							color: #999999;
							margin-left: 24rpx;
						}
					}

					.upload-proof {
						margin-top: 16rpx;

						.uploaded-images {
							display: flex;
							flex-wrap: wrap;
							gap: 20rpx;

							.uploaded-image-item {
								width: 160rpx;
								height: 160rpx;
								border-radius: 16rpx;
								position: relative;

								image {
									width: 100%;
									height: 100%;
									border-radius: 12rpx;
								}

								.image-delete {
									position: absolute;
									top: -12rpx;
									right: -12rpx;
									width: 40rpx;
									height: 40rpx;
									background: rgba(0, 0, 0, 0.6);
									color: #FFFFFF;
									border-radius: 50%;
									display: flex;
									align-items: center;
									justify-content: center;
									font-size: 32rpx;
									font-weight: bold;
									z-index: 1;
								}
							}
						}

						.upload-placeholder {
							width: 160rpx;
							height: 160rpx;
							background: #F7F8FA;
							border-radius: 16rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;

							image {
								width: 48rpx;
								height: 48rpx;
							}
						}
					}
				}
			}
		}
	}

	.btn-box {
		margin-top: 20rpx;
		height: 120upx;
		padding: 0 30upx;
		display: flex;
		align-items: center;
		justify-content: center;

		.sub-btn {
			width: 100%;
			height: 88upx;
			line-height: 88upx;
			text-align: center;
			font-size: 30upx;
			font-family: PingFang SC;
			font-weight: bold;
			color: #FFFFFF;
			background: #388BFF;
			border-radius: 200rpx;
		}
	}

	/* 多选弹窗样式 */
	.u-popup-content {
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		max-height: 80vh;
		display: flex;
		flex-direction: column;
		width: 100%;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1px solid #EBEDF0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.popup-close {
		font-size: 40rpx;
		color: #999;
		cursor: pointer;
	}

	.popup-body {
		padding: 32rpx;
		flex: 1;
		overflow-y: auto;
	}

	.tag-group {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.tag-item {
		padding: 16rpx 32rpx;
		border: 2rpx solid #DCDFE6;
		border-radius: 40rpx;
		font-size: 28rpx;
		color: #666;
		cursor: pointer;
		transition: all 0.3s;
		white-space: nowrap;
	}

	.tag-item.active {
		background: #388BFF;
		border-color: #388BFF;
		color: #fff;
	}

	.popup-footer {
		display: flex;
	}

	.popup-btn {
		flex: 1;
		gap: 20rpx;
		text-align: center;
		height: 88rpx;
		line-height: 88rpx;
		border: none;
		font-size: 28rpx;
		cursor: pointer;
		border-radius: 40rpx;
	}

	.cancel-btn {
		background: #fff;
		color: #666;
		border: 2rpx solid #DCDFE6;
	}

	.confirm-btn {
		background: #388BFF;
		color: #fff;
	}
</style>