zhouxiantao
8 days ago 03193b2a27a2c23e10f3a2f298de9c1142116780
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/**
 * @author 韩天尊
 * @time 2024-01-15
 * @version 1.0.0
 * @description 登录页面组件
 */
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppContext } from '../context/AppContext';
import { authAPI } from '../services/api';
import PageHeader from '../components/PageHeader';
import './LoginPage.css';
 
const LoginPage: React.FC = () => {
    const navigate = useNavigate();
    const { state, dispatch } = useAppContext();
    const [isLogin, setIsLogin] = useState(true);
    const [formData, setFormData] = useState({
        name: '',
        phone: '',
        password: '',
        confirmPassword: ''
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [loginSuccess, setLoginSuccess] = useState(false);
    const [autoLoginLoading, setAutoLoginLoading] = useState(true);
 
    // 自动登录检查
    useEffect(() => {
        const checkAutoLogin = async () => {
            try {
                const fwmPhone = localStorage.getItem('fwmPhone');
                if (fwmPhone) {
                    // 如果有缓存的手机号,尝试获取用户信息
                    const response = await authAPI.getUserByPhone(fwmPhone);
                    if (response.code === 0 && response.data.user) {
                        // 缓存token和用户信息
                        localStorage.setItem('token', response.data.token);
                        localStorage.setItem('user', JSON.stringify(response.data.user));
                        dispatch({ type: 'SET_USER', payload: response.data.user });
                        
                        // 自动跳转到首页
                        navigate('/', { replace: true });
                        return;
                    } else {
                        // 如果获取用户信息失败,清除缓存
                        localStorage.removeItem('fwmPhone');
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                    }
                }
            } catch (error) {
                console.error('自动登录失败:', error);
                // 清除可能存在的无效缓存
                localStorage.removeItem('fwmPhone');
                localStorage.removeItem('token');
                localStorage.removeItem('user');
            } finally {
                setAutoLoginLoading(false);
            }
        };
        
        checkAutoLogin();
    }, [navigate, dispatch]);
 
    // 表单输入处理
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
        setError('');
    };
 
    // 表单提交处理
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError('');
 
        try {
            if (isLogin) {
                // 登录
                const response = await authAPI.login(formData.phone, formData.password);
                if (response.code === 0) {
                    console.log('response.data.token:', response.data.token);
                    localStorage.setItem('token', response.data.token);
                    localStorage.setItem('user', JSON.stringify(response.data.user));
                    // 缓存手机号用于下次自动登录
                    localStorage.setItem('fwmPhone', formData.phone);
                    dispatch({ type: 'SET_USER', payload: response.data.user });
                    
                    // 显示登录成功状态
                    setLoginSuccess(true);
                    setError('');
                    
                    // 延迟0.8秒后跳转到首页
                    setTimeout(() => {
                        navigate('/', { replace: true });
                    }, 800);
                } else {
                    throw new Error(response.msg || '登录失败');
                }
            } else {
                // 注册
                if (formData.password !== formData.confirmPassword) {
                    throw new Error('两次输入的密码不一致');
                }
                const response = await authAPI.register(formData.name, formData.phone, formData.password, '');
                if (response.code === 0) {
                    // 注册成功后自动登录
                    const loginResponse = await authAPI.login(formData.phone, formData.password);
                    if (loginResponse.code === 0) {
                        localStorage.setItem('token', loginResponse.data.token);
                        localStorage.setItem('user', JSON.stringify(loginResponse.data.user));
                        // 缓存手机号用于下次自动登录
                        localStorage.setItem('fwmPhone', formData.phone);
                        dispatch({ type: 'SET_USER', payload: loginResponse.data.user });
                        
                        // 显示注册成功状态
                        setLoginSuccess(true);
                        setError('');
                        
                        // 延迟0.8秒后跳转到首页
                        setTimeout(() => {
                            navigate('/', { replace: true });
                        }, 800);
                    }
                } else {
                    throw new Error(response.msg || '注册失败');
                }
            }
        } catch (error: any) {
            setError(error.message || '操作失败');
            setLoginSuccess(false);
        } finally {
            setLoading(false);
        }
    };
 
    // 切换登录/注册模式
    const toggleMode = () => {
        setIsLogin(!isLogin);
        setFormData({
            name: '',
            phone: '',
            password: '',
            confirmPassword: ''
        });
        setError('');
        setLoginSuccess(false);
    };
 
    // 如果正在自动登录检查,显示加载状态
    if (autoLoginLoading) {
        return (
            <div className="page">
                <div className="login-container">
                    <div className="login-header">
                        <div className="login-logo">
                            <i className="fas fa-heart icon-heart"></i>
                        </div>
                        <h2 className="login-title">志愿者服务平台</h2>
                        <p className="login-subtitle">正在检查登录状态...</p>
                    </div>
                    <div className="loading-container">
                        <div className="loading-spinner"></div>
                        <p>请稍候...</p>
                    </div>
                </div>
            </div>
        );
    }
 
    return (
        <div className="page">
            <div className="login-container">
                {/* 登录头部 */}
                <div className="login-header">
                    <div className="login-logo">
                        <i className="fas fa-heart icon-heart"></i>
                    </div>
                    <h2 className="login-title">志愿者服务平台</h2>
                    <p className="login-subtitle">欢迎使用社区志愿服务积分系统</p>
                </div>
 
                {/* 登录表单 */}
                <div className="login-form">
 
                    <form onSubmit={handleSubmit}>
                        {!isLogin && (
                            <div className="form-group">
                                <label>姓名</label>
                                <div className="input-wrapper">
                                    <i className="fas fa-user"></i>
                                    <input
                                        type="text"
                                        id="name"
                                        name="name"
                                        value={formData.name}
                                        onChange={handleInputChange}
                                        placeholder="请输入真实姓名"
                                        className="form-input"
                                        required={!isLogin}
                                    />
                                </div>
                            </div>
                        )}
 
                        <div className="form-group">
                            <label>手机号码</label>
                            <div className="input-wrapper">
                                <i className="fas fa-mobile-alt"></i>
                                <input
                                    type="tel"
                                    id="phone"
                                    name="phone"
                                    value={formData.phone}
                                    onChange={handleInputChange}
                                    placeholder="请输入手机号码"
                                    className="form-input"
                                    required
                                />
                            </div>
                        </div>
 
                        <div className="form-group">
                            <label>密码</label>
                            <div className="input-wrapper">
                                <i className="fas fa-lock"></i>
                                <input
                                    type="password"
                                    id="password"
                                    name="password"
                                    value={formData.password}
                                    onChange={handleInputChange}
                                    placeholder="请输入密码"
                                    className="form-input"
                                    required
                                />
                            </div>
                        </div>
 
                        {!isLogin && (
                            <div className="form-group">
                                <label>确认密码</label>
                                <div className="input-wrapper">
                                    <i className="fas fa-lock"></i>
                                    <input
                                        type="password"
                                        id="confirmPassword"
                                        name="confirmPassword"
                                        value={formData.confirmPassword}
                                        onChange={handleInputChange}
                                        placeholder="请再次输入密码"
                                        className="form-input"
                                        required={!isLogin}
                                    />
                                </div>
                            </div>
                        )}
 
                        {error && (
                            <div className="error-message">
                                <i className="fas fa-exclamation-circle"></i>
                                {error}
                            </div>
                        )}
 
                        {loginSuccess && (
                            <div className="success-message">
                                <i className="fas fa-check-circle"></i>
                                {isLogin ? '登录成功' : '注册成功'}
                            </div>
                        )}
 
                        {/* 登录按钮 */}
                        <div className="login-actions">
                            <button 
                                type="submit" 
                                className="login-btn"
                                disabled={loading || loginSuccess}
                            >
                                {loading ? (
                                    <>
                                        <span className="loading-spinner"></span>
                                        处理中...
                                    </>
                                ) : loginSuccess ? (
                                    <>
                                        <i className="fas fa-check"></i>
                                        <span>{isLogin ? '登录成功' : '注册成功'}</span>
                                    </>
                                ) : (
                                    <>
                                        <i className="fas fa-sign-in-alt"></i>
                                        <span>{isLogin ? '立即登录' : '立即注册'}</span>
                                    </>
                                )}
                            </button>
                        </div>
                    </form>
 
                    {/* 登录说明 */}
                    <div className="login-notice">
                        <div className="notice-item">
                            <i className="fas fa-info-circle"></i>
                            <span>首次登录将自动注册账号</span>
                        </div>
                        <div className="notice-item">
                            <i className="fas fa-shield-alt"></i>
                            <span>您的个人信息将被严格保密</span>
                        </div>
                    </div>
 
                    <div className="form-footer">
                        <button 
                            type="button" 
                            className="toggle-btn"
                            onClick={toggleMode}
                        >
                            {isLogin ? '还没有账号?立即注册' : '已有账号?立即登录'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};
 
export default LoginPage;