Chat.js 7.14 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
20
21
  const [time, setTime] = useState([''])
  const simpleTime = new Date().toLocaleTimeString()
  const usualTime = simpleTime.substring(0, simpleTime.length - 3)
  const realTime = new Date().toISOString()

const  r = Date.parse(realTime)

JeongYeonwoo's avatar
JeongYeonwoo committed
22

Choi Ga Young's avatar
Choi Ga Young committed
23
24
25
26
27
28
29
30
31
32
33
34
35
  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
36

Soo Hyun Kim's avatar
Soo Hyun Kim committed
37
38
39
  async function getRoomName(roomCode) {
    try {
      let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
Soo Hyun Kim's avatar
Soo Hyun Kim committed
40
      console.log(res.data)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
41
42
43
44
45
      setRoomName(res.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }
Choi Ga Young's avatar
x    
Choi Ga Young committed
46
47
48
49
50
51
52
53
54
  // async function sysMsg(roomCode) {
  //   try {
  //     let res = await axios.get('/room/sysMsg', { params: { 'roomCode': roomCode } })
  //     console.log('sysmsg', res.data)
      
  //   } catch (error) {
  //     catchErrors(error, setError)
  //   }
  // }
Soo Hyun Kim's avatar
Soo Hyun Kim committed
55

56
57
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
58
    setInner(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
59
    setDisabled(false)
60
61
62
  }

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

65
    props.setSingleTime(usualTime)
JeongYeonwoo's avatar
JeongYeonwoo committed
66
67
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
68
    props.setSingleChat(inner)
JeongYeonwoo's avatar
JeongYeonwoo committed
69

70
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
71
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
72
    setDisabled(true)
73
    // console.log('보내기', chat)
74
  }
Choi Ga Young's avatar
Choi Ga Young committed
75

Choi Ga Young's avatar
Choi Ga Young committed
76
  function handleClick() {
Choi Ga Young's avatar
Choi Ga Young committed
77
    props.setRecievedMsg('')
78
79
80
81
    console.log('chat1', chat)
    setChat(['초기화  '])

    console.log('chat2', chat)
Choi Ga Young's avatar
Choi Ga Young committed
82
    props.handleChatc()
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
    console.log('나간시간',realTime, usualTime)
  }

  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
    let chatlist = []
    let userlist = []
    let timelist = []
    let imglist = []
    for (let i = 0; i <= info.length - 1; i++) {  //사용하려는 형식에 맞게 수정 
      chatlist = [...chatlist, info[i].message]
      userlist = [...userlist, info[i].username]
      timelist = [...timelist, info[i].createdAt]
      let hour = timelist[i].split('T')[1].split(':')
      timelist[i] = settingtime(hour[0]) + ':' + hour[1]
    }

    //그 nick에 맞는 프사 불러오기
    const respond2 = await axios.get('/room/getProfileImage', { params: { 'userlist': userlist } })
    const imginfo = respond2.data
    for (let j = 0; j <= imginfo.length - 1; j++) {
      imglist = [...imglist, imginfo[j][0].profileimg]
    }
    setChat(chatlist)
    setSender(userlist)
    setImg(imglist)
    setTime(timelist)
Choi Ga Young's avatar
Choi Ga Young committed
130
131
  }

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
141
    setChat([...chat, props.singleChat])
  }, [props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
142

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

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

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

160

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

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

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


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
222

우지원's avatar
ul    
우지원 committed
223
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
224