<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="userInfo.avatar?userInfo.avatar:'/static/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" @blur="bindblur" @input="bindinput" v-model="userInfo.userName" placeholder="请输入昵称" class="input"/>
						</view>
					</view>
					<view class="info-item" @click="toSelectGender">
						<view class="label">性别</view>
						<view class="right" v-if="userInfo!=null">
							<text class="txt">{{userInfo.sex==1?'男':'女'}}</text>
							<image class="icon" src="/static/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="toSelectDept">
						<view class="label">部门</view>
						<view class="right">
							<text class="txt" :class="{ash:!formData.deptName}">{{formData.deptName||'请选择部门'}}</text>
							<image class="icon" src="/static/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
					<view class="info-item" @click="toSelectPost">
						<view class="label">岗位</view>
						<view class="right">
							<text class="txt" :class="{ash:!formData.postName}">{{formData.postName||'请选择岗位'}}</text>
							<image class="icon" src="/static/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
					<view class="info-item" @click="toSelectProduct">
						<view class="label">产品</view>
						<view class="right">
							<text class="txt" :class="{ash:!formData.productName}">{{formData.productName||'请选择产品'}}</text>
							<image class="icon" src="/static/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
					<view class="info-item" @click="toSelectSuperior">
						<view class="label">直属上级</view>
						<view class="right">
							<text class="txt" :class="{ash:!formData.superiorName}">{{formData.superiorName||'请选择'}}</text>
							<image class="icon" src="/static/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="/static/image/icon_camera.png" mode="aspectFill"></image>
								</view>
							</view>
							<view v-else class="upload-placeholder">
								<image src="/static/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>
	</view>

</template>

