Chat.js 7.43 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
Soo Hyun Kim committed
10
  const [roomName, setRoomName] = useState('')
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
11
  const [inner, setInner] = useState([''])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
12
  const [chat, setChat] = useState([])   //object로 key는 보낸사람 value는 메세지
JeongYeonwoo's avatar
JeongYeonwoo committed
13
14

  const [img, setImg] = useState([])
15
16
17
18
19
  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
20
21
22
23
24
25
26
27
28
29
30
31
32
  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

  const userId = isAuthenticated()
  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
33

Soo Hyun Kim's avatar
Soo Hyun Kim committed
34
35
36
  async function getRoomName(roomCode) {
    try {
      let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
Soo Hyun Kim's avatar
Soo Hyun Kim committed
37
      console.log(res.data)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
38
39
40
41
42
43
      setRoomName(res.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

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

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

53
    props.setSingleTime(usualTime)
JeongYeonwoo's avatar
JeongYeonwoo committed
54
55
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
56
    props.setSingleChat(inner)
57
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
58
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
59
    setDisabled(true)
60
    // console.log('보내기', chat)
61
  }
Choi Ga Young's avatar
Choi Ga Young committed
62

Choi Ga Young's avatar
Choi Ga Young committed
63
  function handleClick() {
Choi Ga Young's avatar
Choi Ga Young committed
64
    props.setRecievedMsg('')
65
66
67
68
    console.log('chat1', chat)
    setChat(['초기화  '])

    console.log('chat2', chat)
Choi Ga Young's avatar
Choi Ga Young committed
69
    props.handleChatc()
70
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
71
    console.log('나간시간', realTime, usualTime)
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
  }

  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
93
    console.log(respond)
94
95
96
97
98
    const info = respond.data
    let chatlist = []
    let userlist = []
    let timelist = []
    let imglist = []
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
99
    let intlist = []
100
101
    for (let i = 0; i <= info.length - 1; i++) {  //사용하려는 형식에 맞게 수정 
      chatlist = [...chatlist, info[i].message]
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
102
103
104
105
106
107
108
109
110
      //userlist = [...userlist, info[i].username]
      if (info[i].username === "system") {
        userlist = [...userlist, ""]
        intlist.push(i)
        // continue;
      } else {
        userlist = [...userlist, info[i].username]
      }

111
      timelist = [...timelist, info[i].createdAt]
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
112
113
      // console.log('int', intlist)
      // console.log('timelist', timelist)
114
115
116
      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
117
    console.log('userlist확인', userlist)
118
119
120
121
122

    //그 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
123
124
125
126
127
      if (intlist.indexOf(j) < 0) {
        imglist = [...imglist, imginfo[j][0].profileimg]
      } else {
        imglist = [...imglist, ""]
      }
128
129
130
131
132
    }
    setChat(chatlist)
    setSender(userlist)
    setImg(imglist)
    setTime(timelist)
Choi Ga Young's avatar
Choi Ga Young committed
133
134
  }

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
135
136
137
  useEffect(() => {
    getProfile(userId)
  }, [userId])
138

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

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

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

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

162

우지원's avatar
ul    
우지원 committed
163
  return (
JeongYeonwoo's avatar
JeongYeonwoo committed
164
165
    <>
      <Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
166
        <Row className="d-flex justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px", margin: "1%" }}>
167
          <Col md="auto">
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
168
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
169
170
171
          </Col>
          <Col>
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
172
            <Row > {props.roomCode}</Row>
173
174
          </Col>
        </Row>
Choi Ga Young's avatar
x    
Choi Ga Young committed
175

JeongYeonwoo's avatar
JeongYeonwoo committed
176
177
178
        {chat.map((value, index) => {
          if (!(value == '')) {
            if (!(sender[index] === user.nickname)) {
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
179
              return ( //상대편 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
180
181
182
183
184
185
186
187
                <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>
188
                      <Col className='ml-1'>{time[index]}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
189
190
                    </Row>
                  </Col>
191
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
192
              )
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
193
            } else if (sender[index] === "") {
JeongYeonwoo's avatar
JeongYeonwoo committed
194
              return (
Choi Ga Young's avatar
xxxxx    
Choi Ga Young committed
195
196
197
198
                { value }
              )
            } else {
              return ( //내가 보낸 메시지
JeongYeonwoo's avatar
JeongYeonwoo committed
199
200
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
201
                    <Col className='mr-1'>{time[index]}</Col>
JeongYeonwoo's avatar
JeongYeonwoo committed
202
                    <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
203
                  </Row>
204
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
205
206
207
208
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
209
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
210
        })
211
        }
Choi Ga Young's avatar
Choi Ga Young committed
212

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


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
228

우지원's avatar
ul    
우지원 committed
229
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
230