admin.tsx 8.24 KB
Newer Older
백승민's avatar
백승민 committed
1
import React, { FormEvent, useEffect, useState, MouseEvent } from "react";
백승민's avatar
백승민 committed
2
import { Link } from "react-router-dom";
백승민's avatar
백승민 committed
3
4
import { mainimgApi } from "../apis";
import { MainimgType } from "../types";
백승민's avatar
백승민 committed
5
6
import { picture } from "../apis/profile.api";
import { catchErrors } from "../helpers";
백승민's avatar
백승민 committed
7
import { MySlide } from "./adminslide";
백승민's avatar
백승민 committed
8

백승민's avatar
백승민 committed
9
10
11
12
// export interface ImgState {
//     state: MainimgType;
// }

백승민's avatar
백승민 committed
13

백승민's avatar
백승민 committed
14
export default function Admin() {
백승민's avatar
백승민 committed
15
    // 이미지 전체 불러오기
백승민's avatar
백승민 committed
16
    const [getimgs, setGetimgs] = useState<MainimgType[]>([]);
백승민's avatar
백승민 committed
17

백승민's avatar
백승민 committed
18
19
20
21
22
23
24
    async function imgsData() {
        const imgs = await mainimgApi.getmainimg();
        setGetimgs(imgs)
    };
    useEffect(() => {
        imgsData();
    }, []);
백승민's avatar
백승민 committed
25
    
백승민's avatar
백승민 committed
26
    // 이미지 추가하기
백승민's avatar
백승민 committed
27
    const [addimg, setAddimg] = useState<MainimgType>({
백승민's avatar
백승민 committed
28
        _id: "",
백승민's avatar
백승민 committed
29
30
31
        theme: "",
        city: "",
        title: "",
백승민's avatar
백승민 committed
32
        pic: { originalfilename: "", newfilename: "" },
백승민's avatar
백승민 committed
33
34
35
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
백승민's avatar
백승민 committed
36
37
    const [addSuccess, setAddSuccess] = useState(false);
    const [delSuccess, setDelSuccess] = useState(false);
백승민's avatar
백승민 committed
38
    const [file, setFile] = useState<File>();
백승민's avatar
백승민 committed
39
40
41

    function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) {
        const { name, value } = event.currentTarget;
백승민's avatar
백승민 committed
42
        console.log(value)
백승민's avatar
백승민 committed
43
44
45
46
47
        setAddimg({ ...addimg, [name]: value });
    }
    function handleInputeChange(event: React.ChangeEvent<HTMLInputElement>) {
        const { name, value } = event.currentTarget;
        setAddimg({ ...addimg, [name]: value });
백승민's avatar
백승민 committed
48
    };
백승민's avatar
백승민 committed
49

백승민's avatar
백승민 committed
50
51
52
53
    function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!(file === undefined)) {
            setFile(file);
백승민's avatar
백승민 committed
54
55
56
        }
    }

백승민's avatar
백승민 committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    async function handleSubmit(event: FormEvent) {
        event.preventDefault();
        const formdata = new FormData();
        console.log(addimg);
        formdata.append("city", addimg.city);
        formdata.append("theme", addimg.theme);
        formdata.append("title", addimg.title);
        if (!(file === undefined)) {
            formdata.append("mainimg", file);
            console.log(formdata);
            const res = await mainimgApi.mainimg(formdata);
            console.log("확인 중 ", res);
            alert("img 추가되었습니다");
        };
    };
    
백승민's avatar
백승민 committed
73
    // 이미지 삭제하기
백승민's avatar
백승민 committed
74
    async function handleDeleteClick(event: MouseEvent<HTMLButtonElement>) {
백승민's avatar
백승민 committed
75
76
77
78
79
80
        try {
            if (confirm("삭제하시겠습니까?") == true) {
                const picId = event.currentTarget.id;
                console.log("picId : ", picId)
                const res = await mainimgApi.delmainimg(picId);
                console.log("delete img", res);
백승민's avatar
백승민 committed
81
                // setGetimgs(getimgs)
백승민's avatar
백승민 committed
82
83
                setDelSuccess(true);
                setError("");
백승민's avatar
백승민 committed
84
                alert("img 삭제되었습니다");
백승민's avatar
백승민 committed
85
86
87
88
89
90
91
92
93
94
            } else {
                return false;
            }
        }
        catch (error) {
            console.log("에러발생");
            catchErrors(error, setError);
        } finally {
            setLoading(false);
        };
백승민's avatar
백승민 committed
95
    };
백승민's avatar
백승민 committed
96
  
백승민's avatar
백승민 committed
97
98
99
    let limit = 15;
    const numPages = Math.ceil(getimgs.length / 15);

백승민's avatar
백승민 committed
100
101
102
    // const location = useLocation() as ImgState;
    // const img = location.state;

