<template>
	<el-row class="top" justify="space-between">
		<h2>个人信息</h2>
		<el-col :span="6">
			<el-button type="danger" @click="handleLogout">注销账号</el-button>
		</el-col>
	</el-row>
	<el-row class="body">
			<el-upload class="avatar-uploader" action="http://localhost:8080/file/upload" :show-file-list="false"
			:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
			<img v-if="formData.avatar" width="100px" height="100px" :src="formData.avatar" class="avatar">
			<el-icon v-else class="avatar-uploader-icon">
				<Plus />
			</el-icon>
		</el-upload>
		<el-text class="phone">{{ formData.username }}</el-text>
		<el-form label-width="auto" style="max-width: 600px">
			<el-form-item label="性别">
				<el-radio-group v-model="formData.gender">
					<el-radio label="男">男</el-radio>
					<el-radio label="女">女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="地区">
				<el-cascader :options="pcaTextArr" v-model="formData.address" placeholder="请选择地区"
					:props="{ checkStrictly: true }" />
			</el-form-item>
			<el-form-item label="绑定手机">
				<el-input v-model="formData.mobile" placeholder="请输入手机号" />
			</el-form-item>
			<el-form-item label="绑定邮箱">
				<el-input v-model="formData.email" placeholder="请输入邮箱" />
			</el-form-item>
			<el-form-item style="margin-top: 30px;">
				<el-button @click="handleChanges" style="margin-left: 100px;">保存信息</el-button>
			</el-form-item>
		</el-form>
		<el-dialog v-model="isDialogVisible" title="确认注销" width="500px" :custom-class="'custom-dialog'">
			<span>确定要注销账号吗？</span>
			<template #footer>
				<el-button @click="isDialogVisible = false">取消</el-button>
				<el-button type="danger" @click="confirmLogout">确认注销</el-button>
			</template>
		</el-dialog>
		<el-dialog v-model="isDialogVisibleSave" title="确认保存" width="500px">
			<span>信息已修改，是否保存更改？</span>
			<template #footer>
				<el-button @click="isDialogVisibleSave=false">取消</el-button>
				<el-button type="primary" @click="confirmChanges">确认</el-button>
			</template>
		</el-dialog>
	</el-row>
</template>

<script lang="ts" setup>
	import { ref, reactive } from 'vue';
	import { useRouter } from 'vue-router';
	import { ElMessage } from 'element-plus';
	import { pcaTextArr } from 'element-china-area-data';
	import request from '../../request.js';
	import { useUserStore } from '../../stores/user';
	
	const userStore = useUserStore();
	const router = useRouter();
	const isDialogVisible = ref(false);
	const isDialogVisibleSave = ref(false);
	

	const formData = reactive({
		username: '',
		gender: '',
		address: [],
		mobile: '',
		avatar: '',
		email:''
	});

	// 初始化用户数据
	request.get('http://localhost:8080/user/info').then(res=> {
			if (res.data.code == '200') {
				const userInfo = res.data.data;
				formData.username = userInfo.username;
				formData.gender = userInfo.gender;
				formData.address = userInfo.address ? userInfo.address.split(' ') : [];
				formData.mobile = userInfo.mobile;
				formData.avatar = userInfo.avatar;
				formData.email = userInfo.email;
			}
		})
		.catch((error) => {
			console.error('请求用户信息失败:', error);
			ElMessage.error('请求用户信息失败，请检查网络连接或联系管理员。');
		});

	const handleChanges = () => {
		isDialogVisibleSave.value = true;
	};

	const confirmChanges = () => {
		request.post('http://localhost:8080/user', {
				username:formData.username,
				gender: formData.gender,
				address: formData.address.join(' '),
				mobile: formData.mobile,
				email: formData.email,
				avatar: formData.avatar
			})
			.then((res) => {
				if (res.data.code == '200') {
					let user = JSON.parse(localStorage.getItem("user") || '{}');
					user.avatar = formData.avatar;
					userStore.setUser(formData);
					ElMessage.success('个人信息保存成功');
				} else {
					ElMessage.error('个人信息保存失败');
				}
			})
			.catch((error) => {
				console.error('保存信息失败:', error);
				ElMessage.error('保存信息失败，请稍后再试');
			});
		isDialogVisibleSave.value = false;
	};

	const handleLogout = () => {
		isDialogVisible.value = true;
	};

	const confirmLogout = () => {
		router.push('/login');
		localStorage.removeItem('user');
		ElMessage.success('退出成功');
	};


	const handleAvatarSuccess = (response) => {
	  if (response && response.data) {
	    formData.avatar = response.data; // 后端返回完整路径
	    ElMessage.success("头像上传成功");
	  } else {
	    ElMessage.error("上传失败，请联系管理员");
	  }
	};
	
	const beforeAvatarUpload = (file) => {
	  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	  const isLt2M = file.size / 1024 / 1024 < 2;
	
	  if (!isJPGorPNG) {
	    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
	  }
	  if (!isLt2M) {
	    ElMessage.error("上传头像图片大小不能超过 2MB!");
	  }
	  return isJPGorPNG && isLt2M;
	};
</script>

<style>
	.top {
		background-color: white;
		height: 50px;
		flex-wrap: nowrap;
		justify-content: space-between;
		align-items: center;
		border-radius: 5px;
		margin-bottom: 15px;
		padding-left: 15px;
	}

	.body {
		background-color: white;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		line-height: 0px;
		height: 90vh;
	}

	.phone {
		margin-top: 20px;
		font-size: 14px;
		margin-bottom: 20px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.avatar-uploader .avatar {
		width: 100px;
		height: 100px;
		display: block;
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		text-align: center;
	}
</style>