<!-- chat/templates/chat/room.html -->
{% extends 'base.html' %}
{% block title_content %}Chat Room{% endblock title_content %}
{% block body_content %}
    <el-scrollbar ref="scrollbarRef" height="400px" always>
        <div ref="innerRef">
            <p v-for="item in items" :key="item" class="scrollbar-demo-item">
                {$ item $}
            </p>
        </div>
    </el-scrollbar>
    
    <el-input id="chat-message-input" v-model="input" placeholder="Please input" @keyup.enter="send"></el-input>
    <el-button @click="send">Send</el-button>

    {{ room_name|json_script:"room-name" }}
{% endblock body_content %}

{% block script_content %}
<script>
    const roomName = JSON.parse(document.getElementById('room-name').textContent);

    let App = {
        setup() {
            const innerRef = Vue.ref()
            const scrollbarRef = Vue.ref()
            const input = Vue.ref("")
            let chatSocket = null
            const items = Vue.ref([])
            // 状态监测，由于监测不到 items 的变化只能用这种标志位了
            const flag = Vue.ref(false)

            const send = () => {
                if (chatSocket == null) {
                    console.error("chatSocket is null")
                    return
                }
                chatSocket.send(JSON.stringify({
                    'message': input.value
                }))
                input.value = ''
            }

            Vue.watch(flag, (newValue, oldValue) => {
                    setTimeout(() => {
                        // 执行实际逻辑
                        scrollbarRef.value.setScrollTop(innerRef.value.clientHeight)
                    }, 50)
                })

            Vue.onMounted(() => {
                chatSocket = new WebSocket(
                    'ws://'
                    + window.location.host
                    + '/ws/chat/'
                    + roomName
                    + '/'
                );

                chatSocket.onmessage = (e) => {
                    const data = JSON.parse(e.data);
                    items.value.push(data.message)
                    flag.value = !flag.value
                };

                chatSocket.onclose = (e) => {
                    console.error('Chat socket closed unexpectedly');
                };
            })

            return {
                items,
                input,
                send,
                innerRef,
                scrollbarRef,
            }
        }
    }

</script>
{% endblock script_content %}


{% block css_content %}
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.el-slider {
  margin-top: 20px;
}
{% endblock css_content %}
