<template>
	<view class="page flex-col">
		<!-- <view class="block_1 flex-row">{{ 123 }}
    </view> -->
		<view style="width: 100%;background: #f4f5f6;box-sizing: border-box;padding-top: 88px;">
			<headers titles="个人信息">
				<uni-icons type="left" color="#000000" size="22px"></uni-icons>
			</headers>
		</view>
		<view class="block_2 flex-col">
			<scroll-view class="scroll-view" scroll-y="true" :style="{ height: scrollHeight + 'px' }">

				<!-- <view class="group_1 flex-row">
        <image
            class="label_1"
            referrerpolicy="no-referrer"
            src="/static/lanhu_gerenxinxi/FigmaDDSSlicePNGacf527a62cbe7351c6472edd8f5b2814.png"
            @click="handleBack()"
        />
        <text class="text_1">个人信息</text>

      </view> -->

				<view class="group_4 flex-col">
					<view class="block_4 flex-row justify-between">
						<text class="text_2">头像</text>
						<view class="label_2">
							<u-upload :fileList="avatarList" @afterRead="avatarAfterRead" @delete="avatarDelete"
								:maxCount="1" width="70rpx" height="70rpx">
								<!-- <image
                  class="label_2"
                  referrerpolicy="no-referrer"
                  :src="(item ? imageUrl + '/' + userDetails.avatar : '/static/lanhu_gerenxinxiweitianxie/FigmaDDSSlicePNG6ea89e46a56641bc7e118ef1d4d789d5.png')"
              /> -->

								<image class="label_2"
									:src="avatarList[0] ? avatarList[0].url : '/static/lanhu_gerenxinxiweitianxie/FigmaDDSSlicePNG6ea89e46a56641bc7e118ef1d4d789d5.png'" />
							</u-upload>
						</view>
					</view>
					<!-- src="/static/lanhu_gerenxinxi/FigmaDDSSlicePNGcc6ee579083c2c921f6c93c250df5d44.png" -->
					<view class="text-wrapper_1 flex-row justify-between">
						<text class="text_3">昵称</text>
						<input class="text_4" v-model="userDetails.name" type="text" placeholder="请填写昵称">
					</view>
					<view class="text-wrapper_2 flex-row justify-between">
						<text class="text_5">联系方式</text>
						<text class="text_6">{{ userDetails.phone }}</text>
					</view>
				</view>
				<view class="group_5 flex-col" v-if="noN">
					<view class="text-wrapper_3 flex-row">
						<text class="text_7">身份证照片</text>
					</view>
					<view class="image-wrapper_2 flex-row justify-between">
						<u-upload :fileList="idCardfileList" @afterRead="idCardAfterRead" @delete="idCardDelete"
							:maxCount="2" width="300rpx" height="196rpx" margin-right="10rpx" :previewFullImage="true">
						</u-upload>
					</view>
				</view>

				<view class="group_6 flex-col" v-if="noN">
					<text class="text_8">生活照片</text>
					<view class="list_1 flex-row">
						<u-upload :fileList="lifePhotoFileList" @afterRead="lifePhotoAfterRead"
							@delete="lifePhotoDelete" :maxCount="3" :previewFullImage="true">
						</u-upload>
					</view>
				</view>

				<!-- <view class="group_7 flex-col" v-if="noN ">
					<text class="text_10">体检报告</text>
					<view class="report-list flex-row">
						<view class="report-item" v-for="(item, index) in examinationReportList" :key="index">
							<image class="report-image" :src="item.url" mode="aspectFill" />
						</view>
					</view>
				</view> -->
				<view class="group_7 flex-col" v-if="noN ">
					<text class="text_10">体检报告</text>
					<u-album :urls="examinationReportList.map(item => item.url)" keyName="url" multipleSize="80"
						rowCount="3" singleSize="200" previewFullImage="true"></u-album>
				</view>


			</scroll-view>
		</view>

		<view class="block_5 flex-col">
			<view class="text-wrapper_4 flex-col" @click="handleSave">
				<text class="text_9">保存</text>
			</view>
		</view>
	</view>
