Chat.js 7.63 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])

Choi Ga Young's avatar
Choi Ga Young committed
156
  //const time = new Date().toLocaleTimeString()
우지원's avatar
ul    
우지원 committed
157
  return (
JeongYeonwoo's avatar
JeongYeonwoo committed
158
159
    <>
      <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
160
        <Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
161
          <Col md="auto">
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
162
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
163
164
          </Col>
          <Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
165
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
166
167
            <Row > {props.roomCode} </Row>
          </Col>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
168
169
          <Col md="auto">
            <Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
170
171
          </Col>
        </Row>
Soo Hyun Kim's avatar
Soo Hyun Kim committed
172
173
174
175
176
177
        {exit ?
          <Row>
            <Col>퇴장하시겠습니까?</Col>
            <Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
          </Row>
          : null}
178
        <p>{props.newUser}님이 입장하셨습니다.</p>
JeongYeonwoo's avatar
JeongYeonwoo committed
179
        {chat.map((value, index) => {
Choi Ga Young's avatar
Choi Ga Young committed
180
          if (!(value === '')) {
JeongYeonwoo's avatar
JeongYeonwoo committed
181
            if (!(sender[index] === user.nickname)) {
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
182
              return ( //상대편 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
183
184
185
186
187
188
189
190
                <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>
191
                      <Col className='ml-1'>{time[index]}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
192
193
                    </Row>
                  </Col>
194
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
195
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
196
            } else if (sender[index] === "") {
JeongYeonwoo's avatar
JeongYeonwoo committed
197
              return (
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
198
199
200
201
                { value }
              )
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
202
203
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
204
                    <Col className='mr-1'>{time[index]}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
205
                    <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
206
                  </Row>
207
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
208
209
210
211
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
212
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
213
        })
214
        }
Choi Ga Young's avatar
Choi Ga Young committed
215

JeongYeonwoo's avatar
JeongYeonwoo committed
216
      </Container >
217
218
      <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
219
          <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
220
221
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
JeongYeonwoo's avatar
JeongYeonwoo committed
222
          </Button>
우지원's avatar
ul    
우지원 committed
223
        </Form.Group>
224
      </Form>
JeongYeonwoo's avatar
JeongYeonwoo committed
225
    </>
우지원's avatar
ul    
우지원 committed
226
227
228
229
230


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
231

우지원's avatar
ul    
우지원 committed
232
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
233