<template>
	<view class="info-item">
		<view class="item-label">
			<text>姓名：</text>
		</view>
		<view class="item-content">
			<input v-model="name" type="text" placeholder="请输入姓名" />
		</view>
	</view>
	<view class="info-item">
		<view class="item-label">
			<text>身份证号：</text>
		</view>
		<view class="item-content">
			<input v-model="idNumber" type="idcard" placeholder="请输入身份证号" maxlength="18" />
		</view>
	</view>
	<view class="update-button">
		<button @click="updateUserInfo">确定</button>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '../../store/userStore'
	let name = ref('')
	let idNumber = ref('')
	let user = useUserStore()
	let userInfo = useUserStore().userInfo

	async function updateUserInfo() {
		if (!name.value || name.value.length < 2) {
			uni.showToast({
				icon: 'none',
				title: '姓名格式错误！'
			})
			return;
		}
		if (!idNumber.value || idNumber.value.length < 18) {
			uni.showToast({
				icon: 'none',
				title: '身份证格式错误！'
			})
			return;
		}
		if (name.value !== userInfo.name || idNumber.value !== userInfo.idNumber) {
			let res = await uni.request({
				url: '/user',
				method: 'PUT',
				data: {
					name: name.value,
					idNumber: idNumber.value
				}
			})
			if (res.data.success) {
				userInfo.name = name.value
				userInfo.idNumber = idNumber.value
				user.updateUserInfo(userInfo)
				uni.showToast({
					icon: 'none',
					title: '修改成功！'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			} else {
				uni.showToast({
					icon: 'none',
					title: '修改失败！'
				})
			}
		} else {
			uni.showToast({
				icon: 'none',
				title: '修改成功！'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1000)
		}
	}

	onLoad(() => {
		name.value = userInfo.name
		idNumber.value = userInfo.idNumber
	})
</script>

<style lang="scss">
	.info-item {
		height: 100rpx;
		display: flex;
		align-items: center;
		margin: 0 40rpx;
		border-bottom: #000000 2rpx solid;

		.item-label {
			width: 30vw;
		}

		.item-content {
			input {
				// background-color: #666666;
				border: #d3d3d3 2rpx solid;
				padding: 10rpx;
				width: 50vw;
			}
		}
	}

	.update-button {
		button {
			margin: 40rpx auto;
			width: 80vw;
			background-color: #a09cc4;
			color: #ffffff;
		}
	}
</style>