Chat.js 7.74 KB
Newer Older
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
1
import axios from 'axios';
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
2
import React, { useState, useEffect } from 'react';
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
3
4
5
import { Form, Button, Row, Image, Col, Container } from 'react-bootstrap';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
우지원's avatar
ul    
우지원 committed
6
7

function Chat(props) {
JeongYeonwoo's avatar
JeongYeonwoo committed
8
9
  const [sender, setSender] = useState([])

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
10
  const [inner, setInner] = useState([''])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
11
  const [chat, setChat] = useState([])   //object로 key는 보낸사람 value는 메세지
JeongYeonwoo's avatar
JeongYeonwoo committed
12
13

  const [img, setImg] = useState([])
14
15
16
17
18
  const [time, setTime] = useState([''])
  const simpleTime = new Date().toLocaleTimeString()
  const usualTime = simpleTime.substring(0, simpleTime.length - 3)
  const realTime = new Date().toISOString()

Choi Ga Young's avatar
Choi Ga Young committed
19
20
21
22
  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

Soo Hyun Kim's avatar
Soo Hyun Kim committed
23
  const [exit, setExit] = useState(false);
Choi Ga Young's avatar
Choi Ga Young committed
24
25

  const userId = isAuthenticated()
Soo Hyun Kim's avatar
Soo Hyun Kim committed
26

Choi Ga Young's avatar
Choi Ga Young committed
27
28
29
30
31
32
33
34
  async function getProfile(userId) {
    try {
      const response = await axios.get(`/users/${userId}`)
      setUser(response.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
35

36
37
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
38
    setInner(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
39
    setDisabled(false)
40
41
42
  }

  function sendMsgCH(e) {
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
43
    e.preventDefault()
JeongYeonwoo's avatar
JeongYeonwoo committed
44

45
    props.setSingleTime(usualTime)
JeongYeonwoo's avatar
JeongYeonwoo committed
46
47
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
48
    props.setSingleChat(inner)
49
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
50
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
51
    setDisabled(true)
52
    // console.log('보내기', chat)
53
  }
Choi Ga Young's avatar
Choi Ga Young committed
54

Choi Ga Young's avatar
Choi Ga Young committed
55
  function handleClick() {
56
    setChat([''])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
57
    props.closeChatRoom(props.roomCode)
Choi Ga Young's avatar
Choi Ga Young committed
58
    props.setRecievedMsg('')
Choi Ga Young's avatar
Choi Ga Young committed
59
    props.handleChatc()
60
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
61
    console.log('나간시간', realTime, usualTime)
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  }

  function settingtime(hour) {
    let newhour = parseInt(hour) + 9
    if (newhour >= 24) {
      newhour -= 24
    }
    if (newhour >= 13) {
      newhour -= 12
      newhour = '오후 ' + newhour
    } else {
      newhour = '오전 ' + newhour
    }
    return newhour
  }

  //이전 채팅 내용에 대한 것 불러오기
  //프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
  async function getPreviousChat() {
    //메세지, 닉네임, 시간 불러오기
    const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
83
    console.log(respond)
84
85
86
87
88
    const info = respond.data
    let chatlist = []
    let userlist = []
    let timelist = []
    let imglist = []
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
89
    let intlist = []
90
91
    for (let i = 0; i <= info.length - 1; i++) {  //사용하려는 형식에 맞게 수정 
      chatlist = [...chatlist, info[i].message]
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
92
93
94
95
96
97
98
99
100
      //userlist = [...userlist, info[i].username]
      if (info[i].username === "system") {
        userlist = [...userlist, ""]
        intlist.push(i)
        // continue;
      } else {
        userlist = [...userlist, info[i].username]
      }

101
      timelist = [...timelist, info[i].createdAt]
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
102
103
      // console.log('int', intlist)
      // console.log('timelist', timelist)
104
105
106
      let hour = timelist[i].split('T')[1].split(':')
      timelist[i] = settingtime(hour[0]) + ':' + hour[1]
    }
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
107
    console.log('userlist확인', userlist)
108
109
110
111
112

    //그 nick에 맞는 프사 불러오기
    const respond2 = await axios.get('/room/getProfileImage', { params: { 'userlist': userlist } })
    const imginfo = respond2.data
    for (let j = 0; j <= imginfo.length - 1; j++) {
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
113
114
115
116
117
      if (intlist.indexOf(j) < 0) {
        imglist = [...imglist, imginfo[j][0].profileimg]
      } else {
        imglist = [...imglist, ""]
      }
118
119
120
121
122
    }
    setChat(chatlist)
    setSender(userlist)
    setImg(imglist)
    setTime(timelist)
Choi Ga Young's avatar
Choi Ga Young committed
123
124
  }

Soo Hyun Kim's avatar
Soo Hyun Kim committed
125
126
127
128
129
130
131
  async function exitAndCloseRoom(){
    props.exitRoom(props.roomCode)
    setExit(false)
    props.handleChatc()
  }
  

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
132
133
134
  useEffect(() => {
    getProfile(userId)
  }, [userId])
135

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
136
  useEffect(() => {
137
    setTime([...time, props.singleTime])
JeongYeonwoo's avatar
JeongYeonwoo committed
138
    setImg([...img, props.singleImg])
JeongYeonwoo's avatar
JeongYeonwoo committed
139
    setSender([...sender, props.singleUser])
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
140
    setChat([...chat, props.singleChat])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
141
142
    console.log('chat', chat)
    console.log('sender', sender)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
143
  }, [props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
144

Soo Hyun Kim's avatar
Soo Hyun Kim committed
145
  useEffect(() => {
146
    setTime([...time, props.recievedTime])
JeongYeonwoo's avatar
JeongYeonwoo committed
147
    setImg([...img, props.recievedImg])
JeongYeonwoo's avatar
JeongYeonwoo committed
148
    setSender([...sender, props.recievedUser])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
149
150
151
    setChat([...chat, props.recievedMsg])
  }, [props.recievedMsg])

152
153
154
155
  useEffect(() => {
    getPreviousChat()
  }, [props.roomCode])

Soo Hyun Kim's avatar
Soo Hyun Kim committed
156
157
  useEffect(() => {
    getRoomName(props.roomCode)
158
    console.log('겟 룸네임', chat)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
159
160
  }, [props.roomCode])

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
161
  const time = new Date().toLocaleTimeString()
우지원's avatar
ul    
우지원 committed
162
  return (
JeongYeonwoo's avatar
JeongYeonwoo committed
163
164
    <>
      <Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
165
        <Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
166
          <Col md="auto">
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
167
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
168
169
          </Col>
          <Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
170
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
171
172
            <Row > {props.roomCode} </Row>
          </Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
173
174
          <Col md="auto">
            <Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
175
176
          </Col>
        </Row>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
177
178
179
180
181
182
        {exit ?
          <Row>
            <Col>퇴장하시겠습니까?</Col>
            <Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
          </Row>
          : null}
183
        <p>{props.newUser}님이 입장하셨습니다.</p>
JeongYeonwoo's avatar
JeongYeonwoo committed
184
185
186
        {chat.map((value, index) => {
          if (!(value == '')) {
            if (!(sender[index] === user.nickname)) {
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
187
              return ( //상대편 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
188
189
190
191
192
193
194
195
                <Row key={index} className='m-1' >
                  <Col xs={2}>
                    <Image src={img && `/images/${img[index]}`} style={{ width: "50px", height: "50px" }} roundedCircle />
                  </Col>
                  <Col xs={8}>
                    <Row><strong>{sender[index]}</strong></Row>
                    <Row className='d-flex flex-wrap-nowrap'>
                      <Row className='border border-dark' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'white', borderRadius: '5px', fontSize: 'x-large' }}>{value}</Row>
196
                      <Col className='ml-1'>{time[index]}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
197
198
                    </Row>
                  </Col>
199
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
200
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
201
            } else if (sender[index] === "") {
JeongYeonwoo's avatar
JeongYeonwoo committed
202
              return (
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
203
204
205
206
                { value }
              )
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
207
208
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
209
                    <Col className='mr-1'>{time[index]}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
210
                    <Row className='mr-2' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
211
                  </Row>
212
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
213
214
215
216
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
217
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
218
        })
219
        }
Choi Ga Young's avatar
Choi Ga Young committed
220

JeongYeonwoo's avatar
JeongYeonwoo committed
221
      </Container >
222
223
      <Form onSubmit={sendMsgCH} fluid>
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
Choi Ga Young's avatar
x    
Choi Ga Young committed
224
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%', position: 'fixed' }} />
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
225
226
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
JeongYeonwoo's avatar
JeongYeonwoo committed
227
          </Button>
우지원's avatar
ul    
우지원 committed
228
        </Form.Group>
229
      </Form>
JeongYeonwoo's avatar
JeongYeonwoo committed
230
    </>
우지원's avatar
ul    
우지원 committed
231
232
233
234
235


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
236

우지원's avatar
ul    
우지원 committed
237
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
238