<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 :style="{ height: scrollHeight + 'px' }">
			<view class="block_2 flex-col">
				<!-- <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">
							<!-- <view v-if="idCardList.length > 0" class="flex-row">
              <image
                  v-for="(item, index) in idCardList"
                  :key="index"
                  class="image_3"
                  :style="{ marginRight: index === 0 ? '20rpx' : '0' }"
                  :src="imageUrl + '/' + item"
                  referrerpolicy="no-referrer"
              />
            </view>
            <image
                v-else
                class="image_3"
                src="/static/lanhu_gerenxinxiweitianxie/FigmaDDSSlicePNG613ddce187a71bcc667c56c84cd2d022.png"
                referrerpolicy="no-referrer"
            /> -->
						</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">
							<!-- <view class="flex-row">
              <view
                  class="list-items_1 flex-col"
                  v-for="(item, index) in lifePhotoList"
                  :key="index"
              >
                <image
                    class="list-items_1"
                    referrerpolicy="no-referrer"
                    :src="imageUrl + '/' + item"
                />
              </view>
              <image
                  v-if="lifePhotoList.length === 0"
                  class="list-items_1"
                  referrerpolicy="no-referrer"
                  src="/static/lanhu_gerenxinxiweitianxie/FigmaDDSSlicePNG6ea89e46a56641bc7e118ef1d4d789d5.png"
              />
            </view> -->
						</u-upload>

					</view>
				</view>
			</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: [],
				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 => {
					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()}`
							}
						})) :
						[];
				});
			},

			// 头像上传
			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 = 145;
				// 计算滚动区域高度
				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';
</style>