<template>
  <div class="container">
    <div class="selectName" id="selectNameId">
      <div class="selectInput">
        <h1>欢迎进入聊天室</h1>
        <div style="display: flex; height: 20%">
          <el-input placeholder="请输入昵称进入聊天室" v-model="user" clearable>
          </el-input>
          <!-- &nbsp; -->
          <!-- <el-button type="success" icon="el-icon-check" circle></el-button> -->
        </div>
        <div class="btn_fx">
          <a @click="registerUsername()">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <p>进入聊天室</p>
          </a>
        </div>
      </div>
    </div>
    <div class="left">
      <el-card class="left_top">
        <p>聊天室</p>
        <!-- <p>人数:{{personCount}}</p> -->
        <p>消息:{{ chatCount }}</p>
        <div
          v-for="(item, index) in room_name"
          :key="index"
          class="roomNameClass"
        >
          <div
            v-bind:class="[
              { room_active: index === room_loc },
              room_defaultClass,
            ]"
            @click="changeRoom(item, index)"
          >
            {{ item }}
          </div>
        </div>
        <p>{{ msg }}</p>
      </el-card>

      <el-card class="input_chat1" shadow="always" cellpadding="1px">
        <div class="right_header" style="display: flex; width: 100%">
          <h1 class="roomName">{{ room_select }}</h1>
          <h1
            class="clearFont"
            style="width: 100%; right: 0; text-align: right; cursor: pointer"
            @click="clearChat()"
          >
            清屏
          </h1>
        </div>

        <el-input type="textarea" v-model="send_info"> </el-input>
        <el-button
          type="success"
          round
          style="margin-top: 2%"
          @click="websocketOpen(send_info)"
          >发送</el-button
        >
      </el-card>
    </div>
    <!-- 聊天信息 -->
    <div class="right" id="idChat" style="opacity: 0.8">
      <el-card shadow="hover" style="line-height: 10px">
        <div class="blockChat">
          <div
            v-for="(item, index) in chat_info"
            :key="index"
            class="text item"
          >
            <!-- {{item}} -->
            <template v-if="item.room === room_select">
              <div
                v-for="(item2, index2) in item.content"
                :key="index2"
                class="msgClass"
                v-bind:class="[
                  { info_active: ws_flag === true },
                  info_defaultClass,
                ]"
              >
                <div class="msgUser">
                  <i class="el-icon-user"
                    >{{ item2.user }} &nbsp;{{ item2.create_time }}</i
                  >
                </div>
                <div class="msgMessage">
                  <p>{{ item2.message }}</p>
                </div>
              </div>
            </template>
          </div>
        </div>

        <el-card class="input_chat2" shadow="always" cellpadding="1px">
          <div class="right_header" style="display: flex; width: 100%">
            <h1 class="roomName">{{ room_select }}</h1>
            <h1
              class="clearFont"
              style="width: 100%; right: 0; text-align: right; cursor: pointer"
              @click="clearChat()"
            >
              清屏
            </h1>
          </div>

          <el-input type="textarea" v-model="send_info"> </el-input>
          <el-button
            type="success"
            round
            style="margin-top: 2%"
            @click="websocketOpen(send_info)"
            >发送</el-button
          >
        </el-card>
      </el-card>
    </div>
  </div>
</template>

<script>
import VueMarkdown from 'vue-markdown'
import axios from 'axios'

