Chat.js 7.44 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

JeongYeonwoo's avatar
JeongYeonwoo committed
7
8
9
10
11
12
13

const INIT_CHAT = {
  msg: '',
  sender: '',
  img: '',
  time: ''
}
14

우지원's avatar
ul    
우지원 committed
15
function Chat(props) {
JeongYeonwoo's avatar
JeongYeonwoo committed
16
17
  const [sender, setSender] = useState([])

Choi Ga Young's avatar
Choi Ga Young committed
18
  //const [roomName, setRoomName] = useState('')
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
19
  const [inner, setInner] = useState([''])
JeongYeonwoo's avatar
JeongYeonwoo committed
20
  const [chat, setChat] = useState([INIT_CHAT])   //object로 key는 보낸사람 value는 메세지
JeongYeonwoo's avatar
JeongYeonwoo committed
21

22
23
24
25
  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
26
27
28
29
  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

Soo Hyun Kim's avatar
Soo Hyun Kim committed
30
  const [exit, setExit] = useState(false);
Choi Ga Young's avatar
Choi Ga Young committed
31
32

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

Choi Ga Young's avatar
Choi Ga Young committed
34
35
36
37
38
39
40
41
  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
42

43
44
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
45
    setInner(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
46
    setDisabled(false)
47
48
49
  }

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

52
    props.setSingleTime(usualTime)
JeongYeonwoo's avatar
JeongYeonwoo committed
53
54
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
55
    props.setSingleChat(inner)
56
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
57
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
58
    setDisabled(true)
59
  }
Choi Ga Young's avatar
Choi Ga Young committed
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

  async function recordEntryLog() {
    const leaveInfo = { userId: userId, roomCode: props.roomCode, leaveTime: realTime }
    try {
      const check = await axios.get('/room/entrylog', { params: leaveInfo })
      if (check.data) {       //있으면 put으로
        await axios.put('/room/entrylog', leaveInfo)
      } else {        //없으면 post
        await axios.post('/room/entrylog', leaveInfo)
      }
    } catch (error) {
      catchErrors(error, setError)
    }

  }


Choi Ga Young's avatar
Choi Ga Young committed
78
  function handleClick() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
79
    props.closeChatRoom(props.roomCode)
Choi Ga Young's avatar
Choi Ga Young committed
80
    props.setRecievedMsg('')
Choi Ga Young's avatar
Choi Ga Young committed
81
    props.handleChatc()
JeongYeonwoo's avatar
JeongYeonwoo committed
82
83
    setChat([''])

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

    recordEntryLog()

    //아니 0으로 바꿔도 개수 세는걸 업데이트안하니까 소용없음 usestate해서 useEffect에 leaveInfo를 달아줘야할듯@@@@
    //누르면 now를 0으로
    // for (let i = 0; i < props.closedlist.length; i++) {
    //   props.leaveInfo[i].now = 0  //그냥 싹다 0으로 해도되잖아?
    //   if (props.leaveInfo[i].roomCode === props.roomCode) {
    //     // setLeftInfo(leftInfo[i].now='보는중')
    //     props.leaveInfo[i].now = 0   // 방 나가면 안 보는중으로 하기 위해 0으로 바꾸기!!!!!@@@@@@@@@@
    //     //usestate로 해보기@@@@@@
    //     console.log(i, '아아아아아아아아')
    //   } else {
    //     props.leaveInfo[i].now = 0
    //   }
    // }


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
  }

  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 } })
    const info = respond.data
JeongYeonwoo's avatar
JeongYeonwoo committed
123
124
125
126
127

    let intochat = []
    for (let prop in info) {
      let hour = info[prop].createdAt.split('T')[1].split(':')
      hour = settingtime(hour[0]) + ':' + hour[1]
128
      intochat.push({ msg: info[prop].message, sender: info[prop].username, img: info[prop].profileimg, time: hour })
129
    }
JeongYeonwoo's avatar
JeongYeonwoo committed
130
    setChat(intochat)
Choi Ga Young's avatar
Choi Ga Young committed
131
132
  }

Choi Ga Young's avatar
Choi Ga Young committed
133
  async function exitAndCloseRoom() {
Soo Hyun Kim's avatar
Soo Hyun Kim committed
134
135
136
137
    props.exitRoom(props.roomCode)
    setExit(false)
    props.handleChatc()
  }
Choi Ga Young's avatar
Choi Ga Young committed
138

Soo Hyun Kim's avatar
Soo Hyun Kim committed
139

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
140
141
142
  useEffect(() => {
    getProfile(userId)
  }, [userId])
143

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
144
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
145
    setChat([...chat, { msg: props.singleChat, sender: props.singleUser, img: props.singleImg, time: props.singleTime }])
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
146
  }, [props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
147

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

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


우지원'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}
JeongYeonwoo's avatar
JeongYeonwoo committed
178
        {chat.map((value, index) => {
179
          if (!(value.msg === '')) {
JeongYeonwoo's avatar
JeongYeonwoo committed
180
            if (!(value.sender === user.nickname)) {
JeongYeonwoo's avatar
JeongYeonwoo committed
181
182
183
              return (
                <Row key={index} className='m-1' >
                  <Col xs={2}>
JeongYeonwoo's avatar
JeongYeonwoo committed
184
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "50px", height: "50px" }} roundedCircle />
JeongYeonwoo's avatar
JeongYeonwoo committed
185
186
                  </Col>
                  <Col xs={8}>
JeongYeonwoo's avatar
JeongYeonwoo committed
187
                    <Row><strong>{value.sender}</strong></Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
188
                    <Row className='d-flex flex-wrap-nowrap'>
JeongYeonwoo's avatar
JeongYeonwoo committed
189
190
                      <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.msg}</Row>
                      <Col className='ml-1'>{value.time}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
191
192
                    </Row>
                  </Col>
193
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
194
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
195
            } else if (sender[index] === "") {
JeongYeonwoo's avatar
JeongYeonwoo committed
196
              return (
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
197
198
199
200
                { value }
              )
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
201
202
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
JeongYeonwoo's avatar
JeongYeonwoo committed
203
204
                    <Col className='mr-1'>{value.time}</Col>
                    <Row className='mr-2' name='msg' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value.msg}</Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
205
                  </Row>
206
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
207
208
209
210
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
211
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
212
        })
213
        }
Choi Ga Young's avatar
Choi Ga Young committed
214

JeongYeonwoo's avatar
JeongYeonwoo committed
215
      </Container >
216
217
      <Form onSubmit={sendMsgCH} fluid>
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
218
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
219
220
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
JeongYeonwoo's avatar
JeongYeonwoo committed
221
          </Button>
우지원's avatar
ul    
우지원 committed
222
        </Form.Group>
223
      </Form>
JeongYeonwoo's avatar
JeongYeonwoo committed
224
    </>
우지원's avatar
ul    
우지원 committed
225
226
227
228
229


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
230

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