<script>
import {
	getUserInfo,//查询用户信息
	updateUserInfo,//更新业务员个人信息
	getDeptList,//获取当前公司部门列表
	getPostList,//获取当前公司岗位列表
	getProductList,//获取当前公司所有产品列表
	getCompanyUserList//获取当前公司所有业务员列表（前端需要排除当前用户）
} from '@/api/user'
import utils from '@/utils/common.js'
	export default {
		data() {
			return {
				user: null,
				formData: {
					proofImages: [],
					avatar: '',
					nickname: '',
					sex: '',
					deptId: '',
					deptName: '',
					postId: '',
					postName: '',
					postIds: '',
					productId: '',
					productName: '',
					productCode: '',
					superiorId: '',
					superiorName: '',
					certificationMaterials: ''
				},
				userInfo:{},
				showPicker: false,
				pickerList: [],
				pickerType: '',
				deptList: [],
				postList: [],
				productList: [],
				userList: []
			}
		},
		onLoad() {
		},
		onShow() {
			this.getUserInfo();
			this.getDeptList();
			this.getPostList();
			this.getProductList();
			this.getCompanyUserList();
		},
		methods: {
			getDeptList(){
				getDeptList().then(
					res => {
						if(res.code==200){
							if(res.data!=null && res.data.length>0){
								this.deptList = res.data.map(item => ({
									id: item.deptId,
									title: item.deptName
								}));
								console.log("获取当前公司部门列表this.deptList",this.deptList);
							}
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			getPostList(){
				getPostList().then(
					res => {
						if(res.code==200){
							if(res.data!=null && res.data.length>0){
								this.postList = res.data.map(item => ({
									id: item.postId,
									title: item.postName
								}));
								console.log("获取当前公司岗位列表this.postList",this.postList);
							}
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			getProductList(){
				getProductList().then(
					res => {
						if(res.code==200){
							if(res.data!=null && res.data.length>0){
								this.productList = res.data.map(item => ({
									id: item.id,
									title: item.productName
								}));
								console.log("获取当前公司所有产品列表this.productList",this.productList);
							}
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			getCompanyUserList(){
				getCompanyUserList().then(
					res => {
						if(res.code==200){
							if(res.data!=null && res.data.length>0){
								this.userList = res.data.map(item => ({
									id: item.userId,
									title: item.nickName
								}));
								console.log("获取当前公司所有业务员列表（前端需要排除当前用户）this.userList",this.userList);
							}
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			bindblur(e) {
				if (this.user) {
					this.user.nickname = e.detail.value;
				}
			},
			bindinput(e){
					if (this.user) {
						this.user.userName = e.detail.value;
						this.formData.nickname = e.detail.value;
					}
				},
			onChooseAvatar(e){
					let {
						avatarUrl
					} = e.detail;
					if (!this.user) {
						uni.showToast({
							icon: 'none',
							title: '请先获取用户信息'
						});
						return;
					}
					uni.uploadFile({
						url: uni.getStorageSync('requestPath')+'/app/common/uploadOSS',
						filePath: avatarUrl,
						name: 'file',
						formData: {
							'user': 'test'
						},
						success: (uploadFileRes) => {
							const avatarUrl = JSON.parse(uploadFileRes.data).url;
							this.user.avatar = avatarUrl;
							this.formData.avatar = avatarUrl;
						}
					});
				},
			submit(){
				if (!this.user) {
					uni.showToast({
						icon: 'none',
						title: '请先获取用户信息'
					});
					return;
				}
				this.user.proofImages = this.formData.proofImages;
				console.log("修改数据",this.user.proofImages);
				console.log("修改数据2",this.user);
				const params = {
					avatar: this.formData.avatar,
					nicknName: this.formData.nickname,
					sex: this.formData.sex,
					deptId: this.formData.deptId,
					postIds: this.formData.postIds,
					productCode: this.formData.productCode,
					superiorId: this.formData.superiorId,
					certificationMaterials: this.formData.certificationMaterials||[]
				}

				updateUserInfo(params).then(
					res => {
						if(res.code==200){
							uni.showToast({
								icon:'success',
								title: "修改成功",
							});
							setTimeout(function(){
								uni.navigateBack({
									delta:1,
								})
							},2000);
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			getUserInfo(){
				getUserInfo().then(
					res => {
						if(res.code==200){
							if(res.user!=null){
								this.user = res.user;
								this.userInfo=res.user;
								uni.setStorageSync('userInfo', this.userInfo);
								this.formData.avatar = this.user.avatar || '';
								this.formData.nickname = this.user.userName || '';
								this.formData.sex = this.user.sex || '';
								this.formData.deptId = this.user.deptId || '';
								this.formData.deptName = this.user.deptName || '';
								this.formData.postId = this.user.postId || '';
								this.formData.postName = this.user.postName || '';
								this.formData.postIds = this.user.postId || '';
								this.formData.productId = this.user.productId || '';
								this.formData.productName = this.user.productName || '';
								this.formData.productCode = this.user.productCode || '';
								this.formData.superiorId = this.user.superiorId || '';
								this.formData.superiorName = this.user.superiorName || '';
								this.formData.certificationMaterials = Array.isArray(this.user.proofImages) ? this.user.proofImages.join(',') : '';
								this.formData.proofImages = this.user.proofImages || [];
							}

						}else{
							uni.showToast({
								icon:'none',
								title: "请求失败",
							});
						}
					},
					rej => {}
				);
			},
			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) {
										console.log('上传成功:', data.data)
										resolve(data.data)
									} else {
										reject(new Error(data.message || '上传失败'))
									}
								},
								fail: (err) => {
									reject(err)
								}
							})
						})
						uploadedImages.push(uploadRes.fileUrl)
					}
					this.formData.proofImages = [...this.formData.proofImages, ...uploadedImages]
				this.formData.certificationMaterials = this.formData.proofImages.join(',')
				uni.hideLoading()
				uni.showToast({ icon: 'success', title: '上传成功' })
				} catch (e) {
					uni.hideLoading()
					uni.showToast({ icon: 'none', title: '上传失败' })
				}
			},
			deleteProofImage(index) {
				this.formData.proofImages.splice(index, 1)
				this.formData.certificationMaterials = this.formData.proofImages.join(',')
			},
			onPickerConfirm(e) {
				const selectedItem = e.value[0];
				
				if (this.pickerType === 'dept') {
					this.formData.deptId = selectedItem.id;
					this.formData.deptName = selectedItem.title;
				} else if (this.pickerType === 'post') {
					this.formData.postId = selectedItem.id;
					this.formData.postName = selectedItem.title;
					this.formData.postIds = selectedItem.id;
				} else if (this.pickerType === 'product') {
					this.formData.productId = selectedItem.id;
					this.formData.productName = selectedItem.title;
					this.formData.productCode = selectedItem.id;
				} else if (this.pickerType === 'superior') {
					this.formData.superiorId = selectedItem.id;
					this.formData.superiorName = selectedItem.title;
				} else if (this.pickerType === 'gender') {
					// 处理性别选择
					this.user.sex = selectedItem.id;
					this.userInfo.sex = selectedItem.id;
					this.formData.sex = selectedItem.id;
				}
				
				this.showPicker = false;
			},
			toSelectDept() {
				if (this.deptList && this.deptList.length > 0) {
					this.pickerList = this.deptList;
					this.pickerType = 'dept';
					this.showPicker = true;
				} else {
					uni.showToast({
						icon: 'none',
						title: '暂无部门数据'
					})
				}
			},
			toSelectPost() {
				if (this.postList && this.postList.length > 0) {
					this.pickerList = this.postList;
					this.pickerType = 'post';
					this.showPicker = true;
				} else {
					uni.showToast({
						icon: 'none',
						title: '暂无岗位数据'
					})
				}
			},
			toSelectProduct() {
				if (this.productList && this.productList.length > 0) {
					this.pickerList = this.productList;
					this.pickerType = 'product';
					this.showPicker = true;
				} else {
					uni.showToast({
						icon: 'none',
						title: '暂无产品数据'
					})
				}
			},
			toSelectSuperior() {
				if (this.userList && this.userList.length > 0) {
					this.pickerList = this.userList;
					this.pickerType = 'superior';
					this.showPicker = true;
				} else {
					uni.showToast({
						icon: 'none',
						title: '暂无业务员数据'
					})
				}
			},
			toSelectGender() {
				// 设置性别选择数据
				this.pickerList = [
					{ id: '1', title: '男' },
					{ id: '0', title: '女' }
				];
				this.pickerType = 'gender';
				this.showPicker = true;
			}

		}
	}
</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;

			.title {
				font-weight: 600;
				font-size: 36rpx;
				color: #333333;
				height: 88rpx;
				text-align: center;
				line-height: 88rpx;

			}

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

						.img {
							width: 62rpx;
							height: 62rpx;
							border-radius: 50%;
							margin-right: 6rpx;
						}

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

					}

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

					.form-input-wrapper {
						position: relative;

						.form-input {
							width: 100%;
							min-height: 120rpx;
							padding: 16rpx;
							background: #f5f5f5;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #333;
						}

						.char-count {
							position: absolute;
							right: 16rpx;
							bottom: 16rpx;
							font-size: 24rpx;
							color: #999;
						}
					}

					.form-select {
						display: flex;
						align-items: center;
						justify-content: space-between;
						height: 80rpx;
						padding: 0 24rpx;
						background: #f5f5f5;
						border-radius: 8rpx;
						font-size: 28rpx;
						color: #333;

						.placeholder {
							color: #999;
						}

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

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

					.attachment-list {
						.attachment-item {
							display: flex;
							align-items: center;
							padding: 16rpx;
							background: #f5f5f5;
							border-radius: 8rpx;
							margin-bottom: 16rpx;

							.attachment-icon {
								font-size: 32rpx;
								margin-right: 16rpx;
							}

							.attachment-info {
								flex:1;
								display: flex;
								flex-direction: column;

								.attachment-name {
									font-size: 28rpx;
									color: #333;
									margin-bottom: 4rpx;
								}

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

							.attachment-delete {
								font-size: 40rpx;
								color: #999;
								width: 40rpx;
								height: 40rpx;
								display: flex;
								align-items: center;
								justify-content: center;
							}
						}

						.add-attachment {
							display: flex;
							align-items: center;
							justify-content: center;
							padding: 24rpx;
							background: #E3F2FD;
							border-radius: 8rpx;
							font-size: 28rpx;
							color: #388BFF;

							.add-icon {
								font-size: 32rpx;
								margin-right: 8rpx;
							}
						}
					}
				}
			}
		}
	}
	.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: 44upx;
		}
	}
</style>