export default {
    components: {
        VueMarkdown
    },
    name: 'Onlinewebsocket',
    data () {
        return {
            ws_flag: false,
            msg: '连接中',
            send_info: 'hello world!',
            room_name: ['DjangoVue'],
            room_select: '',
            // baseUrl: "http://localhost:8006/webchat/index/",
            baseUrl: 'https://yongma16.xyz/api/',
            // websocketUrl: "/ws_api/",
            websocketUrl: 'wss://yongma16.xyz/ws-api/',
            websocket: null,
            // room 存房间名字，content保存聊天信息的数组
            chat_info: new Array(),
            chat_room: null,
            room_loc: 0,
            user: '',
            cookieValue: document.cookie,
            chatCount: 0,
            personCount: 0,
            sendmsg: '',
            getmsg: '',
            // 房间索引0
            chatRoomIndex: 0
            // msg='连接成功'
        }
    },
    mounted () {
    // 判断是否登录
        this.judeIsLogin()
    },
    methods: {
        judeIsLogin () {
            try {
                console.log(
                    'domMain',
                    document.getElementById('mainappid'),
                    document.getElementById('mainappid').style
                )
                document.getElementById('mainappid').style.padding = '0'
                document.getElementById('mainappid').style.margin = '0'
            } catch (e) {
                console.log('e', e)
            }
        },
        registerUsername () {
            let selectNameDom = document.getElementById('selectNameId')
            console.log(selectNameDom)
            selectNameDom.style.display = 'none'
            //
            this.initWebsocket()
            this.getRoom(this.room_loc)
            this.initRoom()
            // this.cookiePrint(); //打印cookie
        },
        clearChat () {
            // 清空消息
            this.chatCount = 0
            this.chat_info = new Array()
            this.websocket.chat_info[this.chatRoomIndex].content = []
        },
        cookiePrint () {
            let that = this
            console.log('cookie')
            let strcookie = document.cookie // 获取cookie字符串
            let arrcookie = strcookie.split(';') // 分割
            let length = arrcookie.length
            // 遍历匹配
            for (let i = 0; i < length; i++) {
                let arr = arrcookie[i].split('=')
                let arrname = arr[0].replace(' ', '')
                // 划分为两个
                if (arrname === 'user') {
                    that.user = arr[1]
                }
                console.log(arrname === 'user', arrname + '：' + arr[1])
            }
        },
        info_defaultClass: function () {
            console.log('发送消息的css')
        },
        room_defaultClass: function () {
            console.log('选中房间的css')
        },
        getRoom: function (room_loc) {
            // 更新index
            this.room_loc = room_loc
            console.log('获取房间')
            axios
                .get(this.baseUrl + 'webchat/index/')
                .then((res) => {
                    console.log('返回', res)
                })
                .catch((error) => {
                    console.log('error', error)
                })
        },
        initRoom: function () {
            // 用户信息
            // 日期格式化
            Date.prototype.Format = function (fmt) {
                var o = {
                    'M+': this.getMonth() + 1, // 月份
                    'd+': this.getDate(), // 日
                    'H+': this.getHours(), // 小时
                    'm+': this.getMinutes(), // 分
                    's+': this.getSeconds(), // 秒
                    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
                    S: this.getMilliseconds() // 毫秒
                }
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(
                        RegExp.$1,
                        (this.getFullYear() + '').substr(4 - RegExp.$1.length)
                    )
                }
                for (var k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) {
                        fmt = fmt.replace(
                            RegExp.$1,
                            RegExp.$1.length === 1
                                ? o[k]
                                : ('00' + o[k]).substr(('' + o[k]).length)
                        )
                    }
                }
                return fmt
            }

            this.room_select = this.room_name[0]
        },
        changeRoom: function (roomName, roomLoc) {
            this.room_loc = roomLoc
            this.room_select = roomName
            // 新建连接
            // this.initWebsocket(roomName)
            console.log('选择房间', roomName)
            // console.log(that)
        },
        initWebsocket: function (roomName) {
            try {
                if (this.websocket) {
                    this.websocket.close()
                }
            } catch (e) {
                console.log('关闭失败！', e)
            }
            // 触发+1
            this.personCount++

            // 默认第一个房间
            let room = roomName !== undefined ? roomName : this.room_name[0]
            // 判断房间是否存在，不存在则创建房间
            let chatRoomIndex = 0
            try {
                // 判断房间是否存在
                let roomFlag = false
                this.chat_info.map((item, index) => {
                    if (item.room === roomName) {
                        // 房间存在
                        console.log('房间存在', roomName)
                        roomFlag = true
                        chatRoomIndex = index
                    }
                })
                if (!roomFlag) {
                    // 房间不存在，创建

                    let roomObject = {
                        room: room,
                        content: []
                    }
                    this.chat_info.push(roomObject)
                    console.log('创建房间', this.chat_info)
                }
            } catch (e) {
                console.log('创建房间出错', e)
            }
            this.chatRoomIndex = chatRoomIndex
            const wsUrl = this.websocketUrl
            this.websocket = new WebSocket(wsUrl + room + '/') // 连接
            console.log(this.websocket, '聊天室')
            this.websocket.onmessage = this.websocketMessage // 函数指向
            this.websocket.onopen = this.websocketOpen
            this.websocket.onerror = this.websocketError
            this.websocket.onclose = this.websocketClose
            // 保存数据 临时容器  房间号
            this.websocket.chat_info = JSON.parse(JSON.stringify(this.chat_info))
            this.websocket.chatRoomIndex = chatRoomIndex
            console.log('实例websocket', this.websocket)
        },
        websocketMessage: function (e) {
            console.log('聊天信息', JSON.parse(JSON.stringify(e.data)))
            let res = JSON.parse(e.data)
            if (res.message.info.isTrusted) {
                console.log('accsee right!')
                // 人数记录,只会后加入的
            }
            let flag = true
            if (flag) {
                //  房间计数
                this.personCount = res.message.person_count
                    ? res.message.person_count
                    : 0
                let getUser = res.message.user
                let getinfo = res.message.info.isTrusted
                    ? `欢迎${getUser}加入聊天室`
                    : res.message.info
                this.getmsg = getinfo
                this.msg = this.sendmsg === this.getmsg ? '连接聊天室成功' : ''
                let getTime = res.message.create_time
                let message = {
                    user: getUser,
                    message: getinfo,
                    create_time: getTime
                }
                // 添加信息

                this.websocket.chat_info[this.websocket.chatRoomIndex].content.push(
                    message
                )
                // 交换数据
                this.chat_info = this.websocket.chat_info
                this.chatCount++
                console.log('信息', this.chat_info)
                setTimeout((o) => {
                    try {
                        let dom = document.getElementById('idChat')
                        console.log('滚动前', dom.scrollTop, dom.scrollHeight)
                        dom.scrollTop = parseInt(dom.scrollHeight)
                        console.log('滚动后', dom.scrollTop, dom.scrollHeight)
                        dom.scrollTop = dom.scrollHeight
                        // document.getElementById('idChat').scrollTop+=20
                    } catch (e) {
                        console.log(e)
                    }
                }, 100)
            }
        },
        websocketOpen: function (info) {
            this.websocketSend(info)
            // this.send_info=''//清空
        },
        websocketSend: function (data) {
            this.sendmsg = data
            // 名字，消息，时间
            let sendData = {
                person_count: this.personCount,
                user: this.user,
                info: data,
                create_time: new Date().Format('yyyy-MM-dd HH:mm:ss')
            }
            // this.msg='消息发送中'
            console.log('消息发送中')
            let info = JSON.stringify({
                message: sendData
            })
            try {
                this.websocket.send(info)
                // this.msg=''
            } catch (e) {
                console.log('消息发送失败', e)
                this.msg = '连接失败'
            }
        },
        websocketError: function () {
            this.msg = '连接失败'
            let selectNameDom = document.getElementById('selectNameId')
            console.log(selectNameDom)
            selectNameDom.style.display = 'block'
            window.alert('websocket连接失败！')
            // this.initWebsocket()// 重连
        },
        websocketClose: function (e) {
            // 人数减一
            this.personCount = this.personCount > 0 ? this.personCount-- : 0
            this.msg = '离开'
            console.log('离开', e)
            let selectNameDom = document.getElementById('selectNameId')
            console.log(selectNameDom)
            selectNameDom.style.display = 'block'
            // 触发减一
        }
    },
    destroyed () {
        this.websocketClose() // 关闭
    }
}
</script>

