<template>
  <div class="console">

    <!-- 左侧：学员列表 -->
    <aside class="panel left-panel">
      <div class="panel-header">
        <span class="panel-title">学员列表</span>
      </div>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户昵称"
          size="small"
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter.native="searchUsers"
        />
        <el-button type="primary" size="small" @click="searchUsers">搜索</el-button>
      </div>
      <el-tabs class="user-tabs" v-model="tabLeft.activeName" @tab-click="handleUserClick" :stretch="true">
        <el-tab-pane :label="alLabel" name="al">
          <el-scrollbar class="user-scroll" ref="manageLeftRef_al">
            <div class="user-card" v-for="u in alDisplayList" :key="u.userId">
              <el-avatar :size="36" :src="u.avatar" />
              <div class="user-info">
                <div class="user-name">{{ u.nickName }}</div>
                <div class="user-id">ID: {{ u.userId }}</div>
              </div>
              <el-dropdown trigger="click" @command="cmd => cmd === 'mute' ? changeUserState(u) : blockUser(u)">
                <i class="el-icon-more action-btn"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="mute">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</el-dropdown-item>
                  <el-dropdown-item command="block" divided>拉黑</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="onlineLabel" name="online">
          <el-scrollbar class="user-scroll" ref="manageLeftRef_online">
            <div class="user-card" v-for="u in onlineDisplayList" :key="u.userId">
              <el-avatar :size="36" :src="u.avatar" />
              <div class="user-info">
                <div class="user-name">{{ u.nickName }}</div>
                <div class="user-id">ID: {{ u.userId }}</div>
              </div>
              <el-dropdown trigger="click" @command="cmd => cmd === 'mute' ? changeUserState(u) : blockUser(u)">
                <i class="el-icon-more action-btn"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="mute">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</el-dropdown-item>
                  <el-dropdown-item command="block" divided>拉黑</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="offlineLabel" name="offline">
          <el-scrollbar class="user-scroll" ref="manageLeftRef_offline">
            <div class="user-card" v-for="u in offlineDisplayList" :key="u.userId">
              <el-avatar :size="36" :src="u.avatar" />
              <div class="user-info">
                <div class="user-name">{{ u.nickName }}</div>
                <div class="user-id">ID: {{ u.userId }}</div>
              </div>
              <el-dropdown trigger="click" @command="cmd => cmd === 'mute' ? changeUserState(u) : blockUser(u)">
                <i class="el-icon-more action-btn"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="mute">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</el-dropdown-item>
                  <el-dropdown-item command="block" divided>拉黑</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="silencedUserLabel" name="silenced">
          <el-scrollbar class="user-scroll" ref="manageLeftRef_silenced">
            <div class="user-card" v-for="u in silencedDisplayList" :key="u.userId">
              <el-avatar :size="36" :src="u.avatar" />
              <div class="user-info">
                <div class="user-name">{{ u.nickName }}</div>
                <div class="user-id">ID: {{ u.userId }}</div>
              </div>
              <el-dropdown trigger="click" @command="cmd => cmd === 'mute' ? changeUserState(u) : blockUser(u)">
                <i class="el-icon-more action-btn"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="mute">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</el-dropdown-item>
                  <el-dropdown-item command="block" divided>拉黑</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </aside>

    <!-- 中间：消息管理 -->
    <main class="panel middle-panel">
      <div class="panel-header">
        <span class="panel-title">消息管理</span>
      </div>

      <div class="chat-area">
        <div class="message-container" @click="handleMessageBoxClick">
          <el-scrollbar class="chat-scroll" ref="manageRightRef">
            <div v-for="(m, msgIndex) in msgList" :key="msgRowKey(m, msgIndex)" class="msg-row">
              <!-- 管理员消息（右） -->
              <div v-if="m.userId === userId && m.msgId == null" class="msg-bubble msg-right">
                <div class="msg-meta">{{ m.nickName }}</div>
                <div v-if="m.replyUserName || m.replyContent" class="msg-reply">
                  回复 {{ m.replyUserName || '用户' }}：{{ m.replyContent }}
                </div>
                <div class="msg-text admin-text">{{ m.msg }}</div>
                <el-avatar :size="32" :src="m.avatar" class="msg-avatar" />
              </div>
              <!-- 用户消息（左） -->
              <div v-else class="msg-bubble msg-left">
                <el-avatar :size="32" :src="m.avatar" class="msg-avatar" />
                <div class="msg-content">
                  <div class="msg-meta">{{ m.nickName }}</div>
                  <div v-if="m.replyUserName || m.replyContent" class="msg-reply">
                    回复 {{ m.replyUserName || '用户' }}：{{ m.replyContent }}
                  </div>
                  <div class="msg-text">{{ m.msg }}</div>
                  <div class="msg-actions">
                    <a @click.stop="changeUserState(m)">{{ m.msgStatus === 1 ? '解禁' : '禁言' }}</a>
                    <a @click.stop="blockUser(m)">拉黑</a>
                    <a @click.stop="replyUser(m)">回复</a>
                    <a @click.stop="deleteMsg(m)">删除</a>
                  </div>
                </div>
              </div>
            </div>
            <div style="height: 16px;"></div>
          </el-scrollbar>
          <el-button
            v-if="showLoadLatestBtn"
            class="load-latest-btn"
            type="primary"
            size="mini"
            round
            @click.stop="loadLatestMessages"
            :disabled="isLoadingHistory"
            :loading="isLoadingHistory"
            icon="el-icon-bottom">
            回到最新
          </el-button>
        </div>
      </div>

      <div class="send-area">
        <el-input
          type="textarea"
          v-model="newMsg"
          placeholder="输入系统消息..."
          :rows="2"
          resize="none"
        />
        <div class="send-actions">
          <el-button size="small" type="primary" @click="sendMessage">发送消息</el-button>
          <el-button size="small" @click="sendPopMessage">弹窗消息</el-button>
          <el-button size="small" @click="showTopMsgDialog">官方消息</el-button>
        </div>
      </div>
    </main>

    <!-- 右侧：运营工具 -->
    <aside class="panel right-panel">
      <div class="panel-header">
        <span class="panel-title">运营工具</span>
      </div>

      <div class="tool-block">
        <div class="block-label">直播观看</div>
        <LivePlayer ref="livePlayer" :videoParam="videoParam" />
      </div>

      <div class="tool-block" v-if="timelineItems.length">
        <div class="block-label">时间轴任务</div>
        <div class="timeline-list">
          <div class="timeline-row" v-for="item in timelineItems.slice(0, 2)" :key="item.id || item.time">
            <span class="timeline-time">{{ formatDate(item.absValue) }}</span>
            <span class="timeline-name">{{ item.taskName }}</span>
            <el-button type="text" size="mini" class="timeline-del" @click="removeTimelineItem(item)">删除</el-button>
          </div>
        </div>
      </div>

      <div class="tool-block">
        <div class="block-label">水军自动化</div>
        <el-input
          type="textarea"
          :disabled="autoWatermark"
          v-model="watermarkTemplate"
          placeholder="每行一条弹幕内容"
          :rows="3"
          resize="none"
        />
        <div class="watermark-opts">
          <span>间隔</span>
          <el-input-number :disabled="autoWatermark" v-model.number="interval" :min="1" size="mini" controls-position="right" />
          <span>秒</span>
          <el-switch v-model="autoWatermark" @change="changeAutoWatermark" active-color="#6366f1" inactive-text="关闭" active-text="开启" />
        </div>
      </div>
    </aside>

    <!-- 官方消息对话框 -->
    <el-dialog title="发送官方消息" :visible.sync="topMsgDialogVisible" width="480px">
      <el-form :model="topMsgForm" label-width="80px">
        <el-form-item label="消息内容">
          <el-input type="textarea" v-model="topMsgForm.msg" placeholder="请输入消息内容" :rows="3" />
        </el-form-item>
        <el-form-item label="显示时长">
          <el-input-number v-model="topMsgForm.duration" :min="1" :max="60" size="small" />
          <span class="unit-text">分钟</span>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="topMsgDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendTopMessage">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import LivePlayer from './LivePlayer.vue';
