Product.js 11.5 KB
Newer Older
1
import axios from 'axios';
kusang96's avatar
kusang96 committed
2
import React, { useState, useEffect, useRef } from 'react';
Jiwon Yoon's avatar
Jiwon Yoon committed
3
4
import { Row, Col, Form, Card, Button, Modal } from 'react-bootstrap';
import { Redirect, useHistory } from 'react-router-dom';
5
import catchErrors from '../utils/catchErrors';
kusang96's avatar
kusang96 committed
6
7


8
function Product({ match, location }) {
kusang96's avatar
0115    
kusang96 committed
9
    const [product, setProduct] = useState(location.state)
Jiwon Yoon's avatar
Jiwon Yoon committed
10
11
12
    const [color, setColor] = useState("")
    const [size, setSize] = useState("")
    const [cart, setCart] = useState([])
13
    const [error, setError] = useState('')
14
    const [selected, setSelected] = useState({ sizes: false, colors: false })
Jiwon Yoon's avatar
Jiwon Yoon committed
15
    const [count, setCount] = useState(1)
Jiwon Yoon's avatar
0113    
Jiwon Yoon committed
16
    const [price, setPrice] = useState(0)
Jiwon Yoon's avatar
Jiwon Yoon committed
17
18
19
20
21
    const [show, setShow] = useState(false);
    let history = useHistory();
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

Jiwon Yoon's avatar
Jiwon Yoon committed
22

23
    useEffect(() => {
Jiwon Yoon's avatar
Jiwon Yoon committed
24
        if (size && color) {
25
            pushOptions()
Jiwon Yoon's avatar
Jiwon Yoon committed
26
            // console.log(cart)
Jiwon Yoon's avatar
Jiwon Yoon committed
27
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
28
    }, [size, color])
kusang96's avatar
kusang96 committed
29
30
31
32
33
34

    function handleClick(e) {
        const box = e.target.parentNode.parentNode
        box.style.display = "none"
    }

35
    function pushOptions() {
Jiwon Yoon's avatar
Jiwon Yoon committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
        // console.log(cart)
        const a = cart.map(el => {
            const rObj = {}
            rObj["color"] = el.color;
            rObj["size"] = el.size;
            return rObj
        })
        const isDuplicated = a.some(el => el.color === color && el.size === size)
        if (isDuplicated) {
            selected.sizes = false
            selected.colors = false
            setColor("")
            setSize("")
            alert("이미 선택한 옵션입니다.")
        } else {
            selected.sizes = false
            selected.colors = false
            setCart([...cart, { color, size, productId: product.id, count: 1 }])
            setColor("")
            setSize("")
            setPrice(product.price + price)
        }

59
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
60

kusang96's avatar
kusang96 committed
61
62
    function handleChange(e) {
        const { name, value } = e.target
Jiwon Yoon's avatar
Jiwon Yoon committed
63
64
        if (name === "sizes") {
            setSize(value)
65
            selected.sizes = true
Jiwon Yoon's avatar
Jiwon Yoon committed
66
67
        } else if (name === "colors") {
            setColor(value)
68
69
            selected.colors = true
        }
kusang96's avatar
kusang96 committed
70
71
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
72
    function deleteOption(e) {
kusang96's avatar
kusang96 committed
73
        e.preventDefault()
74
        let preprice = 0
Jiwon Yoon's avatar
Jiwon Yoon committed
75
        const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
Jiwon Yoon's avatar
Jiwon Yoon committed
76
77
        asd.map((el) => {
            preprice = preprice + el.count * product.price
78
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
79
        setCart(asd)
80
        setPrice(Number(preprice))
kusang96's avatar
kusang96 committed
81
82
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
83
    function handleCount(e) {
84
85
86
        const addCount = cart.map((el) => {
            if (el.color !== e.target.id || el.size !== e.target.name) {
                return { ...el }
Jiwon Yoon's avatar
Jiwon Yoon committed
87
            } else {
88
                return { ...el, count: e.target.value }
Jiwon Yoon's avatar
Jiwon Yoon committed
89
90
            }
        })
91
        let preprice = 0
Jiwon Yoon's avatar
Jiwon Yoon committed
92
93
        addCount.map((el) => {
            preprice = preprice + el.count * product.price
94
95
        })
        setPrice(Number(preprice))
Jiwon Yoon's avatar
Jiwon Yoon committed
96
        setCart(addCount)
Jiwon Yoon's avatar
Jiwon Yoon committed
97
        setCount(e.value)
kusang96's avatar
kusang96 committed
98
99
    }

Jiwon Yoon's avatar
Jiwon Yoon committed
100
    async function addCart(event) {
Jiwon Yoon's avatar
Jiwon Yoon committed
101
        console.log(cart)
Jiwon Yoon's avatar
Jiwon Yoon committed
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
        if (cart.length < 1) {
            alert("옵션을 선택해주세요")
        }
        else if (localStorage.getItem('id')) {
            if (event.target.name === "shoppingcart") {
                // preCart(color, size, count), productId(productlist에서 props), userId(로컬) 를 보내줌
                try {
                    setError('')
                    const response = await axios.put('/api/cart/addcart', {
                        userId: localStorage.getItem('id'),
                        products: cart
                    })
                    console.log(response.data)
                    setShow(true)
                } catch (error) {
                    catchErrors(error, setError)
                }
            } else {
                try {
                    setError('')
                    const response = await axios.put('/api/cart/addcart', {
                        userId: localStorage.getItem('id'),
                        products: cart
                    })
                    console.log(response.data)
                    history.push("/payment")
                } catch (error) {
                    catchErrors(error, setError)
                }
Jiwon Yoon's avatar
Jiwon Yoon committed
131
            }
Jiwon Yoon's avatar
Jiwon Yoon committed
132

Jiwon Yoon's avatar
Jiwon Yoon committed
133
134
135
        } else {
            alert("로그인을 해주세요.")
            return <Redirect to='/login' />
136
137
138
        }
    }

kusang96's avatar
kusang96 committed
139
140
141

    return (
        <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
142
143
144
145
146
147
148
149
150
151
152
            <Modal show={show} onHide={handleClose}>
                <Modal.Header closeButton>
                    <Modal.Title>장바구니에 상품담기</Modal.Title>
                </Modal.Header>
                <Modal.Body>정상적으로 장바구니에 상품을 담았습니다.</Modal.Body>
                <Modal.Footer>
                    <Button variant="secondary" onClick={handleClose}>쇼핑계속하기</Button>
                    <Button variant="primary" href='/shoppingcart'>장바구니로 이동</Button>
                </Modal.Footer>
            </Modal>
            {/* {console.log(cart)} */}
kusang96's avatar
kusang96 committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
            <style type="text/css">
                {`
                .btn {
                    background-color: #CDC5C2;
                    border-color: #CDC5C2;
                }

                .btn:hover, .btn:active, .btn:focus {
                    background-color: #91877F;
                    border-color: #91877F;
                }
                `}
            </style>
            <Row className="justify-content-center mt-5 mx-0">
                <Col sm={11} md={4}>
Jiwon Yoon's avatar
asdf    
Jiwon Yoon committed
168
                    <img src={`/images/${product.main_img}`} style={{ objectFit: "contain", width: "100%" }} />
kusang96's avatar
kusang96 committed
169
170
                </Col>
                <Col sm={11} md={4} className="align-middle mt-4">
kusang96's avatar
0115    
kusang96 committed
171
172
                    <h3 className="mb-4">{product.name}</h3>
                    <h5 className="mb-4">가격 : {product.price}</h5>
kusang96's avatar
kusang96 committed
173
174
175
                    <Form style={{ borderBottom: "1px solid" }}>
                        <Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}>
                            <Form.Label>색상</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
176
                            <Form.Control as="select" className="mb-2" name="colors" value={color} defaultValue="옵션 선택" onChange={handleChange}>
kusang96's avatar
kusang96 committed
177
                                <option>옵션선택</option>
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
178
179
180
                                {product.colors.map((e) => (
                                    <option>{e}</option>
                                ))}
kusang96's avatar
kusang96 committed
181
182
                            </Form.Control>
                            <Form.Label>사이즈</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
183
                            <Form.Control as="select" className="mb-2" name="sizes" value={size} defaultValue="옵션 선택" onChange={handleChange}>
kusang96's avatar
kusang96 committed
184
                                <option>옵션선택</option>
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
185
186
187
                                {product.sizes.map((e) => (
                                    <option>{e}</option>
                                ))}
kusang96's avatar
kusang96 committed
188
189
                            </Form.Control>
                        </Form.Group>
Jiwon Yoon's avatar
Jiwon Yoon committed
190
                        {cart.map((e) => (
191
192
193
                            <Row className="mx-1">
                                <Col xs={6}>{e.color}/{e.size}</Col>
                                <Col xs={4} className="text-right" >
Jiwon Yoon's avatar
Jiwon Yoon committed
194
                                    <input type='number' id={e.color} name={e.size} onChange={handleCount} value={count} style={{ width: '3rem' }} className="text-center" />
195
196
197
198
199
                                </Col>
                                <Col xs={2} className="text-right">
                                    <input onClick={deleteOption} id={e.color} name={e.size} type="image" alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="align-middle" />
                                </Col>
                            </Row>
Jiwon Yoon's avatar
Jiwon Yoon committed
200

201
                        ))}
kusang96's avatar
kusang96 committed
202
203
                        <Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
                            <Col> 금액</Col>
Jiwon Yoon's avatar
0113    
Jiwon Yoon committed
204
                            <Col className="text-right">{price}</Col>
kusang96's avatar
kusang96 committed
205
206
                        </Row>
                        <Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
Jiwon Yoon's avatar
Jiwon Yoon committed
207
208
                            <Button type='button' name="shoppingcart" onClick={addCart} style={{ width: "49%" }}>장바구니</Button>
                            <Button type='button' name="payment" onClick={addCart} style={{ width: "49%" }}>구매하기</Button>
kusang96's avatar
kusang96 committed
209
210
211
212
213
214
215
216
217
218
219
220
221
                        </Row>
                    </Form>
                </Col>
            </Row>
            <Row className="justify-content-center mt-5 mx-0">
                <Col sm={11} md={8}>
                    <h3 style={{ borderBottom: "1px solid #91877F", paddingBottom: "5px", marginBottom: "1em" }}>설명</h3>
                    <div></div>
                </Col>
            </Row>
            <Row className="justify-content-center mx-0 pt-3 px-2" style={{ position: "fixed", bottom: "0", width: "100%", backgroundColor: "#fff" }}>
                <Col sm={12} md={9}>
                    <h6 style={{ borderBottom: "1px solid", paddingBottom: "5px", marginBottom: "1em" }}>회원님이 선호할만한 상품 추천
박상호's avatar
0120    
박상호 committed
222
                        <a className="close float-right" onClick={(e) => handleClick(e)} style={{ fontSize: "1rem", cursor: "pointer" }}>X</a>
kusang96's avatar
kusang96 committed
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
                    </h6>
                    <Row className="justify-content-space mx-0" style={{ flexWrap: "nowrap", width: "100%", overflowX: "auto" }}>
                        <Col as={Card} style={{ minWidth: "10rem", marginRight: "1rem" }}>
                            <Card.Img variant="top" src="https://img.sonyunara.com/files/goods/67504/1607328307_0.jpg" style={{ objectFit: "contain" }} />
                            <Card.Body className="px-0">
                                <Card.Title>클로타탄원피스</Card.Title>
                                <Card.Text>구매자 : 30</Card.Text>
                            </Card.Body>
                        </Col>
                        <Col as={Card} style={{ minWidth: "10rem", marginRight: "1rem" }}>
                            <Card.Img variant="top" src="https://img.sonyunara.com/files/goods/67504/1607328307_0.jpg" style={{ objectFit: "contain" }} />
                            <Card.Body className="px-0">
                                <Card.Title>클로타탄원피스</Card.Title>
                                <Card.Text>구매자 : 30</Card.Text>
                            </Card.Body>
                        </Col>
                        <Col as={Card} style={{ minWidth: "10rem", marginRight: "1rem" }}>
                            <Card.Img variant="top" src="https://img.sonyunara.com/files/goods/67504/1607328307_0.jpg" style={{ objectFit: "contain" }} />
                            <Card.Body className="px-0">
                                <Card.Title>클로타탄원피스</Card.Title>
                                <Card.Text>구매자 : 30</Card.Text>
                            </Card.Body>
                        </Col>
                        <Col as={Card} style={{ minWidth: "10rem", marginRight: "1rem" }}>
                            <Card.Img variant="top" src="https://img.sonyunara.com/files/goods/67504/1607328307_0.jpg" style={{ objectFit: "contain" }} />
                            <Card.Body className="px-0">
                                <Card.Title>클로타탄원피스</Card.Title>
                                <Card.Text>구매자 : 30</Card.Text>
                            </Card.Body>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </div>
    )
}

export default Product