<style scoped>
.selectName {
  width: 100%;
  height: 100%;
  position: absolute;
  overflow: hidden;
  /* display: fixed; */
  top: 50%;
  left: 50%;
  z-index: 3;
  /* border-radius: 10px; */
  transform: translate(-50%, -50%);
  background: #005aa7;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #fffde4, #005aa7);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #fffde4, #005aa7);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
  background-size: 400%;
  animation: sendInfo 20s linear infinite;
  opacity: 0.9;
}

.selectInput {
  position: relative;
  width: 50%;
  height: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.selectInput h1 {
  font-size: 3em;
  color: #fb7248;
}

.btn_fx {
  position: relative;
  padding: 20px;
  /* margin:20px; */
}

.blockChat {
  position: relative;
  width: 100%;
  display: block;
}

.blockChat h1 {
  color: rgb(135, 187, 222);
  font-size: 20px;
  font-weight: bold;
}

.msgClass {
  position: relative;
  width: 100%;
  text-align: left;
  margin-bottom: 30px;
  padding-bottom: 30px;
  /* background: rgba(135, 187, 222,.6); */
  background: #4ca1af;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to left, #c4e0e5, #4ca1af);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to left, #c4e0e5, #4ca1af);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

  background-size: 400%;
  animation: sendInfo 20s linear infinite;
  /* -webkit-background-clip: text;
  -webkit-text-fill-color: transparent; */
}

.msgUser {
  position: relative;
  margin: 5px;
  padding: 5px;
  top: 50%;
  width: 100%;
  height: 30px;
  color: rgb(0, 0, 0);
  /* background: rgb(135, 187, 222); */
}

.msgMessage {
  position: relative;

  width: 100%;
  height: 50px;
  font-size: 20px;
  color: rgb(0, 0, 0);
  /* background: rgb(135, 187, 222); */
}

.msgMessage p {
  position: relative;
  /* left:50%; */
  margin: 5px;
  padding: 5px;
  top: 50%;
}

.left_top {
  position: relative;
  cursor: pointer;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.left_top p {
  font-size: 20px;
  margin-bottom: 5px;
  padding-bottom: 5px;
}

.roomNameClass {
  position: relative;
  cursor: pointer;
}

.room_active {
  appearance: none;
  position: relative;
  text-align: left;
  width: 100%;
  height: 100%;
  font-weight: bold;
  color: rgb(135, 187, 222);
  text-shadow: 0 5px 20px #fff;
  background: transparent;
  cursor: pointer;
  line-height: 20px;
  /* padding-top:10px; */
  /* transition: 0.5s; */
}

.room_defaultClass {
  appearance: none;
  position: relative;
  text-align: left;
  width: 100%;
  height: 100%;
  font-weight: bold;
  color: rgb(0, 140, 255);
  background: transparent;
  cursor: pointer;
  line-height: 20px;
  /* padding-top:10px; */
  /* transition: 0.5s; */
}

.info_active {
  position: relative;
  width: 100%;
  text-align: left;
  margin-bottom: 30px;
  padding-bottom: 30px;
  background: #5d4157;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #a8caba, #5d4157);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #a8caba, #5d4157);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
  background-size: 400%;
  animation: sendInfo 2s linear infinite;
}

.info_defaultClass {
  position: relative;
  width: 100%;
  text-align: left;
  margin-bottom: 30px;
  padding-bottom: 30px;
  background: rgba(135, 187, 222, 0.6);
  background-image: linear-gradient(to right, #9b63ff, #462188);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

@keyframes sendInfo {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.container {
  position: relative;
  height: 100%;
  width: 100%;
  opacity: 1;
  /* overflow: hidden; */
  /* background-color: aliceblue; */
  align-content: inherit;
  display: flex;
  margin: 0;
  padding: 0;
  background: url(https://w.wallhaven.cc/full/72/wallhaven-72wzq9.png);
  /* background-size: cover; */
  background-repeat: repeat-y;
}

/* 取消滚动并且隐藏 */
.container::-webkit-scrollbar,
.left::-webkit-scrollbar .right::-webkit-scrollbar {
  display: none;
}

.left {
  position: relative;
  width: 30%;
  height: 100%;
  overflow: auto;
  margin: 5px;
  padding: 5px;
}

.right {
  position: relative;
  width: 70%;
  height: 100%;
  overflow: auto;
  margin: 5px;
  padding: 5px;
}

.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}

.input_chat1 {
  /* position: myblog_static; */
  margin-top: 5%;
  text-align: letf;
  line-height: 50px;
  /* background: cadetblue; */
}

.input_chat2 {
  /* position: myblog_static; */
  margin-top: 5%;
  text-align: letf;
  line-height: 50px;
  background: cadetblue;
  display: none;
}

.selectName a {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 80px;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.selectName a p {
  position: absolute;
  text-align: center;
  width: 100%;
  height: 100%;
  line-height: 80px;
  appearance: none;
  font-size: 2em;
  text-transform: uppercase;
  color: #fb7248;
  border: 1px solid #fb7248;
  box-sizing: border-box;
  z-index: 1;
  transition: 0.5s;
  margin: 0;
  padding: 0;
}

.selectName a:hover p {
  color: #fff;
}

.selectName a span {
  position: absolute;
  width: 100%;
  height: 100%;
  background: #fb7248;
  opacity: 0.5;
  z-index: -1;
  transition: 0.5s;
}

.selectName a span:nth-child(1) {
  top: -100%;
  left: -100%;
}

.selectName a span:nth-child(2) {
  bottom: -100%;
  left: -100%;
}

.selectName a span:nth-child(3) {
  top: -100%;
  right: -100%;
}

.selectName a span:nth-child(4) {
  bottom: -100%;
  right: -100%;
}

.selectName a:hover span:nth-child(1) {
  top: 0px;
  left: 0px;
}

.selectName a:hover span:nth-child(2) {
  bottom: 0px;
  left: 0px;
}

.selectName a:hover span:nth-child(3) {
  top: 0px;
  right: 0px;
}

.selectName a:hover span:nth-child(4) {
  bottom: 0px;
  right: 0px;
}

@media screen and (max-width: 450px) {
  .selectName a {
    width: 100px;
    height: 50px;
  }

  .selectName a p {
    position: absolute;
    text-align: center;
    width: 100%;
    height: 100%;
    line-height: 50px;
    font-size: 1em;
  }

  .selectInput h1 {
    font-size: 2em;
    color: #fb7248;
  }

  .container {
    background-color: lightblue;
    display: inline-block;
    box-sizing: border-box;
    background: url(https://w.wallhaven.cc/full/72/wallhaven-72wzq9.png);
    background-repeat: repeat-y;
    /* overflow: hidden; */
  }

  .left {
    /* top:60%; */
    position: relative;
    width: 100%;
    height: auto;
    overflow: auto;
    margin: 5px;
    padding: 5px;
  }

  .right {
    /* top:5%; */
    position: relative;
    width: 100%;
    height: auto;
    overflow: auto;
    margin: 5px;
    padding: 5px;
  }

  .input_chat1 {
    display: none;
  }

  .input_chat2 {
    /* position: myblog_static; */
    margin-top: 5%;
    width: 100%;
    text-align: letf;
    line-height: 50px;
    background: cadetblue;
    display: inline-block;
  }
}
</style>