import {blockUser, changeUserStatus, getLiveUserTotals, dashBoardWatchUserList} from '@/api/live/liveWatchUser'
import { listLiveSingleMsg,delLiveMsg } from '@/api/live/liveMsg'
import { getLive } from '@/api/live/live'
import { consoleList } from '@/api/live/task'
import ScreenScale from './ScreenScale.vue'; // 路径根据实际位置调整


export default {
  components: {
    LivePlayer,ScreenScale
  },
  props: {
    liveId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      watermarkIndex: 0,
      watermarkList:[],
      watermarkTemplate: '',
      liveInfo: {},
      videoParam:{
        startTime:'',
        livingUrl: '',
        liveType: 1,
        videoUrl: '',
      },
      msgList:[],
      // 按用户维度维护自见状态，避免消息行共享/重渲染导致按钮状态串台
      userSingleVisibleMap: {},
      currentTab: 'al',
      searchKeyword: '',
      globalVisible: false,
      interval: 10,
      autoWatermark: false,
      streamUrl: 'rtmp://your-live-stream-url',
      users: [
        { id: 1, name: '用户1', avatar: 'https://via.placeholder.com/40', status: 'online', statusText: '在线', silenced: false, msgStatus: false },
        { id: 2, name: '用户2', avatar: 'https://via.placeholder.com/40', status: 'online', statusText: '在线', silenced: false, msgStatus: true },
        { id: 3, name: '用户3', avatar: 'https://via.placeholder.com/40', status: 'offline', statusText: '离线', silenced: true, msgStatus: false },
        { id: 4, name: '用户4', avatar: 'https://via.placeholder.com/40', status: 'online', statusText: '在线', silenced: false, msgStatus: false },
        { id: 5, name: '用户5', avatar: 'https://via.placeholder.com/40', status: 'offline', statusText: '离线', silenced: false, msgStatus: false }
      ],
      messages: [
        { id: 1, user: '用户1', avatar: 'https://via.placeholder.com/30', text: '这个产品怎么样？', isVisible: true },
        { id: 2, user: '用户2', avatar: 'https://via.placeholder.com/30', text: '看起来不错', isVisible: true },
        { id: 3, user: '用户3', avatar: 'https://via.placeholder.com/30', text: '有优惠吗？', isVisible: true }
      ],
      timelineItems: [
        { "searchValue": null,
          "createBy": null,
          "createTime": "2025-09-23 10:36:17",
          "updateBy": null,
          "updateTime": "2025-10-17 09:18:00",
          "remark": null,
          "params": {},
          "id": 6573,
          "liveId": 128,
          "taskName": "2",
          "taskType": 1,
          "triggerType": 2,
          "triggerValue": "2025-01-01T00:02:00.000+0800",
          "absValue": "2025-11-23T10:43:00.000+0800",
          "status": 1,
          "finishStatus": 0 },
      ],
      userTotal: {
        online: 0,       // 在线总人数
        offline: 0,      // 离线总人数
        silenced: 0,      // 禁言总人数
        al: 0
      },
      tabLeft: {
        activeName: "al",
      },
      taskParams:{
        currentPage: 1,
        pageSize: 20,
        prevPage: 0,
        totalLoaded: 0,
        total: 0,
        hasMore: true,
        hasPrev: false
      },
      loadMsgMaxPage: 2,
      liveWsUrl: process.env.VUE_APP_LIVE_WS_URL + '/app/webSocket',
      alDisplayList: [],
      onlineDisplayList: [],    // 在线用户显示列表
      offlineDisplayList: [],   // 离线用户显示列表
      silencedDisplayList: [],  // 禁言用户显示列表
      // 各Tab的分页参数
      pageParams: {
        al: {
          currentPage: 1,
          pageSize: 20,
          prevPage: 0,
          totalLoaded: 0,
          total: 0,
          hasMore: true,
          hasPrev: false
        },
        online: {
          currentPage: 1,       // 当前页（下一页加载用）
          pageSize: 20,       // 当前页（下一页加载用）
          prevPage: 0,          // 上一页页码（上一页加载用）
          totalLoaded: 0,       // 已加载总条数
          total: 0,             // 总数据量
          hasMore: true,        // 是否有下一页
          hasPrev: false        // 是否有上一页
        },
        offline: {
          currentPage: 1,
          pageSize: 20,
          prevPage: 0,
          totalLoaded: 0,
          total: 0,
          hasMore: true,
          hasPrev: false
        },
        silenced: {
          currentPage: 1,
          pageSize: 20,
          prevPage: 0,
          totalLoaded: 0,
          total: 0,
          hasMore: true,
          hasPrev: false
        }
      },
      scrLoading: {
        al: { next: false, prev: false },
        online: { next: false, prev: false },
        offline: { next: false, prev: false },
        silenced: { next: false, prev: false }
      },
      newMsg:'',
      autoMsgTimer: null,
      checkInterval: 2000, // 检查间隔（1分钟，可根据需求调整）
      topMsgDialogVisible: false,
      topMsgForm: {
        msg: '',
        duration: 5
      },
      // 消息滚动控制：窗口固定 30 条，暂停后可上下游标翻页
      MSG_WINDOW_SIZE: 30,
      isAutoScrollEnabled: true,
      autoScrollTimer: null,
      showLoadLatestBtn: false,
      isLoadingHistory: false,
      hasMoreOlder: true,
      hasMoreNewer: false,
      // 边缘触达后需先离开再触达，才允许再次加载（防止贴边连打接口）
      olderEdgeArmed: true,
      newerEdgeArmed: true,
      // 回到最新过程中忽略滚动暂停，避免清空列表触发 scroll 又把自动跟随关掉
      suppressScrollPause: false,
      scrollDebounceTimer: null,
      msgParams: {
        pageNum: 1,
        pageSize: 30,
        liveId: null
      }
    };
  },
  computed: {
    userId() {
      return this.$store.state.user.user.userId
    },
    companyId() {
      return this.$store.state.user.user.companyId
    },
    onlineLabel() {
      return `在线(${this.userTotal.online})`;
    },
    alLabel() {
      return `全部(${this.userTotal.al})`;
    },
    offlineLabel() {
      return `离线(${this.userTotal.offline})`;
    },
    silencedUserLabel() {
      return `禁言(${this.userTotal.silenced})`;
    }
  },
  created() {
    if(!this.liveId) return
    this.getList()
    this.handleUserClick({name:'al'})
    this.connectWebSocket()
    this.getLive()
  },
  mounted() {
    this.$nextTick(() => {
      this.restoreChatScrollPosition();

      if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
        this.$refs.manageRightRef.wrap.addEventListener('scroll', this.saveChatScrollPosition);
      }
    });
    this.initScrollListeners();
  },
  methods: {
    // 点击消息框：暂停实时滚动，显示「回到最新」
    handleMessageBoxClick() {
      this.pauseMsgAutoScroll()
    },
    pauseMsgAutoScroll() {
      this.isAutoScrollEnabled = false
      if (this.autoScrollTimer) {
        clearTimeout(this.autoScrollTimer)
        this.autoScrollTimer = null
      }
      this.showLoadLatestBtn = true
    },
    scrollToBottom(forceScroll = false) {
      if (!this.isAutoScrollEnabled && !forceScroll) {
        return
      }
      if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
        this.$nextTick(() => {
          const wrap = this.$refs.manageRightRef.wrap
          if (!wrap) return
          if (forceScroll || this.isAutoScrollEnabled) {
            this.showLoadLatestBtn = false
            wrap.scrollTop = wrap.scrollHeight - wrap.clientHeight
          }
        })
      }
    },
    scrollMsgToTop() {
      if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
        this.$refs.manageRightRef.wrap.scrollTop = 0
      }
    },
    scrollMsgToBottom() {
      if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
        const wrap = this.$refs.manageRightRef.wrap
        wrap.scrollTop = Math.max(0, wrap.scrollHeight - wrap.clientHeight)
      }
    },
    // 回到最新：重新拉最近 30 条并恢复 socket 跟随滚动
    loadLatestMessages() {
      if (this.isLoadingHistory) {
        return
      }
      this.suppressScrollPause = true
      this.isLoadingHistory = true
      this.showLoadLatestBtn = false
      this.isAutoScrollEnabled = true
      this.hasMoreOlder = true
      this.hasMoreNewer = false
      this.olderEdgeArmed = true
      this.newerEdgeArmed = true
      if (this.scrollDebounceTimer) {
        clearTimeout(this.scrollDebounceTimer)
        this.scrollDebounceTimer = null
      }
      this.msgList = []
      this.msgParams.pageNum = 1
      this.msgParams.pageSize = this.MSG_WINDOW_SIZE
      this.loadMsgList(true)
    },
    decorateMsgRows(rows) {
      if (!rows || !rows.length) {
        return
      }
      rows.forEach(row => {
        let user = this.alDisplayList.find(u => u.userId === row.userId)
        row.msgStatus = user ? user.msgStatus : 0
        if (row.userId != null) {
          const uid = String(row.userId)
          if (!Object.prototype.hasOwnProperty.call(this.userSingleVisibleMap, uid)) {
            this.$set(this.userSingleVisibleMap, uid, Number(row.singleVisible) === 1 ? 1 : 0)
          } else {
            this.$set(row, 'singleVisible', Number(this.userSingleVisibleMap[uid]) === 1 ? 1 : 0)
          }
        }
      })
      this.alDisplayList.forEach(u => {
        rows.filter(m => m.userId === u.userId).forEach(m => { m.msgStatus = u.msgStatus })
      })
    },
    getFirstMsgId() {
      for (let i = 0; i < this.msgList.length; i++) {
        if (this.msgList[i] && this.msgList[i].msgId != null) {
          return this.msgList[i].msgId
        }
      }
      return null
    },
    getLastMsgId() {
      for (let i = this.msgList.length - 1; i >= 0; i--) {
        if (this.msgList[i] && this.msgList[i].msgId != null) {
          return this.msgList[i].msgId
        }
      }
      return null
    },
    // 向上翻：更早的 30 条，窗口裁剪后滚到中间
    loadOlderMessages() {
      if (this.isLoadingHistory || this.isAutoScrollEnabled || !this.hasMoreOlder) {
        return
      }
      const beforeMsgId = this.getFirstMsgId()
      if (beforeMsgId == null) {
        return
      }
      this.isLoadingHistory = true
      listLiveSingleMsg({
        liveId: this.liveId,
        pageNum: 1,
        pageSize: this.MSG_WINDOW_SIZE,
        beforeMsgId
      }).then(response => {
        const { code, rows } = response
        if (code !== 200) {
          return
        }
        let list = (rows || []).slice()
        this.hasMoreOlder = list.length >= this.MSG_WINDOW_SIZE
        list.reverse()
        list = list.filter(r => r.msgId != null && !this.msgList.some(m => m.msgId === r.msgId))
        this.decorateMsgRows(list)
        if (!list.length) {
          this.hasMoreOlder = false
          this.olderEdgeArmed = false
          this.$nextTick(() => this.scrollMsgToBottom())
          return
        }
        this.msgList = list.concat(this.msgList)
        if (this.msgList.length > this.MSG_WINDOW_SIZE) {
          this.msgList = this.msgList.slice(0, this.MSG_WINDOW_SIZE)
          this.hasMoreNewer = true
        }
        // 加载更早后滚到底：需先往下再滚回顶部，才能再次向上查
        this.$nextTick(() => {
          this.scrollMsgToBottom()
          this.olderEdgeArmed = false
          this.newerEdgeArmed = false
        })
      }).finally(() => {
        this.isLoadingHistory = false
      })
    },
    // 向下翻：更新的 30 条，窗口裁剪后滚到顶部
    loadNewerMessages() {
      if (this.isLoadingHistory || this.isAutoScrollEnabled || !this.hasMoreNewer) {
        return
      }
      const afterMsgId = this.getLastMsgId()
      if (afterMsgId == null) {
        return
      }
      this.isLoadingHistory = true
      listLiveSingleMsg({
        liveId: this.liveId,
        pageNum: 1,
        pageSize: this.MSG_WINDOW_SIZE,
        afterMsgId
      }).then(response => {
        const { code, rows } = response
        if (code !== 200) {
          return
        }
        let list = (rows || []).slice()
        this.hasMoreNewer = list.length >= this.MSG_WINDOW_SIZE
        list = list.filter(r => r.msgId != null && !this.msgList.some(m => m.msgId === r.msgId))
        this.decorateMsgRows(list)
        if (!list.length) {
          this.hasMoreNewer = false
          this.newerEdgeArmed = false
          this.$nextTick(() => this.scrollMsgToTop())
          return
        }
        this.msgList = this.msgList.concat(list)
        if (this.msgList.length > this.MSG_WINDOW_SIZE) {
          this.msgList = this.msgList.slice(this.msgList.length - this.MSG_WINDOW_SIZE)
          this.hasMoreOlder = true
        }
        // 加载更新后滚到顶：需先往上再滚回底部，才能再次向下查
        this.$nextTick(() => {
          this.scrollMsgToTop()
          this.olderEdgeArmed = false
          this.newerEdgeArmed = false
        })
      }).finally(() => {
        this.isLoadingHistory = false
      })
    },
    msgRowKey(m, index) {
      if (m && m.msgId != null && m.msgId !== '') {
        return 'msg-' + m.msgId
      }
      return 'msg-tmp-' + (m && m.userId != null ? m.userId : 'x') + '-' + (m && m.createTime ? m.createTime : '') + '-' + index
    },
    isUserSingleVisible(m) {
      if (!m || m.userId == null) {
        return false
      }
      const uid = String(m.userId)
      if (Object.prototype.hasOwnProperty.call(this.userSingleVisibleMap, uid)) {
        return Number(this.userSingleVisibleMap[uid]) === 1
      }
      return Number(m.singleVisible) === 1
    },
    applyUserSingleVisible(userId, status) {
      if (userId == null) {
        return
      }
      const uid = String(userId)
      const next = Number(status) === 1 ? 1 : 0
      this.$set(this.userSingleVisibleMap, uid, next)
      this.msgList.forEach(m1 => {
        if (String(m1.userId) === uid) {
          this.$set(m1, 'singleVisible', next)
        }
      })
    },
    singleVisible(m){
      // 仅更新同一用户的消息自见状态，不影响其他用户
      const status = this.isUserSingleVisible(m) ? 0 : 1
      this.applyUserSingleVisible(m.userId, status)
      // 消息自可见
      let msg = {
        liveId: this.liveId,
        userId: m.userId,
        userType: 0,
        cmd: 'singleVisible',
        status
      }
      this.socket.send(JSON.stringify(msg))
    },
    replyUser(m) {
      this.$prompt('请输入回复内容', '回复 ' + (m.nickName || m.userId), {
        confirmButtonText: '发送',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '回复内容不能为空'
      }).then(({ value }) => {
        const msg = {
          liveId: this.liveId,
          userId: m.userId,
          userType: 1,
          cmd: 'replyUser',
          msg: value.trim(),
          avatar: this.$store.state.user.user.avatar,
          nickName: this.$store.state.user.user.nickName,
          replyMsgId: m.msgId,
          replyUserName: m.nickName || '',
          replyContent: m.msg || ''
        }
        this.socket.send(JSON.stringify(msg))
      }).catch(() => {})
    },
    deleteMsg(m){
      // 1. 弹出确认对话框
      this.$confirm('此操作将永久删除该消息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delLiveMsg(m.msgId).then(res => {
          if (res.code === 200) {
            const index = this.msgList.findIndex(item => item.msgId === m.msgId);
            if (index !== -1) {
              this.msgList.splice(index, 1);
              console.log(`消息 ${m.msgId} 已在本地删除。`);
            }
            let msg = {
              liveId: this.liveId,
              userId: m.userId,
              msg: m.msgId, // 关键：将消息ID发送给后台
              cmd: 'deleteMsg',
            };
            this.socket.send(JSON.stringify(msg));
            // 可以在这里给用户一个删除成功的提示
            this.$message({
              type: 'success',
              message: '消息删除成功!'
            });
          }
        })
      }).catch(() => {
        // 3. 用户点击“取消”或关闭对话框后的回调
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    globalVisibleChange( val){
      // 消息自可见
      let msg = {
        liveId: this.liveId,
        userId: '9999',
        userType: 0,
        cmd: 'globalVisible',
        status:this.globalVisible ? 1 :0
      }
      this.socket.send(JSON.stringify(msg))
    },
    changeAutoWatermark( val){
      this.watermarkList = this.watermarkTemplate
        .split('\n')
        .map(line => line.trim())
        .filter(line => line !== '');
      if(this.watermarkTemplate.length < 1 || this.watermarkList.length === 0) {
        this.$message.warning('请先填写水印模板')
        this.$nextTick(() => {
          this.autoWatermark = false
        });
        return
      }
      this.disabled = this.autoWatermark
      if(this.autoWatermark){
        this.autoMsgTimer = setInterval(() => {
          this.sendNormalMessage()
        }, 1000 * this.interval)
      } else {
        clearInterval(this.autoMsgTimer)
        this.watermarkIndex = 0;
        this.watermarkList = [];
      }
    },
    sendNormalMessage() {
      if(this.watermarkIndex >= this.watermarkList.length){
        clearInterval(this.autoMsgTimer)
        this.watermarkIndex = 0;
        this.watermarkList = [];
        this.$message.success('自动发送消息已结束');
        this.$nextTick(() => {
          this.autoWatermark = false
        });
        return;
      }
      const curMsg = this.watermarkList[this.watermarkIndex]
      // 发送前简单校验
      if (curMsg.trim() === '') {
        return;
      }
      let msg = {
        msg: curMsg,
        liveId: this.liveId,
        userId: '9999',
        userType: 0,
        cmd: 'sendNormalMsg',
        avatar: this.$store.state.user.user.avatar,
        nickName: this.$store.state.user.user.nickName,
      }
      this.socket.send(JSON.stringify(msg))
      this.watermarkIndex += 1
    },
    // 弹窗消息
    sendPopMessage() {
      // 发送前简单校验
      if (this.newMsg.trim() === '') {
        return;
      }

      let msg = {
        msg: this.newMsg,
        liveId: this.liveId,
        userId: this.userId,
        userType: 1,
        cmd: 'sendPopMsg',
        avatar: this.$store.state.user.user.avatar,
        nickName: this.$store.state.user.user.nickName,
      }

      this.socket.send(JSON.stringify(msg))

      this.newMsg = '';
    },
    // 显示官方消息对话框
    showTopMsgDialog() {
      this.topMsgForm.msg = '';
      this.topMsgForm.duration = 5;
      this.topMsgDialogVisible = true;
    },
    // 发送官方消息
    sendTopMessage() {
      // 发送前简单校验
      if (this.topMsgForm.msg.trim() === '') {
        this.$message.warning('请输入消息内容');
        return;
      }

      if (!this.topMsgForm.duration || this.topMsgForm.duration < 1) {
        this.$message.warning('请输入有效的显示时长');
        return;
      }

      let msg = {
        msg: this.topMsgForm.msg,
        duration: this.topMsgForm.duration,
        liveId: this.liveId,
        userId: this.userId,
        userType: 1,
        cmd: 'sendTopMsg',
        avatar: this.$store.state.user.user.avatar,
        nickName: this.$store.state.user.user.nickName,
      }

      this.socket.send(JSON.stringify(msg))

      this.topMsgDialogVisible = false;
      this.$message.success('官方消息发送成功');
    },
    sendMessage() {
      // 发送前简单校验
      if (this.newMsg.trim() === '') {
        return;
      }

      // userId 使用专用 fs_user(400001)，与后端入库账号一致
      let msg = {
        msg: this.newMsg,
        liveId: this.liveId,
        userId: 400001,
        userType: 1,
        cmd: 'sendMsg',
        avatar: this.$store.state.user.user.avatar,
        nickName: this.$store.state.user.user.nickName || '直播管理员',
      }

      this.socket.send(JSON.stringify(msg))

      this.newMsg = '';
    },
    handleWsMessage(event) {
      const res = JSON.parse(event.data)
      const { code, data, msg } = res
      if (code !== 200) {
        this.$message.error(msg || '操作失败')
        return
      }
      if (!data) {
        if (msg) {
          this.$message.success(msg)
        }
        return
      }
      let { cmd } = data
      if (cmd === 'sendMsg') {
          let message = JSON.parse(data.data)

          let user = this.alDisplayList.find(u => u.userId === message.userId)
          if (user) {
            message.msgStatus = user.msgStatus
          } else {
            message.msgStatus = 0
          }
          delete message.params
          if (message.userId != null) {
            const uid = String(message.userId)
            if (Object.prototype.hasOwnProperty.call(this.userSingleVisibleMap, uid)) {
              message.singleVisible = Number(this.userSingleVisibleMap[uid]) === 1 ? 1 : 0
            } else {
              this.$set(this.userSingleVisibleMap, uid, Number(message.singleVisible) === 1 ? 1 : 0)
            }
          }
          // 暂停浏览历史时不插入实时消息，避免窗口膨胀；点「回到最新」再同步
          if (!this.isAutoScrollEnabled) {
            this.showLoadLatestBtn = true
            return
          }
          if (message.msgId != null && this.msgList.some(m => m.msgId === message.msgId)) {
            return
          }
          this.msgList.push(message)
          while (this.msgList.length > this.MSG_WINDOW_SIZE) {
            this.msgList.shift()
            this.hasMoreOlder = true
          }
          this.$nextTick(() => {
            this.autoScrollTimer = setTimeout(() => {
              this.scrollToBottom()
            }, 200)
          })
        } else if (cmd === 'entry' || cmd === 'out') {
          const user = data;
          const online = cmd === 'entry' ? 0 : 1; // 0=在线，1=离线
          const info = {
            online:online,
            msgStatus: user.msgStatus || 0,
            nickName: user.nickName || '',
            userType: user.userType || 0,
            userId: user.userId || '',
          };

          // 1. 更新总人数（在线/离线互转）
          if (cmd === 'entry') {
            this.userTotal.online += 1;
            this.userTotal.offline = Math.max(0, this.userTotal.offline - 1); // 确保不小于0
          } else {
            this.userTotal.offline += 1;
            this.userTotal.online = Math.max(0, this.userTotal.online - 1); // 确保不小于0
          }
          // 2. 强制更新相关列表（无论当前激活哪个Tab）
          if (cmd === 'entry') {
            // 用户进入：从离线列表删除，添加到在线列表
            this.offlineDisplayList = this.offlineDisplayList.filter(u => u.userId !== user.userId);
            const newOnlineList = this.onlineDisplayList.filter(u => u.userId !== user.userId);
            newOnlineList.push(info);
            this.onlineDisplayList = newOnlineList.slice(-40); // 限制最大50条
          } else {
            // 用户离开：从在线列表删除，添加到离线列表
            this.onlineDisplayList = this.onlineDisplayList.filter(u => u.userId !== user.userId);
            const newOfflineList = this.offlineDisplayList.filter(u => u.userId !== user.userId);
            newOfflineList.push(info);
            this.offlineDisplayList = newOfflineList.slice(-40); // 限制最大50条
          }
          // 3. 处理禁言列表（如果用户是禁言状态，无论进出都要同步）
          if (info.msgStatus === 1) {
            // 禁言用户：从禁言列表删除旧数据，添加新数据
            const newSilencedList = this.silencedDisplayList.filter(u => u.userId !== user.userId);
            newSilencedList.push(info);
            this.silencedDisplayList = newSilencedList.slice(-40);
          } else {
            // 非禁言用户：从禁言列表删除（如果存在）
            this.silencedDisplayList = this.silencedDisplayList.filter(u => u.userId !== user.userId);
          }

        } else if (cmd === 'singleVisible') {
          this.applyUserSingleVisible(data.userId, data.status)
        } else if (cmd === 'live_start') {

        } else if (cmd === 'live_end') {

        }
    },
    getLive(){
      getLive(this.liveId).then(res => {
        if (res.code == 200) {
          if (res.data.isAudit != 1) {
            this.$message.error("当前直播间未经审核");
            this.loading = false
            return
          }
          this.isAudit = true
          this.status = res.data.status
          this.videoParam.startTime = new Date(res.data.startTime).getTime()
          if(res.data.status == 4){
            this.videoParam.liveType = 3
            this.videoParam.videoUrl = res.data.videoUrl;
          }else {
            if (res.data.status != 2) {
              this.$message.error("当前直播间未直播");
              this.loading = false
              return
            }
            if (res.data.liveType == 1) {
              this.videoParam.livingUrl = res.data.flvHlsUrl
              this.videoParam.livingUrl = this.videoParam.livingUrl.replace("flv","m3u8")
              // this.$nextTick(() => {
              //   this.initPlayer()
              // })
              // this.processInterval = setInterval(this.updateLiveProgress, 1000);
            } else {
              this.videoParam.liveType = 2
              this.videoParam.videoUrl = res.data.videoUrl;
              // this.$nextTick(() => {
              //   this.initVideoPlayer(res.data.startTime)
              // })
            }
          }
          this.$nextTick(() => {
            this.globalVisible = res.data.globalVisible
            this.$refs.livePlayer.initPlayer()
          })
          this.loading = false
        } else {
          this.$message.error(res.msg)
          this.loading = false
        }
        this.liveInfo = res.data
      })
    },
    connectWebSocket() {
      this.$store.dispatch('initLiveWs', {
        liveWsUrl: this.liveWsUrl,
        liveId: this.liveId,
        userId: this.userId
      })
      this.socket = this.$store.state.liveWs[this.liveId]
      this.socket.onmessage = (event) => this.handleWsMessage(event)
    },
    changeUserState(u) {
      const displayList = this[`${this.currentTab}DisplayList`];
      // 修改状态
      changeUserStatus({liveId: u.liveId, userId: u.userId}).then(response => {
        let { code } = response;
        if (200 === code) {
          u.msgStatus = u.msgStatus === 0 ? 1 : 0
          // 同步更新消息列表中相同用户的状态
          this.msgList.forEach(msg => {
            if (msg.userId === u.userId) {
              msg.msgStatus = u.msgStatus;
            }
          });

          displayList.forEach(user => {
            if (user.userId === u.userId) {
              user.msgStatus = u.msgStatus;
            }
          });
          // 4. 关键：重新筛选所有Tab的显示列表，确保状态同步
          this.refreshUserDisplayLists(u);

          let msg = u.msgStatus === 0 ? "已解禁" : "已禁言"
          this.msgSuccess(msg);
          return
        }
        this.msgError("操作失败");
      })
    },
    refreshUserDisplayLists(user) {
      const { userId, msgStatus: newStatus, online } = user;
      const oldStatus = newStatus === 1 ? 0 : 1; // 操作前的状态（反向）

      // 1. 禁言操作（newStatus=1）：从原在线/离线列表移除，加入禁言列表
      if (newStatus === 1) {
        // 从在线/离线列表中移除该用户（根据当前在线状态）
        if (online === 0) {
          this.onlineDisplayList = this.onlineDisplayList.filter(u => u.userId !== userId);
          this.userTotal.online = Math.max(0, this.userTotal.online - 1);
        } else {
          this.offlineDisplayList = this.offlineDisplayList.filter(u => u.userId !== userId);
          this.userTotal.offline = Math.max(0, this.userTotal.offline - 1);
        }
        this.userTotal.silenced = this.userTotal.silenced + 1;
        // 添加到禁言列表（去重+限制长度）
        const silencedList = this.silencedDisplayList.filter(u => u.userId !== userId);
        silencedList.push(user);
        this.silencedDisplayList = silencedList.slice(-40);
      }

      // 2. 解禁操作（newStatus=0）：从禁言列表移除，回到原在线/离线列表
      else {
        // 从禁言列表移除
        this.silencedDisplayList = this.silencedDisplayList.filter(u => u.userId !== userId);
        this.userTotal.silenced = Math.max(0, this.userTotal.silenced - 1);
        // 回到对应的在线/离线列表（根据当前在线状态）
        if (online === 0) {
          // 加入在线列表（去重+限制长度）
          const onlineList = this.onlineDisplayList.filter(u => u.userId !== userId);
          onlineList.push(user);
          this.onlineDisplayList = onlineList.slice(-40);
          this.userTotal.online = this.userTotal.online + 1;
        } else {
          // 加入离线列表（去重+限制长度）
          const offlineList = this.offlineDisplayList.filter(u => u.userId !== userId);
          offlineList.push(user);
          this.offlineDisplayList = offlineList.slice(-40);
          this.userTotal.offline = this.userTotal.offline + 1;
        }
      }
    },
    blockUser(u){
      this.$confirm('是否确认封禁用户账号为:"' + u.nickName + '-' + u.userId + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return blockUser(u.userId);
      }).then(() => {
        if(u.msgStatus === 1){
          this.userTotal.silenced -= 1
          this.silencedDisplayList = this.silencedDisplayList.filter(user => user.userId !== u.userId)
        } else if( u.online === 0){
          this.userTotal.online -= 1
          this.onlineDisplayList = this.onlineDisplayList.filter(user => user.userId !== u.userId)
        } else {
          this.userTotal.offline -= 1
          this.offlineDisplayList = this.offlineDisplayList.filter(user => user.userId !== u.userId)
        }
        this.userTotal.al -= 1
        this.alDisplayList = this.alDisplayList.filter(user => user.userId !== u.userId)
        let msg = {
          msg: "",
          liveId: this.liveId,
          userId: u.userId,
          userType: 0,
          cmd: 'blockUser',
          avatar: this.$store.state.user.user.avatar,
          nickName: this.$store.state.user.user.nickName
        }
        this.socket.send(JSON.stringify(msg))
        this.msgSuccess("封禁成功");


      }).catch(() => {});
    },
    searchUsers(){
      this.resetUserParams()
      this.loadNextPage(this.currentTab)
    },
    /** 按 Tab 组装列表查询参数，与 liveUserTotals 口径一致 */
    buildWatchUserQuery(tabName, pageNum) {
      const queryParams = {
        liveId: this.liveId,
        pageNum,
        pageSize: 20,
        userName: this.searchKeyword
      };
      if (tabName === 'al') {
        queryParams.all = 1;
      } else if (tabName === 'online') {
        queryParams.online = 0;
        queryParams.msgStatus = 0;
      } else if (tabName === 'offline') {
        queryParams.online = 1;
        queryParams.msgStatus = 0;
      } else if (tabName === 'silenced') {
        // 禁言：不传 online，在线/离线禁言都查
        queryParams.msgStatus = 1;
      }
      return queryParams;
    },
    /** Tab 人数与列表接口 total 保持一致 */
    syncUserTotalFromList(tabName, total) {
      const fieldMap = { al: 'al', online: 'online', offline: 'offline', silenced: 'silenced' };
      const field = fieldMap[tabName];
      if (field != null && total != null) {
        this.$set(this.userTotal, field, total);
      }
    },
    handleUserClick(tab){
      const tabName = tab.name;
      this.currentTab = tabName;
      const params = this.pageParams[tabName];
      const displayList = this[`${tabName}DisplayList`];
      // 首次切换到该Tab或列表未满一页时重新拉取，保证人数与接口 total 一致
      if (displayList.length < 20) {
        // 重置分页参数，清空本地缓存列表（避免前端乐观更新与接口不一致）
        params.currentPage = 1;
        params.pageSize = 20;
        params.prevPage = 0;
        params.totalLoaded = 0;
        params.hasMore = true;
        params.hasPrev = false;
        this[`${tabName}DisplayList`] = [];
        this.loadNextPage(tabName);
      } else {
        // 非首次切换，恢复滚动位置
        this.$nextTick(() => {
          const scrollEl = this.getScrollElement(tabName);
          if (scrollEl) {
            scrollEl.scrollTop = this.tabScrollPositions[tabName] || 0;
          }
        });
      }
    },
    loadNextPage(tabName) {
      const params = this.pageParams[tabName];
      const displayList = this[`${tabName}DisplayList`];

      // 若没有更多数据或正在加载，直接返回
      if (!params.hasMore || this.scrLoading[tabName].next) {
        return;
      }

      this.scrLoading[tabName].next = true;
      const isFirstPage = params.currentPage === 1;
      const queryParams = this.buildWatchUserQuery(tabName, params.currentPage);
      // 调用接口加载对应状态的分页数据（需后端支持按状态筛选）
      dashBoardWatchUserList(queryParams).then(response => {
        this.scrLoading[tabName].next = false;
        if (response.code !== 200) return;

        const { rows, total } = response;
        params.total = total; // 记录总数据量
        this.syncUserTotalFromList(tabName, total);
        // 过滤重复数据（基于userId）
        const newRows = (rows || []).filter(row =>
          !displayList.some(u => u.userId === row.userId)
        );
        if (isFirstPage) {
          this[`${tabName}DisplayList`] = newRows;
        } else {
          displayList.push(...newRows);
          // 添加新数据并限制最大长度（避免内存占用过大）
          if (displayList.length >= 40) {
            this[`${tabName}DisplayList`] = displayList.slice(-40);
            const scrollEl = this.getScrollElement(tabName);
            this.$nextTick(() => {
              if (scrollEl) {
                scrollEl.scrollTop = scrollEl.scrollHeight * 0.5;
              }
            });
          }
        }
        // 更新分页状态
        params.hasMore = params.currentPage * params.pageSize < total;
        params.currentPage += 1;
        params.hasPrev = params.currentPage > 2; // 当前页>2时一定有上一页
        params.prevPage = params.currentPage - 2;
      }).catch(() => {
        this.scrLoading[tabName].next = false;
      });
    },
    // 新增：加载上一页（向上滚动时）
    loadPrevPage(tabName) {
      const params = this.pageParams[tabName];
      const displayList = this[`${tabName}DisplayList`];
      // 边界校验：无上一页/正在加载/当前页<=1
      if (!params.hasPrev || this.scrLoading[tabName].prev || params.currentPage <= 1) {
        return;
      }
      this.scrLoading[tabName].prev = true;
      const targetPage = params.prevPage > 0 ? params.prevPage : params.currentPage - 2;
      const queryParams = this.buildWatchUserQuery(tabName, targetPage);
      dashBoardWatchUserList(queryParams).then(response => {
        this.scrLoading[tabName].prev = false;
        if (response.code !== 200) return;

        const { rows, total } = response;
        if (total != null) {
          params.total = total;
          this.syncUserTotalFromList(tabName, total);
        }
        if (!rows || rows.length === 0) {
          params.hasPrev = false;
          return;
        }

        // 记录滚动位置（用于加载后校准）
        const scrollEl = this.getScrollElement(tabName);

        // 过滤重复数据并添加到列表头部
        const newRows = rows.filter(row => !displayList.some(u => u.userId === row.userId));
        this[`${tabName}DisplayList`] = [...newRows, ...displayList];
        params.totalLoaded += newRows.length;

        // 限制最大长度
        if (this[`${tabName}DisplayList`].length > 40) {
          this[`${tabName}DisplayList`] = this[`${tabName}DisplayList`].slice(0, 40);
        }

        // 更新分页状态
        params.prevPage = targetPage - 1;
        params.hasPrev = targetPage > 1; // 上一页页码>1时还有更多上一页
        params.currentPage = params.currentPage - 1;
        if(params.currentPage * 20 < params.total) params.hasMore = true;
        // 校准滚动位置（保持视觉连续性）
        this.$nextTick(() => {
          if (scrollEl) {
            scrollEl.scrollTop = scrollEl.scrollHeight * 0.5;
          }
        });
      }).catch(() => {
        this.scrLoading[tabName].prev = false;
      });
    },
    getList() {
      this.resetUserParams()
      this.resetMsgParams()
      // this.loadUserList()
      this.loadUserTotals(); // 先加载总人数
      // this.handleClick('online')
      // this.handleClick({name:'online'})
      this.loadMsgList()
      this.loadLiveTask()
    },
    formatDate(value) {
      // 检查值是否存在且为日期类型（或可转换为日期）
      if (!value) return '';

      let date;
      // 处理字符串类型的日期
      if (typeof value === 'string') {
        date = new Date(value);
      }
      // 处理Date对象
      else if (value instanceof Date) {
        date = value;
      }
      // 无效类型直接返回原值
      else {
        return value;
      }

      // 检查是否为有效日期
      if (isNaN(date.getTime())) {
        return value;
      }

      // 格式化年月日时分秒（补零处理）
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    loadLiveTask(){
      if(!this.taskParams.hasMore) return
      const queryParams = {
        liveId: this.liveId,
        pageSize: 10,
        pageNum: 1
      }
      consoleList(queryParams).then(res => {
        let {code, rows,total} = res;
        if (code === 200) {
          this.taskParams.total = total
          this.timelineItems = rows
          if(rows.length  < this.taskParams.pageSize){
            this.taskParams.hasMore = false
          }
          this.startTaskTimer()
        } else {
          this.stopTaskTimer()
        }
      })
    },
    loadMsgList(fromResumeLatest = false){
      // 初次/回到最新：拉最近 MSG_WINDOW_SIZE 条（desc → reverse 成正序）
      listLiveSingleMsg({
        liveId: this.liveId,
        pageNum: 1,
        pageSize: this.MSG_WINDOW_SIZE
      }).then(response => {
        let { code, rows } = response
        if (code === 200) {
          let list = (rows || []).slice()
          this.hasMoreOlder = list.length >= this.MSG_WINDOW_SIZE
          this.hasMoreNewer = false
          list.reverse()
          this.decorateMsgRows(list)
          this.msgList = list.slice(-this.MSG_WINDOW_SIZE)
          Object.keys(this.userSingleVisibleMap).forEach(uid => {
            const status = Number(this.userSingleVisibleMap[uid]) === 1 ? 1 : 0
            this.msgList.forEach(m => {
              if (String(m.userId) === uid) {
                this.$set(m, 'singleVisible', status)
              }
            })
          })
          this.$nextTick(() => {
            // 回到最新：强制恢复跟随并滚到底，避免被中间的 scroll 事件再次 pause
            if (fromResumeLatest || this.isAutoScrollEnabled) {
              this.isAutoScrollEnabled = true
              this.showLoadLatestBtn = false
              this.scrollMsgToBottom()
              this.$nextTick(() => {
                this.scrollMsgToBottom()
                this.isLoadingHistory = false
                this.suppressScrollPause = false
              })
            } else {
              this.isLoadingHistory = false
              this.suppressScrollPause = false
              this.showLoadLatestBtn = true
            }
          })
        } else {
          this.isLoadingHistory = false
          this.suppressScrollPause = false
        }
      }).catch(() => {
        this.isLoadingHistory = false
        this.suppressScrollPause = false
      })

      this.$nextTick(() => {
        if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
          this.$refs.manageRightRef.wrap.removeEventListener('scroll', this.manageRightScroll)
          this.$refs.manageRightRef.wrap.addEventListener('scroll', this.manageRightScroll)
        }
      })
    },
    // 消息滚动：暂停后顶/底触发游标加载；实时模式滚离底部则暂停
    manageRightScroll() {
      if (this.suppressScrollPause || this.isLoadingHistory) {
        return
      }
      if (this.scrollDebounceTimer) {
        clearTimeout(this.scrollDebounceTimer)
      }
      this.scrollDebounceTimer = setTimeout(() => {
        if (this.suppressScrollPause || this.isLoadingHistory) {
          return
        }
        this.saveChatScrollPosition()
        if (!this.$refs.manageRightRef || !this.$refs.manageRightRef.wrap) {
          return
        }
        const wrap = this.$refs.manageRightRef.wrap
        const scrollHeight = wrap.scrollHeight
        const clientHeight = wrap.clientHeight
        const currentScrollTop = wrap.scrollTop
        const maxScrollTop = Math.max(0, scrollHeight - clientHeight)

        if (this.isAutoScrollEnabled) {
          // 用户主动上滑离开底部 → 暂停实时跟随
          if (currentScrollTop < maxScrollTop - 50) {
            this.pauseMsgAutoScroll()
          }
          return
        }

        // 暂停态：到顶/到底各加载一次；离开边缘后重新武装，避免贴边连打
        this.showLoadLatestBtn = true
        const atTop = currentScrollTop <= 40
        const atBottom = currentScrollTop >= maxScrollTop - 40
        if (atTop) {
          if (this.olderEdgeArmed) {
            this.loadOlderMessages()
          }
        } else {
          this.olderEdgeArmed = true
        }
        if (atBottom) {
          if (this.newerEdgeArmed) {
            this.loadNewerMessages()
          }
        } else {
          this.newerEdgeArmed = true
        }
      }, 200)
    },
    loadUserTotals() {
      if (!this.liveId) return;
      // 假设后端提供一个接口返回总人数（如果没有，可通过首次加载全量数据后统计）
      getLiveUserTotals({ liveId: this.liveId }).then(res => {
        if (res.code === 200) {
          this.userTotal = res.data; // { online, offline, silenced }
        }
      });
    },
    toggleBlack(user) {
      user.isBlack = !user.isBlack;
    },
    toggleMute(user) {
      user.isMuted = !user.isMuted;
    },
    toggleVisible(msg) {
      msg.isVisible = !msg.isVisible;
    },
    deleteMessage(msg) {
      const index = this.messages.indexOf(msg);
      if (index > -1) {
        this.messages.splice(index, 1);
      }
    },
    addTimelineItem() {
      this.timelineItems.push({ time: '00:00', action: '新动作' });
    },
    removeTimelineItem(item) {
      const index = this.timelineItems.indexOf(item);
      if (index > -1) {
        this.timelineItems.splice(index, 1);
      }
    },
    resetUserParams() {
      // 重置各Tab的显示列表和分页参数
      this.alDisplayList = [];
      this.onlineDisplayList = [];   // 在线用户显示列表
      this.offlineDisplayList = [];   // 离线用户显示列表
      this.silencedDisplayList = [];  // 禁言用户显示列表
      this.pageParams=  {
        al: {
          currentPage: 1,
          pageSize: 20,
          prevPage: 0,
          totalLoaded: 0,
          total: 0,
          hasMore: true,
          hasPrev: false
        },
        online: {
          currentPage: 1,       // 当前页（下一页加载用）
          pageSize: 20,       // 当前页（下一页加载用）
          prevPage: 0,          // 上一页页码（上一页加载用）
          totalLoaded: 0,       // 已加载总条数
          total: 0,             // 总数据量
          hasMore: true,        // 是否有下一页
          hasPrev: false        // 是否有上一页
        },
        offline: {
          currentPage: 1,
          pageSize: 20,
          prevPage: 0,
          totalLoaded: 0,
          total: 0,
          hasMore: true,
          hasPrev: false
        },
        silenced: {
          currentPage: 1,
          pageSize: 20,
          prevPage: 0,
          totalLoaded: 0,
          total: 0,
          hasMore: true,
          hasPrev: false
        }
      },
        this.scrLoading = {
          al: { next: false, prev: false },
          online: { next: false, prev: false },
          offline: { next: false, prev: false },
          silenced: { next: false, prev: false }
        }
    },
    resetMsgParams() {
      this.msgList = []
      this.hasMoreOlder = true
      this.hasMoreNewer = false
      this.olderEdgeArmed = true
      this.newerEdgeArmed = true
      this.msgParams = {
        pageNum: 1,
        pageSize: this.MSG_WINDOW_SIZE,
        liveId: this.liveId
      }
      this.taskParams = {
        currentPage: 1,
        pageSize: 20,
        prevPage: 0,
        totalLoaded: 0,
        total: 0,
        hasMore: true,
        hasPrev: false
      }
    },
    getScrollElement(tabName) {
      const scrollRefs = {
        al: this.$refs.manageLeftRef_al,
        online: this.$refs.manageLeftRef_online,
        offline: this.$refs.manageLeftRef_offline,
        silenced: this.$refs.manageLeftRef_silenced
      };
      return scrollRefs[tabName]?.wrap;
    },
    // 初始化滚动监听（在mounted中调用）
    initScrollListeners() {
      // 为每个Tab的滚动容器添加监听
      this.$nextTick(() => {
        const scrollRefs = {
          al: this.$refs.manageLeftRef_al,
          online: this.$refs.manageLeftRef_online,
          offline: this.$refs.manageLeftRef_offline,
          silenced: this.$refs.manageLeftRef_silenced
        };

        Object.keys(scrollRefs).forEach(tabName => {
          const scrollEl = scrollRefs[tabName]?.wrap;
          if (scrollEl) {
            scrollEl.addEventListener('scroll', () =>
              this.handleTabScroll(tabName, scrollEl)
            );
          }
        });
      });
    },
    // 处理Tab滚动事件（判断是否触底）
    handleTabScroll(tabName, scrollEl) {
      const { scrollTop, scrollHeight, clientHeight } = scrollEl;
      const bottomThreshold = 50; // 距离底部100px触发下一页
      const topThreshold = 50;    // 距离顶部100px触发上一页

      // 加载下一页（滚动到底部附近）
      if (scrollHeight - scrollTop - clientHeight < bottomThreshold) {
        this.loadNextPage(tabName);
      }

      // 加载上一页（滚动到顶部附近）
      if (scrollTop < topThreshold) {
        this.loadPrevPage(tabName);
      }
    },
    // 恢复聊天滚动位置
    restoreChatScrollPosition() {
      if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
        this.$refs.manageRightRef.wrap.scrollTop = this.chatScrollTop;
      }
    },
    // 保存聊天滚动位置
    saveChatScrollPosition() {
      if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
        this.chatScrollTop = this.$refs.manageRightRef.wrap.scrollHeight - this.$refs.manageRightRef.wrap.clientHeight;
      }
    },
    /**
     * 停止任务检测定时器
     */
    stopTaskTimer() {
      if (this.taskTimer) {
        clearInterval(this.taskTimer);
        this.taskTimer = null;
      }
    },
    /**
     * 启动任务检测定时器
     */
    startTaskTimer() {
      // 先清除已有定时器，避免重复
      if (this.taskTimer) {
        clearInterval(this.taskTimer);
      }

      // 立即执行一次检查
      this.checkTaskExpiration();

      // 启动定时器，定期检查
      this.taskTimer = setInterval(() => {
        this.checkTaskExpiration();
      }, this.checkInterval);
    },
    /**
     * 检查时间轴第一条任务是否过期
     */
    checkTaskExpiration() {
      // 如果没有任务，直接返回
      if (!this.timelineItems || this.timelineItems.length === 0) {
        this.stopTaskTimer()
        return;
      };

      // 获取第一条任务的时间
      const firstTask = this.timelineItems[0];
      const taskTime = new Date(firstTask.absValue).getTime();
      const currentTime = new Date().getTime();

      // 如果任务时间已过当前时间（过期），重新加载任务列表
      if (taskTime < currentTime) {
        this.timelineItems.shift()
        this.loadLiveTask(); // 重新加载任务列表
      }
    },
  },
  beforeDestroy() {
    if (this.autoMsgTimer != null) {
      clearInterval(this.autoMsgTimer);
    }
    if (this.autoScrollTimer) {
      clearTimeout(this.autoScrollTimer);
    }
    if (this.scrollDebounceTimer) {
      clearTimeout(this.scrollDebounceTimer);
    }
    // 移除滚动监听器
    if (this.$refs.manageRightRef && this.$refs.manageRightRef.wrap) {
      this.$refs.manageRightRef.wrap.removeEventListener("scroll", this.manageRightScroll);
    }
  },
  // 使用 deactivated 和 activated 钩子替代 beforeDestroy 和 destroyed
  deactivated() {
    this.saveChatScrollPosition();
  },
  activated() {
    this.$nextTick(() => {
      this.restoreChatScrollPosition();
    });
    // todo yhq
    // this.$nextTick(() => {
    //   const video = this.$refs.videoPlayer;
    //   if (video != null) {
    //     this.initVideoPlayer(this.liveInfo.startTime)
    //   }
    // })
  },
};
</script>

