File size: 12,213 Bytes
708809b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import BasicTemplate from "../templates/BasicTemplate";
import { Container, Form, Row, Col, Card, Alert, Button, Image } from "react-bootstrap";
import React, { useState, useEffect } from "react";
import validator from "validator";
import axios from "axios";
import DataStorage from "../organisms/DataStorage";

export default function UserInfoPage() {

    // fetch data:

    const [error, setErrors] = useState("");
    const [initialData, setInitialData] = useState(null);
    const [formData, setFormData] = useState({
        avatar: "/default_avatar.jpg",
        full_name: "",
        phone_number: "",
        address: "",
        email: "",
        password: "",
        confirmPassword: "",
    });

    useEffect(() => {
        axios
            .get(process.env.REACT_APP_API_URL + '/authentication/profile', {
                headers: {
                    Authorization: `Bearer ${DataStorage.get('accessToken')}`,
                },
            })
            .then((response) => {
                if (response.status === 401) {
                    // phiên hết hạn
                    setErrors(JSON.stringify(response));
                } else {
                    const { avatar, full_name, address, phone_number, email } = response.data;
                    const fetchedData = {
                        avatar: avatar || "/default_avatar.jpg",
                        full_name: full_name || "",
                        phone_number: phone_number || "",
                        address: address || "",
                        email: email || "",
                        password: "",
                        confirmPassword: "",
                    };

                    if (fetchedData.full_name !== DataStorage.get('username')) DataStorage.set('username', fetchedData.full_name)
                    setInitialData(fetchedData);
                    setFormData(fetchedData);
                }
            })
            .catch((error) => {
                setErrors(JSON.stringify(error));
            });
    }, []);

    // console.log('formdata', formData);
    // console.log('initialdata', initialData);
    // State để hiển thị lỗi khi validation

    const [isChanged, setChanged] = useState(false);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value });
    };

    // Hàm xử lý thay đổi avatar
    const handleAvatarChange = (e) => {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onloadend = () => {
            setFormData((prevData) => ({
              ...prevData,
              avatar: reader.result // Cập nhật ảnh đại diện
            }));
          };
          reader.readAsDataURL(file);
          setChanged(true);
        }
      };

    useEffect(() => {
        const hasChanges = () => {
            if (initialData) {
                for (let key in formData) {
                    if (formData[key] !== initialData[key]) {
                        return true;
                    }
                }
                return false;
            } else {
                return false;
            }
        };
        setChanged(hasChanges());
    }, [formData, initialData]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setChanged(false); // prevent another click
        if (formData.phone_number.trim() !== "" && !validator.isMobilePhone(formData.phone_number, 'vi-VN')) setErrors("Số điện thoại không hợp lệ");
        else if (formData.email.trim() !== "" && !validator.isEmail(formData.email)) setErrors("Email không hợp lệ");
        else if (formData.password !== "" && formData.confirmPassword !== formData.password) setErrors("Mật khẩu không khớp");
        else {

            // let avatarBase64 = null;

            // if (formData.avatar) {
            //     // Chuyển ảnh đại diện thành chuỗi Base64
            //     avatarBase64 = await new Promise((resolve, reject) => {
            //         const reader = new FileReader();
            //         reader.onloadend = () => resolve(reader.result.split(",")[1]); // Chỉ lấy phần Base64
            //         reader.onerror = (error) => reject(error);
            //         reader.readAsDataURL(formData.avatar);
            //     });
            // }

            let data = {};

            // if (avatarBase64) data.avatar = avatarBase64;
            if (formData.full_name.trim() !== "" && formData.full_name.trim() !== initialData.full_name) data.full_name = formData.full_name.trim();
            if (formData.phone_number.trim() !== "" && formData.phone_number.trim() !== initialData.phone_number) data.phone_number = formData.phone_number.trim();
            if (formData.address.trim() !== "" && formData.address.trim() !== initialData.address) data.address = formData.address.trim();
            if (formData.email.trim() !== "" && formData.email.trim() !== initialData.email) data.email = formData.email.trim();
            if (formData.password.trim() !== "") data.hash_password = formData.password;

            // gửi request ở đây
            axios.post(process.env.REACT_APP_API_URL + '/users/updateUser', data, {
                headers: {
                    Authorization: `Bearer ${DataStorage.get('accessToken')}`,
                }
            }).then((response) => {
                if (response.status === 200 || response.status === 201) {
                    window.location.reload(); // cập nhật lại thông tin
                } else {
                    setErrors(JSON.stringify(response));
                }
            }).catch((error) => setErrors(JSON.stringify(error)));
        }
    };

    return <BasicTemplate content={
        (
            <Container fluid className="d-flex align-items-center justify-content-center mt-5">
                <Row>
                    <Col xs={1} md={2}></Col>
                    <Col xs={10} md={8}>
                        <Card style={{ width: '30rem' }} className='justify-content-center'>
                            <Card.Header>
                                <Card.Title className='mt-1 text-center'>Thông tin khách hàng</Card.Title>
                            </Card.Header>
                            <Card.Body>

                                <Form onSubmit={handleSubmit}>
                                    {error && <Alert variant="danger">{error}</Alert>}
                                    <Row className="mb-3">
                                        <Col xs={12} md={6} className="text-center">
                                            {/*Image*/}
                                            <Image
                                                src={formData.avatar} // Hiển thị ảnh đại diện từ formData
                                                alt="User Avatar"
                                                roundedCircle
                                                width={120}
                                                height={120}
                                            />
                                            <Form.Group controlId="formAvatar">
                                                <Form.Label>Ảnh đại diện</Form.Label>
                                                <Form.Control type="file" accept="image/*" onChange={handleAvatarChange} />
                                            </Form.Group>
                                        </Col>
                                        <Col xs={12} md={6}>
                                            <Form.Group controlId="formUsername">
                                                <Form.Label>Họ tên người dùng</Form.Label>
                                                <Form.Control
                                                    type="text"
                                                    name="full_name"
                                                    placeholder="Họ tên người dùng"
                                                    value={formData.full_name}
                                                    onChange={handleChange}
                                                />
                                            </Form.Group>
                                        </Col>
                                    </Row>

                                    <Form.Group controlId="formPhone" className="mb-3">
                                        <Form.Label>Số điện thoại</Form.Label>
                                        <Form.Control
                                            type="text"
                                            name="phone_number"
                                            placeholder="Số điện thoại"
                                            value={formData.phone_number}
                                            onChange={handleChange}
                                        />
                                    </Form.Group>

                                    <Form.Group controlId="formAddress" className="mb-3">
                                        <Form.Label>Địa chỉ giao hàng mặc định</Form.Label>
                                        <Form.Control
                                            type="text"
                                            name="address"
                                            placeholder="Địa chỉ giao hàng"
                                            value={formData.address}
                                            onChange={handleChange}
                                        />
                                    </Form.Group>

                                    <Form.Group controlId="formEmail" className="mb-3">
                                        <Form.Label>Email</Form.Label>
                                        <Form.Control
                                            type="text"
                                            name="email"
                                            placeholder="Email"
                                            value={formData.email}
                                            onChange={handleChange}
                                        />
                                    </Form.Group>

                                    <Form.Group controlId="formPassword" className="mb-3">
                                        <Form.Label>Password</Form.Label>
                                        <Form.Control
                                            type="password"
                                            name="password"
                                            placeholder="********"
                                            value={formData.password}
                                            onChange={handleChange}
                                        />
                                    </Form.Group>

                                    <Form.Group controlId="formConfirmPassword" className="mb-3">
                                        <Form.Label>Nhập lại Password</Form.Label>
                                        <Form.Control
                                            type="password"
                                            name="confirmPassword"
                                            placeholder="********"
                                            value={formData.confirmPassword}
                                            onChange={handleChange}
                                        />
                                    </Form.Group>

                                    <Button variant="primary" type="submit" disabled={!isChanged}>
                                        Cập nhật
                                    </Button>
                                </Form>
                            </Card.Body>
                        </Card>

                    </Col>
                    <Col xs={1} md={2}></Col>
                </Row>


            </Container>
        )
    } />
}