<script setup>
import { user } from '~/store/user';
import { getAvatarUrl } from '~/utils/helper';
console.log("2022/10/19 16:02");
const props = defineProps({
  id: String
})

const ws = new WebSocket("wss://socket.bozedu.net/")
// let userList = ref(undefined)

const msgList = ref([])

ws.addEventListener('message', (e) => {
  if (e.data) {
    try {
      const data = JSON.parse(e.data)
      if (data.type !== 'ping') {
        console.log('ws message :>> ', data);
      }

      if (data.type === 'login') {
        // if (data.client_list) {
        //   userList.value = Object.fromEntries(Object.entries(data.client_list).map(([key, value]) => {
        //     const [id, name] = value.split('|')
        //     return [key, { id, name }]
        //   }))
        // }
      }

      if (data.type === 'say') {
        const [id, name] = data.from_client_name.split('|')
        msgList.value.push({
          id,
          name,
          time: data.time,
          content: data.content
        })
        nextTick(() => {
          chatBox.value.scrollTo({
            top: (chatItemBox.value.getBoundingClientRect()).height,
            left: 0,
            behavior: "smooth"
          })
        })

      }

    } catch (error) {
      console.error(error);
    }
  }

})

ws.addEventListener('error', (err) => {
  console.error('ws error :>> ', err);
})

ws.addEventListener('open', (e) => {
  ws.send(JSON.stringify({
    "type": "login",
    // "client_id": user.user_id,
    "client_name": user.user_id + '|' + user.user_realname,
    "room_id": 'xtbk' + props.id
  }))
})

const msg = ref('')
const chatBox = ref()
const chatItemBox = ref()
function handleSendClick() {
  ws.send(JSON.stringify({
    type: "say",
    to_client_id: 'all',
    to_client_name: '所有人',
    content: msg.value
  }))
  msg.value = ''

}


</script>

<template>
  <div class="w-full h-full flex flex-col bg-white shadow">
    <div class="h-80 overflow-hidden overflow-y-auto flex-auto" ref="chatBox">
      <ul ref="chatItemBox">
        <li v-for="item in msgList" class="flex px-6 py-4">
          <div class="mr-3">
            <el-avatar :src="getAvatarUrl(item.id)"></el-avatar>
          </div>
          <div class="flex flex-col flex-auto">
            <span class="text-sm font-bold">{{item.name}}</span>
            <div class="my-3 rounded-md p-2 bg-hex-F5F5FA min-h-4 box-content"><span v-html="item.content"></span></div>
            <span class="text-xs text-hex-8083A3">{{item.time}}</span>
          </div>
        </li>
      </ul>

    </div>
    <div class="flex flex-none p-3">
      <el-input v-model="msg"></el-input>
      <el-button rounded type="primary" @click="handleSendClick" class="ml-4">发送</el-button>
    </div>
  </div>
</template>
