ProductRegist.js 10.2 KB
Newer Older
Kim, Subin's avatar
Kim, Subin committed
1
import React, { useState, useEffect, useRef } from 'react';
2
import { Redirect } from 'react-router-dom';
kusang96's avatar
dd    
kusang96 committed
3
import { Row, Col, Button, Form, Container, Alert } from 'react-bootstrap';
Jiwon Yoon's avatar
Jiwon Yoon committed
4
import axios from 'axios'
5
import catchErrors from '../utils/catchErrors';
Jiwon Yoon's avatar
Jiwon Yoon committed
6

7
let color = {}
Jiwon Yoon's avatar
Jiwon Yoon committed
8
9
let preColors = []
let colorHtml = []
10
let list = []
Kim, Subin's avatar
Kim, Subin committed
11
12

function ProductsRegist() {
13
14
15
16
17
18
    const INIT_PRODUCT = {
        pro_name: '',
        price: 0,
        stock: 0,
        main_category: '',
        sub_category: [],
Jiwon Yoon's avatar
Jiwon Yoon committed
19
20
        sizes: [],
        colors: [],
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
        description: '',
        main_image: [],
        detail_image: []
    }
    const categorys = {
        "DRESS": ["LONG DRESS", "SHORT DRESS", "KNIT DRESS", "SHIRT DRESS", "PATTERN DRESS", "BUSTIER DRESS", "TWO-PIECE DRESS"],
        "OUTER": ["PADDED JACKET", "JACKET", "JUMPER", "COAT", "FLEECE", "CARDIGAN / VEST"],
        "TOP": ["KNIT", "HOODY", "BLOUSE", "SHIRT", "SWEATSHIRT", "LONG SLEEVE SHIRT", "SHORT SLEEVE / SLEEVELESS SHIRT"],
        "PANTS": ["JEANS", "SKINNY JEANS", "BANDING PANTS", "WIDE-FIT PANTS", "BOOT-CUT PANTS", "STRAIGHT-FIT PANTS", "SHORTS", "TROUSERS", "LEGGINGS", "JUMPSUIT / OVERALLS"],
        "SKIRT": ["LONG SKIRT", "MIDI SKIRT", "MINI SKIRT"],
        "TRAINING": [],
        "SHOES": ["SNEAKERS / SLIP-ON", "FLAT / LOAFER", "HEEL / PUMP", "BOOTS", "SANDAL / SLIPPER"]
    }
    const [product, setProduct] = useState(INIT_PRODUCT)
    const [categoryNum, setCategoryNum] = useState(0)
    const [tag, setTag] = useState(0)
kusang96's avatar
dd    
kusang96 committed
37
    const [error, setError] = useState('')
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    const [success, setSuccess] = useState(false)
    const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })

    const mainCategorys = Object.keys(categorys)
    const subCategorys = Object.values(categorys)

    function addCategory() {
        console.log(product)
        list.push(
            <div>
                <span i={tag}>{product["main_category"]} / {product["sub_category"][tag]}</span>
                <input type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteCategory} />
            </div>)
        setTag(tag + 1)
    }
    function deleteCategory(e) {
        const categ = e.target.parentNode
        categ.remove()
        product["sub_category"].splice(e.target.parentNode.firstElementChild.getAttribute("i"), 1)
        console.log(product)
    }
    function handleCheckBox(e) {
        setChecked({ ...checked, [e.target.value]: !checked[`${e.target.value}`] })
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
62

63
    function addColor() {
Jiwon Yoon's avatar
Jiwon Yoon committed
64
65
66
        preColors.push(color["colors"])
        colorHtml.push(
            <p>{color["colors"]}</p>
67
        )
Jiwon Yoon's avatar
Jiwon Yoon committed
68
69
        setProduct({...product, "colors":preColors})
    }
70

Jiwon Yoon's avatar
Jiwon Yoon committed
71
72
    function colorChange(e){
        color[e.target.name]= e.target.value
73
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
74
75

    function handleChange(event) {
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
76
        const { name, value, files } = event.target
77
78
        if (event.target.name === "sub_category") {
            product["sub_category"].push(event.target.value)
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
79
        } else if (files) {
kusang96's avatar
dd    
kusang96 committed
80
            setProduct({ ...product, [name]: files })
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
81

kusang96's avatar
dd    
kusang96 committed
82
83
84
        } else {
            setProduct({ ...product, [name]: value })
        }
85
86
87
        if (event.target.name === "main_category") {
            setCategoryNum(event.target.selectedIndex - 1)
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
88
89
    }

kusang96's avatar
dd    
kusang96 committed
90
    async function handleSubmit(e) {
Jiwon Yoon's avatar
Jiwon Yoon committed
91
        e.preventDefault()
92
93
94
95
96
97
        const sizes = []
        for (let [key, value] of Object.entries(checked)) {
            if (value === true) {
                sizes.push(key)
            }
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
98
        product["sizes"]=sizes
Jiwon Yoon's avatar
0111    
Jiwon Yoon committed
99
        console.log(product)
kusang96's avatar
kusang96 committed
100
        const formData = new FormData();
kusang96's avatar
dd    
kusang96 committed
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
        for (const key in product) {
            console.log("product[key]=", product[key])
            if (key == "main_image" || key == "detail_image") {
                for (const file of product[key]) {
                    formData.append(key, file)
                }
            } else {
                formData.append(key, product[key])
            }
        }
        // formData 값 확인용
        // for (const key of formData.keys()) {

        //     console.log("key=",key);

        //   }

        //   for (const value of formData.values()) {

        //     console.log(value);

        //   }
        try {
            const response = await axios.post('/api/product/regist', formData)
        } catch (error) {
            catchErrors(error, setError)
kusang96's avatar
kusang96 committed
127
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
128
129
    }

130
131
    if (success) {
        return <Redirect to='/' />
132
    }
Kim, Subin's avatar
Kim, Subin committed
133
134
    return (
        <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
135
136
            <Container>
                <Row className="justify-content-md-center">
137
                    <Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
138
                    {error && <Alert variant="danger" className="text-center">{error}</Alert>}
Jiwon Yoon's avatar
Jiwon Yoon committed
139
                        <h2 className="text-center mt-5 font-weight-bold">상품등록</h2>
Jiwon Yoon's avatar
Jiwon Yoon committed
140
                        <Form className="p-5" onSubmit={handleSubmit}>
Jiwon Yoon's avatar
Jiwon Yoon committed
141
142
                            <Form.Group controlId="productNameform">
                                <Form.Label>상품명</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
143
                                <Form.Control type="text" name="pro_name" placeholder="상품명" onChange={handleChange} />
Jiwon Yoon's avatar
Jiwon Yoon committed
144
145
                            </Form.Group>
                            <Form.Group controlId="productAmountform">
Jiwon Yoon's avatar
Jiwon Yoon committed
146
147
                                <Form.Label>재고</Form.Label>
                                <Form.Control type="text" name="stock" placeholder="숫자만 입력해주세요" onChange={handleChange} />
Jiwon Yoon's avatar
Jiwon Yoon committed
148
149
150
                            </Form.Group>
                            <Form.Group controlId="productPriceform">
                                <Form.Label>가격</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
151
                                <Form.Control type="text" name="price" placeholder="숫자만 입력해주세요" onChange={handleChange} />
Jiwon Yoon's avatar
Jiwon Yoon committed
152
153
154
155
                            </Form.Group>
                            <Form.Group>
                                <Form.Label>분류</Form.Label>
                                <Row>
156
                                    <Col md={4}>
157
158
159
                                        <Form.Control as="select" name="main_category" onChange={handleChange}>
                                            <option value="" >상위분류</option>
                                            {mainCategorys.map((main) => (
160
                                                <option value={main}>{main}</option>
161
                                            ))}
Jiwon Yoon's avatar
Jiwon Yoon committed
162
163
164
                                        </Form.Control>
                                    </Col>
                                    <Col md={6}>
165
166
167
                                        <Form.Control as="select" name="sub_category" onChange={handleChange}>
                                            <option value="" >하위분류</option>
                                            {subCategorys[categoryNum].map((sub) => (
168
                                                <option value={sub}>{sub}</option>
169
                                            ))}
Jiwon Yoon's avatar
Jiwon Yoon committed
170
171
                                        </Form.Control>
                                    </Col>
172
173
174
                                    <Col >
                                        <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addCategory}>추가</Button>
                                    </Col>
Jiwon Yoon's avatar
Jiwon Yoon committed
175
                                </Row>
176
                                {list.map((element) => element)}
Jiwon Yoon's avatar
Jiwon Yoon committed
177
                            </Form.Group>
178
179
                            <Form.Group>
                                <Form.Label>사이즈</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
180
181
182
183
184
185
                                <Form.Check type="checkbox" name="sizes" label="Free" value="Free" onChange={handleCheckBox} />
                                <Form.Check type="checkbox" name="sizes" label="XL" value="XL" onChange={handleCheckBox} />
                                <Form.Check type="checkbox" name="sizes" label="L" value="L" onChange={handleCheckBox} />
                                <Form.Check type="checkbox" name="sizes" label="M" value="M" onChange={handleCheckBox} />
                                <Form.Check type="checkbox" name="sizes" label="S" value="S" onChange={handleCheckBox} />
                                <Form.Check type="checkbox" name="sizes" label="XS" value="XS" onChange={handleCheckBox} />
186
187
188
189
190
                            </Form.Group>
                            <Form.Group>
                                <Form.Label>색상</Form.Label>
                                <Row>
                                    <Col md={10}>
Jiwon Yoon's avatar
Jiwon Yoon committed
191
                                        <Form.Control as="textarea" rows={1} name="colors" placeholder="색상" onChange={colorChange} />
192
193
194
195

                                    </Col>
                                    <Col>

Jiwon Yoon's avatar
Jiwon Yoon committed
196
                                        <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
197
                                    </Col>
Jiwon Yoon's avatar
Jiwon Yoon committed
198
                                </Row>
Jiwon Yoon's avatar
Jiwon Yoon committed
199
                                {colorHtml.map((element) => element)}
Jiwon Yoon's avatar
Jiwon Yoon committed
200
                            </Form.Group>
201

Jiwon Yoon's avatar
Jiwon Yoon committed
202
203
                            <Form.Group controlId="productDescriptionform">
                                <Form.Label>상품설명</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
204
                                <Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} />
Jiwon Yoon's avatar
Jiwon Yoon committed
205
206
207
                            </Form.Group>
                            <Form.Group>
                                <Form.Label>대표이미지</Form.Label>
Jiwon Yoon's avatar
Jiwon Yoon committed
208
209
210
211
212
                                <Form.File id="productImageform" name="main_image" onChange={handleChange} />
                            </Form.Group>
                            <Form.Group>
                                <Form.Label>상세이미지</Form.Label>
                                <Form.File id="productImageform" name="detail_image" onChange={handleChange} />
Jiwon Yoon's avatar
Jiwon Yoon committed
213
                            </Form.Group>
214
                            <Button className="float-right" type="submit" style={{ background: '#91877F', borderColor: '#91877F' }}>등록</Button>
Jiwon Yoon's avatar
Jiwon Yoon committed
215
216
217
218
                        </Form>
                    </Col>
                </Row>
            </Container>
Kim, Subin's avatar
Kim, Subin committed
219
220
221
222
223
        </div>
    )
}

export default ProductsRegist