Files
web-Iot/src/pages/Profile.tsx

410 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useState, useEffect } from 'react';
import {
Card,
Form,
Input,
Button,
Upload,
message,
Tabs,
Avatar,
Row,
Col,
Divider,
Typography,
Space,
Radio,
} from 'antd';
import {
UserOutlined,
LockOutlined,
UploadOutlined,
PhoneOutlined,
MailOutlined,
SafetyOutlined,
EditOutlined,
ManOutlined,
WomanOutlined,
} from '@ant-design/icons';
import { useSelector } from 'react-redux';
import { RootState, useAppDispatch } from '../store';
import { setUserInfo } from '../store/userSlice';
import { getUserProfile, updateUserProfile, updateUserPwd, uploadAvatar } from '../api/user';
import envConfig from '../../env';
import utils from '../lib/utils';
import { useTranslation } from 'react-i18next';
const { TabPane } = Tabs;
const { Title } = Typography;
const Profile: React.FC = () => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [profileData, setProfileData] = useState<any>(null);
const { userInfo } = useSelector((state: RootState) => state.user);
const dispatch = useAppDispatch();
const [form] = Form.useForm();
const [pwdForm] = Form.useForm();
const message = utils.message; // 使用全局 message
const fetchProfile = async () => {
try {
const res: any = await getUserProfile();
if (res.code === 200) {
setProfileData(res.data);
form.setFieldsValue(res.data);
}
} catch (error) {
message.error(t('profile.getProfileFailed'));
}
};
useEffect(() => {
fetchProfile();
}, []);
const handleUpdateProfile = async (values: any) => {
setLoading(true);
try {
// 构建完整的个人信息对象,包含用户 ID 等必要字段
const updateData = {
...profileData,
...values,
};
const res: any = await updateUserProfile(updateData);
if (res.code === 200) {
message.success(t('profile.modifySuccess'));
const newUserInfo = { ...userInfo, ...values };
dispatch(setUserInfo(newUserInfo));
fetchProfile();
} else {
message.error(res.msg || t('profile.modifyFailed'));
}
} catch (error) {
message.error(t('profile.requestFailed'));
} finally {
setLoading(false);
}
};
const handleUpdatePwd = async (values: any) => {
if (values.newPassword !== values.confirmPassword) {
message.error(t('profile.passwordMismatch'));
return;
}
setLoading(true);
try {
const res: any = await updateUserPwd(values.oldPassword, values.newPassword);
if (res.code === 200) {
message.success(t('profile.passwordChanged'));
pwdForm.resetFields();
} else {
message.error(res.msg || t('profile.modifyFailed'));
}
} catch (error) {
message.error(t('profile.requestFailed'));
} finally {
setLoading(false);
}
};
const handleUpload = async (options: any) => {
const { file } = options;
const formData = new FormData();
formData.append('avatarfile', file);
try {
const res: any = await uploadAvatar(formData);
if (res.code === 200) {
message.success(t('profile.avatarUploadSuccess'));
const newUserInfo = { ...userInfo, avatar: res.imgUrl };
dispatch(setUserInfo(newUserInfo));
fetchProfile();
} else {
message.error(res.msg || t('profile.avatarUploadFailed'));
}
} catch (error) {
message.error(t('profile.avatarUploadFailed'));
}
};
const avatarUrl = profileData?.avatar
? profileData.avatar.startsWith('http')
? profileData.avatar
: `${envConfig.baseURL}${profileData.avatar}`
: null;
return (
<div style={{ padding: '20px 40px', background: '#f5f7fa', minHeight: '100vh' }}>
<Title level={4} style={{ marginBottom: 24, fontWeight: 600 }}>
{t('profile.title')}
</Title>
{/* 🔥 关键:给 Row 添加 align="stretch" 让两列自动等高 */}
<Row gutter={24} align="stretch">
{/* 左侧信息卡片 */}
<Col xs={24} sm={24} md={8} lg={7} xl={6}>
<Card
variant="borderless"
style={{
borderRadius: 12,
boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
textAlign: 'center',
overflow: 'hidden',
height: '100%', // 🔥 高度 100%
display: 'flex',
flexDirection: 'column',
}}
>
<div style={{ padding: '20px 0', flex: 1 }}> {/* 🔥 自动填充高度 */}
<Avatar
size={120}
src={avatarUrl}
icon={<UserOutlined style={{ fontSize: 50 }} />}
style={{
border: '6px solid #fff',
boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
}}
/>
<div style={{ marginTop: 20 }}>
<Upload customRequest={handleUpload} showUploadList={false} accept="image/*">
<Button
icon={<UploadOutlined />}
style={{
borderRadius: 6,
borderColor: '#d9d9d9',
}}
>
{t('profile.changeAvatar')}
</Button>
</Upload>
</div>
</div>
<Divider style={{ margin: '12px 0' }} />
<div style={{ textAlign: 'left', padding: '8px 12px' }}>
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<div style={{ display: 'flex', alignItems: 'center', fontSize: 14 }}>
<UserOutlined style={{ marginRight: 12, color: '#165DFF', fontSize: 16 }} />
<span style={{ color: '#666' }}>{t('profile.username')}:</span>
<strong style={{ marginLeft: 4, color: '#333' }}>{profileData?.userName}</strong>
</div>
<div style={{ display: 'flex', alignItems: 'center', fontSize: 14 }}>
<PhoneOutlined style={{ marginRight: 12, color: '#165DFF', fontSize: 16 }} />
<span style={{ color: '#666' }}>{t('profile.phone')}:</span>
<strong style={{ marginLeft: 4, color: '#333' }}>{profileData?.phonenumber || t('profile.notSet')}</strong>
</div>
<div style={{ display: 'flex', alignItems: 'center', fontSize: 14 }}>
<MailOutlined style={{ marginRight: 12, color: '#165DFF', fontSize: 16 }} />
<span style={{ color: '#666' }}>{t('profile.email')}:</span>
<strong style={{ marginLeft: 4, color: '#333' }}>{profileData?.email || t('profile.notSet')}</strong>
</div>
<div style={{ display: 'flex', alignItems: 'center', fontSize: 14 }}>
<SafetyOutlined style={{ marginRight: 12, color: '#165DFF', fontSize: 16 }} />
<span style={{ color: '#666' }}>{t('profile.role')}:</span>
<strong style={{ marginLeft: 4, color: '#333' }}>
{profileData?.roles?.map((r: any) => r.roleName).join(', ') || t('profile.notSet')}
</strong>
</div>
</Space>
</div>
</Card>
</Col>
{/* 右侧表单卡片 */}
<Col xs={24} sm={24} md={16} lg={17} xl={18}>
<Card
variant="borderless"
style={{
borderRadius: 12,
boxShadow: '0 2px 12px rgba(0,0,0,0.06)',
overflow: 'hidden',
height: '100%', // 🔥 高度 100%
}}
>
<Tabs
defaultActiveKey="1"
type="card"
style={{
marginTop: -8,
}}
>
{/* 基本资料 */}
<TabPane tab={t('profile.basicInfo')} key="1">
<div style={{ maxWidth: 500, margin: '0 auto', padding: '12px 0' }}>
<Form
form={form}
layout="vertical"
onFinish={handleUpdateProfile}
initialValues={profileData}
size="large"
>
<Form.Item
label={t('profile.username')}
name="userName"
>
<Input
prefix={<UserOutlined />}
disabled
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item
label={t('users.nicknameLabel')}
name="nickName"
rules={[{ required: true, message: t('profile.nicknamePlaceholder') }]}
>
<Input
prefix={<UserOutlined />}
placeholder={t('profile.nicknamePlaceholder')}
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item
label={t('users.genderLabel')}
name="sex"
>
<Radio.Group>
<Radio value="0"><ManOutlined /> {t('profile.male')}</Radio>
<Radio value="1"><WomanOutlined /> {t('profile.female')}</Radio>
</Radio.Group>
</Form.Item>
<Form.Item
label={t('users.phoneLabel')}
name="phonenumber"
rules={[{ pattern: /^1[3-9]\d{9}$/, message: t('profile.phoneInvalid') }]}
>
<Input
prefix={<PhoneOutlined />}
placeholder={t('profile.phonePlaceholder')}
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item
label={t('users.email')}
name="email"
rules={[{ type: 'email', message: t('profile.emailInvalid') }]}
>
<Input
prefix={<MailOutlined />}
placeholder={t('profile.emailPlaceholder')}
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item
label={t('roles.remark')}
name="remark"
>
<Input.TextArea
placeholder={t('profile.remarkPlaceholder')}
style={{ borderRadius: 6 }}
rows={3}
/>
</Form.Item>
<Form.Item style={{ marginTop: 28 }}>
<Button
type="primary"
htmlType="submit"
loading={loading}
icon={<EditOutlined />}
style={{
borderRadius: 6,
height: 42,
width: 160,
}}
>
{t('profile.saveChanges')}
</Button>
</Form.Item>
</Form>
</div>
</TabPane>
{/* 修改密码 */}
<TabPane tab={t('profile.changePassword')} key="2">
<div style={{ maxWidth: 500, margin: '0 auto', padding: '12px 0' }}>
<Form
form={pwdForm}
layout="vertical"
onFinish={handleUpdatePwd}
size="large"
>
<Form.Item
label={t('profile.oldPassword')}
name="oldPassword"
rules={[{ required: true, message: t('profile.oldPasswordPlaceholder') }]}
>
<Input.Password
prefix={<LockOutlined />}
placeholder={t('profile.oldPasswordPlaceholder')}
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item
label={t('profile.newPassword')}
name="newPassword"
rules={[
{ required: true, message: t('profile.newPasswordPlaceholder') },
{ min: 6, message: t('profile.passwordLengthError') },
]}
>
<Input.Password
prefix={<LockOutlined />}
placeholder={t('profile.newPasswordPlaceholder')}
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item
label={t('profile.confirmPassword')}
name="confirmPassword"
rules={[{ required: true, message: t('profile.confirmPasswordRequired') }]}
>
<Input.Password
prefix={<LockOutlined />}
placeholder={t('profile.confirmPasswordPlaceholder')}
style={{ borderRadius: 6 }}
/>
</Form.Item>
<Form.Item style={{ marginTop: 28 }}>
<Button
type="primary"
htmlType="submit"
loading={loading}
icon={<EditOutlined />}
style={{
borderRadius: 6,
height: 42,
width: 160,
}}
>
{t('profile.confirmChange')}
</Button>
</Form.Item>
</Form>
</div>
</TabPane>
</Tabs>
</Card>
</Col>
</Row>
</div>
);
};
export default Profile;