백승민's avatar
백승민 committed
103
104
105
    const slides = []
    for (let i = 0; i < numPages; i++) {
        const k = [
백승민's avatar
백승민 committed
106
            getimgs.slice(i * limit, i * limit + limit).map((picture, index: number) => (
백승민's avatar
백승민 committed
107
108
109
                <div key={index}>
                    <div className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}>
                        <img
백승민's avatar
백승민 committed
110
                            src={"http://localhost:3000/images/" + picture.pic.newfilename}
백승민's avatar
백승민 committed
111
112
                            className="w-full h-10 md:h-20 object-center"
                        />
백승민's avatar
백승민 committed
113
                        <p className="text-center text-xs">{picture.title}</p>
백승민's avatar
백승민 committed
114
                    </div>
백승민's avatar
백승민 committed
115
116
                    <div className="text-end">
                        <button className="border-r-2 border-r-indigo-500 text-xs">
백승민's avatar
백승민 committed
117
                            <Link to={`/admin/${picture._id}`} state={picture}>
백승민's avatar
백승민 committed
118
119
120
                                수정
                            </Link>
                        </button>
백승민's avatar
백승민 committed
121
                        <button id={picture._id} onClick={handleDeleteClick} className="text-xs">
백승민's avatar
백승민 committed
122
123
124
                            삭제
                        </button>
                    </div>
백승민's avatar
백승민 committed
125
126
127
128
129
                </div>
            ))]
        slides.push(k);
    }

백승민's avatar
백승민 committed
130
131
    return (
        <div>
백승민's avatar
백승민 committed
132
            <form onSubmit={handleSubmit}>
백승민's avatar
백승민 committed
133
134
135
136
137
138
139
140
141
142
                <div className="flex flex-wrap justify-center gap-3">
                    <div className="gap-3 md:flex ">
                        <select
                            name="city"
                            id="Questions"
                            className="border border-3 border-black w-20 my-5"
                            defaultValue="질문종류"
                            onChange={handleSelectChange}
                        >
                            <option value="질문종류">도시</option>
백승민's avatar
백승민 committed
143
144
145
146
147
148
149
150
151
152
                            <option value="서울">서울</option>
                            <option value="부산">부산</option>
                            <option value="인천">인천</option>
                            <option value="대구">대구</option>
                            <option value="광주">광주</option>
                            <option value="대전">대전</option>
                            <option value="울산">울산</option>
                            <option value="세종">세종</option>
                            <option value="독도">독도</option>
                            <option value="제주">제주</option>
백승민's avatar
백승민 committed
153
154
155
156
157
158
159
160
161
                        </select>
                        <select
                            name="theme"
                            id="Questions"
                            className="border border-3 border-black w-20 my-5"
                            defaultValue="질문종류"
                            onChange={handleSelectChange}
                        >
                            <option value="질문종류">테마</option>
백승민's avatar
백승민 committed
162
163
164
165
166
167
168
169
170
171
172
173
                            <option value="사이클링">사이클링</option>
                            <option value="서핑">서핑</option>
                            <option value="액티비티">액티비티</option>
                            <option value="캠핑">캠핑</option>
                            <option value="스키">스키</option>
                            <option value="보트">보트</option>
                            <option value="사막">사막</option>
                            <option value="골프">골프</option>
                            <option value="동굴">동굴</option>
                            <option value="문화재">문화재</option>
                            <option value="동물원">동물원</option>
                            <option value="사이클링">사이클링</option>
백승민's avatar
백승민 committed
174
175
                        </select>
                        <div className="flex items-center justify-end gap-3">
백승민's avatar
백승민 committed
176
177
178
179
180
181
182
183
184
185
                            <input
                                type="file"
                                id="files"
                                className="hidden"
                                onChange={handleFileChange}
                            ></input>
                            <label htmlFor="files" className="border-2 m-5">
                                이미지 선택
                            </label>

백승민's avatar
백승민 committed
186
187
188
189
190
191
                        </div>
                        <div className="flex items-center justify-end gap-3 mt-2 md:mt-0">
                            <p>title :</p>
                            <input name="title" className="border-2 border-sky-500"
                                onChange={handleInputeChange} />
                        </div>
백승민's avatar
백승민 committed
192
                    </div>
백승민's avatar
백승민 committed
193
194
                    <div className="my-5 flex items-center">
                        <button className="border-2 border-gray-500 rounded ">추가</button>
백승민's avatar
백승민 committed
195
196
197
                    </div>
                </div>
            </form>
백승민's avatar
백승민 committed
198
            <div className="flex justify-center">
백승민's avatar
백승민 committed
199
200
201
                <MySlide key={Math.random()}
                    slides={slides}
                />
백승민's avatar
백승민 committed
202

백승민's avatar
백승민 committed
203
            </div>
백승민's avatar
백승민 committed
204
205
206
        </div>
    );
};