<style scoped>
.console {
  display: flex;
  height: 100vh;
  background: #f5f8fc;
  gap: 12px;
  padding: 12px;
  box-sizing: border-box;
}

.panel {
  display: flex;
  flex-direction: column;
  background: #fff;
  overflow: hidden;
  border-radius: 12px;
  border: 1px solid #e8eef5;
  box-shadow: 0 1px 2px rgba(15, 23, 42, 0.03);
}

.left-panel {
  width: 28%;
  min-width: 260px;
}

.middle-panel {
  width: 44%;
  flex: 1;
}

.right-panel {
  width: 28%;
  min-width: 280px;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 16px 10px;
  border-bottom: 1px solid #f1f5f9;
}

.panel-title {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
}

.search-bar {
  display: flex;
  gap: 8px;
  padding: 10px 16px;
}

.user-tabs {
  flex: 1;
  overflow: hidden;
  padding: 0 8px;
}

.user-tabs >>> .el-tabs__header {
  margin-bottom: 8px;
}

.user-tabs >>> .el-tabs__item {
  font-size: 13px;
  padding: 0 12px;
}

.user-scroll {
  height: calc(100vh - 160px);
}

.user-card {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 10px;
  margin: 4px 8px;
  border-radius: 8px;
  transition: background 0.15s;
}

