<template>
  <!-- 直播中控台 start -->
  <el-row type="flex" justify="center" class="live-console" :gutter="10">

    <!-- 用户列表 start -->
    <el-col class="live-console-col" :span="5">
      <el-tabs class="live-console-tab-left" v-model="tabLeft.activeName" @tab-click="handleClick">
        <el-tab-pane :label="onlineLabel" name="online">
          <el-scrollbar ref="manageLeftRef" style="height: 800px; width: 100%;">
            <el-row style="margin-top: 10px" type="flex" align="middle" v-for="u in onlineUserList">
              <el-col :span="5"><el-avatar :src="u.avatar"></el-avatar></el-col>
              <el-col :span="12" :offset="2">{{ u.nickName }}</el-col>
              <el-col :span="3" >
                <el-switch
                  v-model="u.msgStatus"
                  :active-value="0"
                  :inactive-value="1"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="offlineLabel" name="offline">
          <el-scrollbar ref="manageLeftRef" style="height: 100%; width: 100%;">
            <el-row style="margin-top: 10px" type="flex" align="middle" v-for="u in offlineUserList">
              <el-col :span="5"><el-avatar :src="u.avatar"></el-avatar></el-col>
              <el-col :span="12" :offset="2">{{ u.nickName }}</el-col>
              <el-col :span="3" >
                <el-switch
                  v-model="u.msgStatus"
                  :active-value="0"
                  :inactive-value="1"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="silencedUserLabel" name="silenced">
          <el-scrollbar ref="manageLeftRef" style="height: 100%; width: 100%;">
            <el-row style="margin-top: 10px" type="flex" align="middle" v-for="u in silencedUserList">
              <el-col :span="5"><el-avatar :src="u.avatar"></el-avatar></el-col>
              <el-col :span="12" :offset="2">{{ u.nickName }}</el-col>
              <el-col :span="3" >
                <el-switch
                  v-model="u.msgStatus"
                  :active-value="0"
                  :inactive-value="1"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <!-- 用户列表 end -->

    <!-- 直播/视频 start -->
    <el-col class="live-console-col" :span="10">
      <video controls autoplay :src="this.liveVideo.videoUrl" width="100%"></video>
    </el-col>
    <!-- 直播/视频 end -->

    <!-- 聊天 start -->
    <el-col class="live-console-col" :span="5">
      <el-tabs class="live-console-tab-right" v-model="tabRight.activeName" @tab-click="handleClick">
        <el-tab-pane label="聊天" name="talk">
          <el-scrollbar style="height: 500px; width: 300px;" ref="manageRightRef">
            <el-row v-for="m in msgList">
              <el-row style="margin-top: 10px" type="flex" align="top">
                <el-col :span="3" :offset="1"><el-avatar :src="m.avatar"/></el-col>
                <el-col :span="15">
                  <el-row>
                    <el-col>{{ m.nickName }}</el-col>
                    <el-col>{{ m.msg }}</el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-row>
          </el-scrollbar>

          <!-- 消息输入区域 -->
          <div class="chat-input">
            <el-input
              v-model="newMsg"
              placeholder="请输入消息..."
              @keyup.enter.native="sendMessage"
              clearable
            ></el-input>
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <!-- 聊天 end -->
  </el-row>
  <!-- 直播中控台  end -->
</template>

<script>
import { changeUserStatus, watchUserList } from '@/api/live/liveWatchUser'
import { getLiveVideoByLiveId } from '@/api/live/liveVideo'
import { listLiveMsg } from '@/api/live/liveMsg'
import { LiveWS } from '@/utils/webSocket'