</template>
<script>
	import upload from '@/utils/upload.js'
	import request from '@/utils/request.js'
	import {
		getLocalUserInfo
	} from '../../utils/auth';
	import headers from "@/components/header/headers.vue";

	export default {
		components: {
			headers
		},
		data() {
			return {
				usersMsg: {},
				userId: null,
				constants: {},
				avatarList: [],
				idCardfileList: [],
				// idCardList: [],
				// lifePhotoList: [],
				lifePhotoFileList: [],
				examinationReportList: [], // 体检报告图片列表
				imageUrl: this.$imagesUrl,
				userDetails: {
					userId: null,
					avatar: '',
					name: null,
					phone: null,
					idCardImg: '',
					lifeImg: '',
				},
				noN: true,
				scrollHeight: 0,

				loopData0: [{
						lanhuBg0: 'url(https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG6c58eb8af40eb273da0485e6cc1d93d1.png) 100% no-repeat',
						lanhuimage0: 'https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG5d1a336033ae66a9d731e3524093ecf5.png'
					},
					{
						lanhuBg0: 'url(https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNGb51240b007489f1975779de452af0c84.png) 100% no-repeat',
						lanhuimage0: 'https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG5d1a336033ae66a9d731e3524093ecf5.png'
					},
					{
						lanhuBg0: 'url(https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG6096ca91210c53f26481649ad200964b.png) 100% no-repeat',
						lanhuimage0: 'https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG5d1a336033ae66a9d731e3524093ecf5.png'
					},
					{
						lanhuBg0: 'url(https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG31e719001bca1c0de203d1dbe975991e.png) 100% no-repeat',
						lanhuimage0: 'https://lanhu-oss-2537-2.lanhuapp.com/FigmaDDSSlicePNG5d1a336033ae66a9d731e3524093ecf5.png'
					}
				],
				constants: {}
			};
		},
		onLoad(option) {
			console.log('option', option)
			this.usersMsg = getLocalUserInfo()
			this.userId = option.userId;
			this.userDetails.userId = option.userId;
			this.getUserInfo()
		},
		onReady() {
			// 动态计算滚动区域高度
			this.calculateScrollHeight();
		},
		methods: {
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			},



			getUserInfo() {
				request({
					url: '/app-api/small/dl-drive-school-student/getByUserId',
					method: 'GET',
					params: {
						userId: this.userId
					},
				}).then(res => {
					console.log('userDetails', res.data)
					if (!res.data) {
						this.noN = false;
						this.userDetails = {
							name: this.usersMsg.nickname,
							phone: this.usersMsg.username,
							avatar: this.usersMsg.avatar
						};
						// 头像初始化
						if (this.usersMsg.avatar) {
							this.avatarList = [{
								url: `${this.imageUrl}/${this.usersMsg.avatar}`,
								fileName: this.usersMsg.avatar,
								status: 'success',
								response: {
									url: this.usersMsg.avatar
								}
							}];
						}
						return;
					}

					this.userDetails = {
						...res.data
					};

					// 头像初始化
					if (res.data.avatar) {
						this.avatarList = [{
							url: `${this.imageUrl}/${res.data.avatar}`,
							fileName: res.data.avatar,
							status: 'success',
							response: {
								url: res.data.avatar
							}
						}];
					}

					// 身份证照片初始化
					this.idCardfileList = res.data.idPhoto ?
						res.data.idPhoto.split(',')
						.filter(url => url.trim())
						.map(url => ({
							url: `${this.imageUrl}/${url.trim()}`,
							fileName: url.trim(),
							status: 'success',
							response: {
								url: `${this.imageUrl}/${url.trim()}`
							}
						})) : [];

					// 生活照初始化
					this.lifePhotoFileList = res.data.lifePhoto ?
						res.data.lifePhoto.split(',')
						.filter(url => url.trim())
						.map(url => ({
							url: `${this.imageUrl}/${url.trim()}`,
							fileName: url.trim(),
							status: 'success',
							response: {
								url: `${this.imageUrl}/${url.trim()}`
							}
						})) : [];

					this.examinationReportList = res.data.examinationReport ?
						res.data.examinationReport.split(',')
						.filter(url => url.trim())
						.map(url => ({
							url: `${this.imageUrl}/${url.trim()}`,
							fileName: url.trim()
						})) : [];
				});
			},

			// 头像上传
			avatarAfterRead(event) {
				const file = event.file[0] || event.file
				this.uploadFile(file, 'avatar').then(res => {
					this.avatarList = [{
						url: `${this.imageUrl}/${res.data.url}`,
						fileName: res.data.url
					}]
					this.userDetails.avatar = res.data.url
				})
			},
			// 头像删除
			avatarDelete() {
				this.avatarList = []
				this.userDetails.avatar = ''
			},

			// 身份证照片上传
			idCardAfterRead(event) {
				const files = Array.isArray(event.file) ? event.file : [event.file]
				if (this.idCardfileList.length + files.length > 2) {
					uni.showToast({
						title: '最多上传2张身份证照片',
						icon: 'none'
					})
					return
				}

				Promise.all(
					files.map(file =>
						this.uploadFile(file, 'idCard').then(res => ({
							url: `${this.imageUrl}/${res.data.url}`,
							fileName: res.data.url
						}))
					)
				).then(newFiles => {
					this.idCardfileList = [...this.idCardfileList, ...newFiles];
				});
			},

			// 身份证照片删除
			idCardDelete(event) {
				this.idCardfileList.splice(event.index, 1)
			},


			// 生活照上传
			lifePhotoAfterRead(event) {
				const files = Array.isArray(event.file) ? event.file : [event.file]
				if (this.lifePhotoFileList.length + files.length > 3) {
					uni.showToast({
						title: '最多上传3张生活照片',
						icon: 'none'
					})
					return
				}

				Promise.all(files.map(file =>
					this.uploadFile(file, 'lifePhoto').then(res => ({
						url: `${this.imageUrl}/${res.data.url}`,
						fileName: res.data.url
					}))
				)).then(newFiles => {
					this.lifePhotoFileList = [...this.lifePhotoFileList, ...newFiles]
				})
			},
			// 生活照删除
			lifePhotoDelete(event) {
				this.lifePhotoFileList.splice(event.index, 1)
			},

			// 上传
			uploadFile(file, type) {
				return new Promise((resolve, reject) => {
					upload({
						url: '/app-api/small-upload/common/upload',
						filePath: file.url || file.path,
						name: 'file',
						formData: {
							type
						}
					}).then(resolve).catch(reject)
				})
			},

			getUserOrder() {
				request({
					url: '/app-api/small/drive/school-course-order/getCourseByLoginUser',
					method: 'GET',
				}).then(res => {
					if (res.data === null) {
						// this.insertSchoolStudent()
					}
				})
			},

			insertSchoolStudent() {
				request({
					url: '/app-api/small/dl-drive-school-student/create',
					method: 'POST',
					data: this.userDetails
				})
				this.updateSysUsersNickName()
			},
			updateSysUsersNickName(name, userId, avatar) {
				request({
					url: '/app-api/system/user/update',
					method: 'PUT',
					headers: {
						'Content-Type': 'application/json'
					},
					data: {
						nickname: name,
						id: userId,
						avatar: avatar,
					}
				})
			},
			calculateScrollHeight() {
				// 获取屏幕高度
				const screenHeight = uni.getSystemInfoSync().windowHeight;
				// 获取顶部区域高度
				const topHeight = 150;
				// 计算滚动区域高度
				this.scrollHeight = screenHeight - topHeight;
			},


			handleSave() {
				if (!this.noN) {
					const submitData = {
						...this.userDetails,
						avatar: this.avatarList[0]?.fileName || '',
						idPhoto: this.idCardfileList.map(item => item.fileName).join(','),
						lifePhoto: this.lifePhotoFileList.map(item => item.fileName).join(',')
					}
					this.updateSysUsersNickName(submitData.name, submitData.userId, submitData.avatar)
					return
				}
				// 准备提交数据（只使用fileName）
				const submitData = {
					...this.userDetails,
					avatar: this.avatarList[0]?.fileName || '',
					idPhoto: this.idCardfileList.map(item => item.fileName).join(','),
					lifePhoto: this.lifePhotoFileList.map(item => item.fileName).join(',')
				}
				this.updateSysUsersNickName(submitData.name, submitData.userId, submitData.avatar)

				request({
					url: '/app-api/small/dl-drive-school-student/update',
					method: 'PUT',
					data: submitData
				}).then(() => {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					setTimeout(() => uni.navigateBack(), 1500)
				}).catch(() => {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				})
			}


		}
	};
</script>
<style lang='scss'>
	@import '../common/common.scss';
	@import './assets/style/index.rpx.scss';


	.group_7 {
		margin-top: 30rpx;
		padding: 0 30rpx;
		background-color: rgba(255, 255, 255, 1);
		border-radius: 16rpx;
		margin-left: 32rpx;
		margin-right: 32rpx;

		.text_10 {
			font-size: 28rpx;
			color: #333;
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			font-weight: bold;
		}

		// 可以添加自定义样式覆盖u-album的默认样式
		::v-deep .u-album {
			margin-top: 10rpx;
			margin: auto;
			margin-bottom: 20rpx;

			// 单图模式下的图片样式
			.u-album__single-image {
				border-radius: 8rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			}

			// 多图模式下的图片样式
			.u-album__image {
				border-radius: 8rpx;
			}
		}
	}
</style>