.user-card:hover {
  background: #f8fafc;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 13px;
  font-weight: 500;
  color: #334155;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-id {
  font-size: 11px;
  color: #94a3b8;
  margin-top: 2px;
}

.action-btn {
  cursor: pointer;
  color: #94a3b8;
  padding: 4px;
  border-radius: 4px;
}

.action-btn:hover {
  color: #6366f1;
  background: #f1f5f9;
}

.global-toggle {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #64748b;
  cursor: pointer;
}

.chat-area {
  flex: 1;
  padding: 0 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.message-container {
  position: relative;
  flex: 1;
  background: #f8fafc;
  border-radius: 10px;
  border: 1px solid #e8eef5;
  overflow: hidden;
}

.chat-scroll {
  height: calc(100vh - 280px);
}

.msg-row {
  padding: 6px 12px;
}

.msg-bubble {
  display: flex;
  gap: 8px;
  max-width: 85%;
}

.msg-right {
  flex-direction: row-reverse;
  margin-left: auto;
  align-items: flex-start;
}

.msg-left {
  align-items: flex-start;
}

.msg-content {
  max-width: 320px;
}

.msg-meta {
  font-size: 11px;
  color: #94a3b8;
  margin-bottom: 3px;
}

.msg-reply {
  font-size: 11px;
  color: #94a3b8;
  margin-bottom: 4px;
  word-break: break-all;
}

.msg-text {
  background: #fff;
  border: 1px solid #e8ecf0;
  padding: 8px 12px;
  border-radius: 0 10px 10px 10px;
  font-size: 13px;
  color: #334155;
  word-break: break-word;
  line-height: 1.5;
}

.admin-text {
  background: #eef2ff;
  border-color: #c7d2fe;
  border-radius: 10px 0 10px 10px;
}

.msg-actions {
  margin-top: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.msg-actions a {
  font-size: 11px;
  color: #6366f1;
  cursor: pointer;
}

.msg-actions a:hover {
  text-decoration: underline;
}

.load-latest-btn {
  position: absolute;
  bottom: 12px;
  right: 12px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
}

.send-area {
  padding: 12px 16px 16px;
  border-top: 1px solid #f1f5f9;
}

.send-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.tool-block {
  padding: 12px 16px;
  border-bottom: 1px solid #f1f5f9;
}

.block-label {
  font-size: 12px;
  font-weight: 600;
  color: #64748b;
  margin-bottom: 8px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.timeline-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.timeline-row {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  padding: 6px 8px;
  background: #f8fafc;
  border-radius: 6px;
}

.timeline-time {
  color: #6366f1;
  white-space: nowrap;
}

.timeline-name {
  flex: 1;
  color: #475569;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.timeline-del {
  color: #ef4444 !important;
}

.watermark-opts {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  font-size: 12px;
  color: #64748b;
}

.unit-text {
  margin-left: 6px;
  color: #94a3b8;
  font-size: 13px;
}

.el-scrollbar__wrap {
  overflow-x: hidden !important;
}
</style>