export default {
  name: "LiveConsole",
  data() {
    return {
      tabLeft: {
        activeName: "online",
      },
      tabRight: {
        activeName: "talk",
      },
      liveVideo: {},
      socket: null,
      userParams:{
        pageNum: 1,
        pageSize: 10,
        liveId: null
      },
      msgParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null
      },
      userList: [],
      msgList: [],
      newMsg: ''
    }
  },
  created() {
    this.getLiveVideo()
    this.getList()
    this.connectWebSocket()
  },
  computed: {
    liveId() {
      return this.$route.params.liveId;
    },
    userId() {
      return this.$store.state.user.user.userId
    },
    onlineUserList() {
      return this.userList.filter(u => u.online === 0)
    },
    onlineLabel() {
      if (this.onlineUserList.length > 0) {
        return '在线(' + this.onlineUserList.length + ')'
      }
      return '在线'
    },
    offlineUserList() {
      return this.userList.filter(u => u.online === 1)
    },
    offlineLabel() {
      if (this.offlineUserList.length > 0) {
        return '离线(' + this.offlineUserList.length + ')'
      }
      return '离线'
    },
    silencedUserList() {
      return this.userList.filter(u => u.msgStatus === 1)
    },
    silencedUserLabel() {
      if (this.silencedUserList.length > 0) {
        return '禁言(' + this.silencedUserList.length + ')'
      }
      return '禁言'
    }
  },
  methods: {
    handleClick(tab) {
      console.log("click",tab.name)
      console.log("liveId", this.liveId)
    },
    getLiveVideo() {
      getLiveVideoByLiveId(this.liveId).then(res => {
        this.liveVideo = res.data
      })
    },
    getList() {
      this.resetParams()
      this.loadUserList()
      this.loadMsgList()
    },
    resetParams() {
      this.userList= []
      this.userParams = {
        pageNum: 1,
        pageSize: 10,
        liveId: this.liveId
      }
      this.msgList = []
      this.msgParams = {
        pageNum: 1,
        pageSize: 10,
        liveId: this.liveId
      }
    },
    loadUserList() {
      // 直播间用户
      watchUserList({
        liveId: this.liveId,
        pageNum: this.userParams.pageNum,
        pageSize: this.userParams.pageSize
      }).then(response => {
        let {rows,total} = response;
        this.userParams.pageNum = (this.userParams.pageNum - 1) * this.userParams.pageSize;
        rows.forEach(row => {
          if (!this.userList.some(u => u.userId === row.userId)) {
            this.userList.push(row)
          }
        })

        // 没加载完继续加载
        if (this.userList.length < total) {
          this.loadUserList()
        }
      })
    },
    loadMsgList() {
      // 直播间消息
      listLiveMsg({
        liveId:this.liveId,
        pageNum: this.msgParams.pageNum,
        pageSize: this.msgParams.pageSize
      }).then(response => {
          let {rows,total} = response;
          console.log(rows);
          this.msgParams.pageNum = (this.msgParams.pageNum - 1) * this.msgParams.pageSize;
          rows.forEach(row => {
            if (!this.msgList.some(m => m.msgId === row.msgId)) {
              this.msgList.push(row)

              // 移动到底部
              this.$nextTick(() => {
                setTimeout(() => {
                  this.$refs.manageRightRef.wrap.scrollTop = this.$refs.manageRightRef.wrap.scrollHeight - this.$refs.manageRightRef.wrap.clientHeight
                }, 200)
              })
            }
          })

          // 没加载完继续加载
          if (this.msgList.length < total) {
            this.loadMsgList()
          }
        })

      // 添加滚动监听
      this.$nextTick(() => {
        this.$refs.manageRightRef.wrap.addEventListener("scroll", this.manageRightScroll)
      })
    },
    manageRightScroll() {
      let max = this.$refs.manageRightRef.wrap.scrollHeight - this.$refs.manageRightRef.wrap.clientHeight
      let current = this.$refs.manageRightRef.wrap.scrollTop
      console.log("manageRightMax", max);
      console.log("manageRight", current)
    },
    changeUserState(u) {
      // 还原状态
      u.msgStatus = u.msgStatus === 0 ? 1 : 0
      // 修改状态
      changeUserStatus({liveId: u.liveId, userId: u.userId}).then(response => {
        let { code } = response;
        if (200 === code) {
          u.msgStatus = u.msgStatus === 0 ? 1 : 0
          let msg = u.msgStatus === 0 ? "已解禁" : "已禁言"
          this.msgSuccess(msg);
          return
        }
        this.msgError("操作失败");
      })
    },
    connectWebSocket() {
      // M3: WebSocket 地址从环境变量读取，缺省回退本地调试地址
      const wsUrl = process.env.VUE_APP_WS_URL || 'ws://localhost:7114/app/webSocket';
      let socket = new LiveWS(wsUrl, this.liveId, this.userId);
      socket.ws.onmessage = (e) => {
        this.handleWsMessage(e)
      }
      this.socket = socket
    },
    handleWsMessage(event) {
      console.log(event.data);
    },
    sendMessage() {
      console.log(this.newMsg);
      // 发送前简单校验
      if (this.newMsg.trim() === '') {
        return;
      }

      this.msgList.push({
        msg: this.newMsg,
        liveId: this.liveId,
        userId: this.userId,
        avatar: 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4Rv7nYYRvbQcJD9OogfiaMWDj8LTiceZ5J3Bm6Ph9pIiac9MVcwdfwPUI9XQ50ibo4TFp0ZHjgzLH6dw/132',
        nickName: '测试123123'
      })

      this.newMsg = '';
      this.$nextTick(() => {
        // 新消息加入后自动滚动到底部
        if (this.$refs.manageRightRef) {
          this.$refs.manageRightRef.update();
          const scrollDom = this.$refs.manageRightRef.$el.querySelector('.el-scrollbar__wrap');
          scrollDom.scrollTop = scrollDom.scrollHeight;
        }
      });
    }
  },
  destroyed() {
    this.socket?.close()
  }
}
</script>

<style scoped>
  .live-console {
    width: 90vw;
    padding: 10px 0;
  }
  .live-console .live-console-col {
    height: 88vh;
    margin-left: 5px;
    padding: 0 10px;
    background-color: white;
    border-radius: 4px;
  }
  /*隐藏水平滚动条*/
  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  /* 消息输入区域 */
  .chat-input {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ebeef5;
    background-color: #fff;
    min-height: 60px;
  }

  .chat-input .el-input {
    flex: 1;
    margin-right: 10px;
    min-height: 40px;
  }
</style>
