Chat.js 7.28 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: ''
}
우지원's avatar
ul    
우지원 committed
14
function Chat(props) {
JeongYeonwoo's avatar
JeongYeonwoo committed
15
16
  const [sender, setSender] = useState([])

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

  const [img, setImg] = useState([])
22
23
24
25
26
27
  const [time, setTime] = useState([''])
  const simpleTime = new Date().toLocaleTimeString()
  const usualTime = simpleTime.substring(0, simpleTime.length - 3)
  const realTime = new Date().toISOString()


JeongYeonwoo's avatar
JeongYeonwoo committed
28

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
29
  const [disabled, setDisabled] = useState(true)
Choi Ga Young's avatar
Choi Ga Young committed
30
31
  const [user, setUser] = useState('')
  const [error, setError] = useState('');
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
32

Choi Ga Young's avatar
Choi Ga Young committed
33

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
34
35
36
37
38
39
40
41
42
43
  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
Soo Hyun Kim committed
44
45
46
  async function getRoomName(roomCode) {
    try {
      let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
Soo Hyun Kim's avatar
Soo Hyun Kim committed
47
      console.log(res.data)
Soo Hyun Kim's avatar
Soo Hyun Kim committed
48
49
50
51
52
53
      setRoomName(res.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

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

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

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

69
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
70
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
71
    setDisabled(true)
72
  }
Choi Ga Young's avatar
Choi Ga Young committed
73

Choi Ga Young's avatar
Choi Ga Young committed
74
  function handleClick() {
75
    props.setRecievedMsg('')
JeongYeonwoo's avatar
JeongYeonwoo committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    setChat([''])

    // props.handleChatc()
    // console.log("22222222222222222", props.leaveInfo)

    // let find1 = props.leaveInfo.findIndex((ele) => ele.roomName === props.roomCode)
    // console.log("33333333333333333", find1)

    // let find=0
    // for(let i=0;i<=props.leaveInfo.length-1;i++){
    //   if(props.leaveInfo[i].roomName===props.roomCode){
    //     find = i
    //     break;
    //   }
    //   console.log('찾자',find)
    // }

    // if (props.leaveInfo[find1]) {
    //   props.setLeaveInfo(props.leaveInfo[find1] = { roomName: props.roomCode, leaveTime: realTime })
    //   console.log('트루')
    // } else {
    //   props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
    //   console.log('폴스')
    // }
    // console.log('나간다', props.leaveInfo)
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
  }

  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
124
125
126

    let intochat = []
    let msglist = []
127
    let userlist = []
JeongYeonwoo's avatar
JeongYeonwoo committed
128
    let hourlist = []
129
    let imglist = []
JeongYeonwoo's avatar
JeongYeonwoo committed
130
131
132
133
134
135
    for (let prop in info) {
      let hour = info[prop].createdAt.split('T')[1].split(':')
      hour = settingtime(hour[0]) + ':' + hour[1]
      msglist.push(info[prop].message)
      userlist.push(info[prop].username)
      hourlist.push(hour)
136
137
    }
    const respond2 = await axios.get('/room/getProfileImage', { params: { 'userlist': userlist } })
JeongYeonwoo's avatar
JeongYeonwoo committed
138
139
140
141
    imglist = respond2.data
    console.log('확인해보자', imglist)
    for (let i = 0; i < msglist.length; i++) {
      intochat.push({ msg: msglist[i], sender: userlist[i], img: imglist[i].profileimg, time: hourlist[i] })
142
    }
JeongYeonwoo's avatar
JeongYeonwoo committed
143
    setChat(intochat)
Choi Ga Young's avatar
Choi Ga Young committed
144
145
  }

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
146
147
148
  useEffect(() => {
    getProfile(userId)
  }, [userId])
149

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

JeongYeonwoo's avatar
JeongYeonwoo committed
154
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
155
    setChat([...chat, { msg: props.recievedMsg, sender: props.recievedUser, img: props.recievedImg, time: props.recievedTime }])
JeongYeonwoo's avatar
JeongYeonwoo committed
156
  }, [props.recievedMsg])
Choi Ga Young's avatar
aa    
Choi Ga Young committed
157

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

164

우지원's avatar
ul    
우지원 committed
165
  return (
JeongYeonwoo's avatar
JeongYeonwoo committed
166
167
    <>
      <Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
JeongYeonwoo's avatar
dd    
JeongYeonwoo committed
168
        <Row className="d-flex justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px", margin: "1%" }}>
169
          <Col md="auto">
Choi Ga Young's avatar
dmdk    
Choi Ga Young committed
170
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
171
172
173
          </Col>
          <Col>
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
174
            <Row > {props.roomCode}</Row>
175
176
          </Col>
        </Row>
177
        <p>{props.newUser}님이 입장하셨습니다.</p>
JeongYeonwoo's avatar
JeongYeonwoo committed
178
        {chat.map((value, index) => {
JeongYeonwoo's avatar
JeongYeonwoo committed
179
180
          if (!(value.msg == '')) {
            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
193
194
195
196
197
198
                    </Row>
                  </Col>
                </Row>
              )
            } else {
              return (
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
JeongYeonwoo's avatar
JeongYeonwoo committed
199
200
                    <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
201
                  </Row>
202
                </Row>
JeongYeonwoo's avatar
JeongYeonwoo committed
203
204
205
206
              )
            }
          } else {
            return null
JeongYeonwoo's avatar
JeongYeonwoo committed
207
          }
JeongYeonwoo's avatar
JeongYeonwoo committed
208
        })
Soo Hyun Kim's avatar
Soo Hyun Kim committed
209
        }
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
210

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


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
226

우지원's avatar
ul    
우지원 committed
227
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
228