<template>
  <!-- 直播中控台 start -->
  <el-row type="flex" justify="center" class="live-console" :gutter="10">
    <!-- 聊天 start -->
    <el-col class="live-console-col" :span="6">
      <el-tabs class="live-console-tab-left" v-model="tabRight.activeName" @tab-click="handleClick" :stretch="true">
        <el-tab-pane label="讨论" name="talk">
          <el-scrollbar style="height: 500px; width: 100%;" ref="manageRightRef">
            <el-row v-for="m in msgList" >
              <el-row v-if="m.userId !== userId" style="margin-top: 5px" type="flex" align="top" >
                <el-col :span="3" style="margin-left: 10px"><el-avatar :src="m.avatar"/></el-col>
                <el-col :span="15">
                  <el-row style="margin-left: 10px">
                    <el-col><div style="font-size: 12px; color: #999; margin-bottom: 3px;">{{ m.nickName }}</div></el-col>
                    <el-col :span="24" style="max-width: 200px;">
                      <div style="white-space: normal; word-wrap: break-word;background-color: #f0f2f5; padding: 8px; border-radius: 5px;font-size: 14px;width: 100%;">
                        {{ m.msg }}
                      </div>
                    </el-col>
                    <el-col>
                      <a style="cursor: pointer;color: #ff0000;padding: 8px 8px 0 0;font-size: 12px;" @click="changeUserState(m)">{{ m.msgStatus === 1 ? '解禁' : '禁言' }}</a>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <el-row v-if="m.userId === userId" style="padding: 8px 0" type="flex" align="top" justify="end">
                <div style="display: flex;justify-content: flex-end">
                  <div style="display: flex;justify-content: flex-end;flex-direction: column;max-width: 200px;align-items: flex-end">
                    <div style="font-size: 12px; color: #999; margin-bottom: 3px;">{{ m.nickName }}</div>
                    <div style="white-space: normal; word-wrap: break-word;width: 100%; background-color: #e6f7ff; padding: 8px; border-radius: 5px;font-size: 14px;">{{ m.msg }}</div>
                  </div>
                  <el-avatar :src="m.avatar" style="margin-left: 10px; margin-right: 10px;"/>
                </div>
              </el-row>
            </el-row>
            <!-- 底部留白 -->
            <div style="height: 20px;"></div>
          </el-scrollbar>

          <!-- 消息输入区域 -->
          <div style="padding: 10px; border-top: 1px solid #ebeef5; background-color: #fff; min-height: 120px;">
            <el-input
              type="textarea"
              v-model="newMsg"
              placeholder="请输入消息..."
              :rows="8"
              @keyup.enter.native="sendMessage"
              clearable
              resize="none"
              style="flex: 1; margin-right: 10px;"
            >
            </el-input>
            <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
              <el-button plain @click="sendMessage">发送</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <!-- 聊天 end -->


    <!-- 直播/视频 start -->
    <el-col class="live-console-col" :span="12">
      <div style="background: #000; border-radius: 5px; overflow: hidden; margin: 10px 5px;">
        <div style="border-radius: 5px; overflow: hidden;" v-if="liveType == 1">
          <video
            controls
            ref="livingPlayer"
            autoplay
            width="100%"
            style="display: block; background: #000; height: 45vh;"
          ></video>
        </div>
        <div style="border-radius: 5px; overflow: hidden;" v-else-if="liveType == 2">
          <video
            controls
            ref="videoPlayer"
            loop
            autoplay
            width="100%"
            :src="videoUrl"
            @click.prevent
            @contextmenu.prevent
            class="custom-video"
            style="display: block; background: #000; height: 45vh;"
          ></video>
        </div>
<!--        <div style="border-radius: 5px; overflow: hidden;" v-else-if="!isAudit">-->
<!--          <img :src="require('@/assets/images/videoIsAudit.png')" style="width: 100%; height: 45vh;">-->
<!--        </div>-->
<!--        <div style="border-radius: 5px; overflow: hidden;" v-else>-->
<!--          <img :src="require('@/assets/images/videoNotStart.png')" style="width: 100%; height: 45vh;">-->
<!--        </div>-->
      </div>
      <!-- 底部导航栏 -->
      <div style="display: flex; justify-content: space-around; padding: 15px 0; background: #fff; border-top: 1px solid #f0f0f0;">
        <div style="display: flex; flex-direction: column; align-items: center; cursor: pointer;" @click="handleClickRed">
          <i class="el-icon-money" style="font-size: 20px;"></i>
          <span style="font-size: 12px; margin-top: 4px;">红包配置</span>
        </div>
        <div style="display: flex; flex-direction: column; align-items: center; cursor: pointer;" @click="handleClickLottery">
          <i class="el-icon-present" style="font-size: 20px;"></i>
          <span style="font-size: 12px; margin-top: 4px;">抽奖配置</span>
        </div>
        <div style="display: flex; flex-direction: column; align-items: center; cursor: pointer;" @click="handleClickGoods">
          <i class="el-icon-goods" style="font-size: 20px;"></i>
          <span style="font-size: 12px; margin-top: 4px;">商品</span>
        </div>
        <div style="display: flex; flex-direction: column; align-items: center; cursor: pointer;" @click="handleClickOrder">
          <i class="el-icon-goods" style="font-size: 20px;"></i>
          <span style="font-size: 12px; margin-top: 4px;">直播订单</span>
        </div>
      </div>
      <el-radio-group v-model="tableRadio" >
        <el-radio-button label="订单数">订单数</el-radio-button>
      </el-radio-group>
      <div  style="position: relative;width: 100%; height: 300px;">
        <div ref="chartContainer" style="width: 100%; height: 100%;"></div>
        <div style="position: absolute; top: 10px; right: 10px; background: #fff; padding: 5px; z-index: 1;">
          <el-select v-model="searchQuery.timeOptions" placeholder="请选择" style="width: 150px"  @change="timeChange">
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-select v-model="searchQuery.timeGranularity" placeholder="请选择" style="width: 150px"  @change="timeGranularityChange">
            <el-option
              v-for="item in timeGranularity"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
<!--          <el-button type="primary" @click="applyFilter">搜索</el-button>-->
        </div>
      </div>
    </el-col>
    <!-- 直播/视频 end -->

    <!-- 用户列表 start -->
    <el-col class="live-console-col" :span="6">
      <el-tabs class="live-console-tab-right" v-model="tabLeft.activeName" @tab-click="handleClick" :stretch="true">
        <el-tab-pane :label="onlineLabel" name="online">
          <el-scrollbar ref="manageLeftRef_online" style="height: 800px; width: 100%;">
            <el-row style="margin-top: 10px" type="flex" align="middle" v-for="u in onlineUserList">
              <el-col :span="20">
                <el-row type="flex" align="middle">
                  <el-col :span="4" style="padding-left: 10px;"><el-avatar :src="u.avatar"></el-avatar></el-col>
                  <el-col :span="19" :offset="1">{{ u.nickName }}</el-col>
                  <el-col :span="19" :offset="1">{{ u.userId }}</el-col>
                </el-row>
              </el-col>
              <el-col :span="4" >
                <el-popover
                  width="100"
                  trigger="click">
                  <a style="cursor: pointer;color: #ff0000;" @click="changeUserState(u)">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</a>
                  <i class="el-icon-more" slot="reference"></i>
                </el-popover>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="offlineLabel" name="offline">
          <el-scrollbar ref="manageLeftRef_offline" style="height: 800px; width: 100%;">
            <el-row style="margin-top: 10px" type="flex" align="middle" v-for="u in offlineUserList">
              <el-col :span="20">
                <el-row type="flex" align="middle">
                  <el-col :span="4" style="padding-left: 10px;"><el-avatar :src="u.avatar"></el-avatar></el-col>
                  <el-col :span="19" :offset="1">{{ u.nickName }}</el-col>
                  <el-col :span="19" :offset="1">{{ u.userId }}</el-col>
                </el-row>
              </el-col>
              <el-col :span="4" >
                <el-popover
                  width="100"
                  trigger="click">
                  <a style="cursor: pointer;color: #ff0000;" @click="changeUserState(u)">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</a>
                  <i class="el-icon-more" slot="reference"></i>
                </el-popover>
              </el-col>
            </el-row>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane :label="silencedUserLabel" name="silenced">
          <el-scrollbar ref="manageLeftRef_silenced" style="height: 800px; width: 100%;">
            <el-row style="margin-top: 10px" type="flex" align="middle" v-for="u in silencedUserList">
              <el-col :span="20">
                <el-row type="flex" align="middle">
                  <el-col :span="4" style="padding-left: 10px;"><el-avatar :src="u.avatar"></el-avatar></el-col>
                  <el-col :span="19" :offset="1">{{ u.nickName }}</el-col>
                  <el-col :span="19" :offset="1">{{ u.userId }}</el-col>
                </el-row>
              </el-col>
              <el-col :span="4" >
                <el-popover
                  width="100"
                  trigger="click">
                  <a style="cursor: pointer;color: #ff0000;" @click="changeUserState(u)">{{ u.msgStatus === 1 ? '解禁' : '禁言' }}</a>
                  <i class="el-icon-more" slot="reference"></i>
                </el-popover>
              </el-col>
            </el-row>
          </el-scrollbar>
        </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 { getLivingUrl,getLive } from '@/api/live/live'
import { getLiveOrderTimeGranularity } from '@/api/live/liveOrder'
import { listLiveMsg } from '@/api/live/liveMsg'
import Hls from 'hls.js';
import LiveLotteryConf from '@/views/live/liveLotteryConf/index.vue'
import LiveRedConf from '@/views/live/liveRedConf/index.vue'
import LiveGoods from '@/views/live/liveGoods/index.vue'
import LiveOrder from '@/views/live/liveOrder/index.vue'
import echarts from 'echarts'


export default {
  name: "LiveConsole",
  components: { LiveLotteryConf,LiveRedConf,LiveGoods },
  data() {
    return {
      tabLeft: {
        activeName: "online",
      },
      tabRight: {
        activeName: "talk",
      },
      livingUrl: "",
      videoUrl: "",
      status: 0,
      loadMsgMaxPage: 2,
      his: null,
      liveVideo: {},
      socket: null,
      liveWsUrl: process.env.VUE_APP_LIVE_WS_URL + '/app/webSocket',
      userParams:{
        pageNum: 1,
        pageSize: 10,
        liveId: null
      },
      msgParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null
      },
      userList: [],
      msgList: [],
      newMsg: '',
      isAudit: false,
      myChart: null, // 用于存储 ECharts 实例
      liveType: 1,
      tableRadio: '订单数',
      // ... 其他数据 ...
      searchQuery: {timeOptions:'2',timeGranularity:'10',liveId: null}, // 搜索查询条件
      timeOptions: [
        {value:'2',label:'最近2小时',key:'2'},
        {value:'4',label:'最近4小时',key:'4'},
        {value:'all',label:'全场',key:'all'},
      ],
      timeGranularity: [
        {value:'10',label:'10分钟',key:'10'},
        {value:'30',label:'30分钟',key:'30'},
        {value:'60',label:'1小时',key:'60'},
      ],
    }
  },
  created() {
    // this.getLiveVideo()
    this.getList()
    this.connectWebSocket()
    this.getLive()
    this.searchQuery.liveId = this.liveId
  },
  computed: {
    liveId() {
      return this.$route.params.liveId;
    },
    userId() {
      return this.$store.state.user.user.userId
    },
    companyId() {
      return this.$store.state.user.user.companyId
    },
    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 '禁言'
    }
  },
  mounted() {
    this.getEchartsTables();
    if (this.videoUrl.length > 0) {
      const video = this.$refs.videoPlayer;
      video.play()
    }

  },
  methods: {
    // 切换音量状态
    toggleVolume() {
      const video = this.$refs.videoPlayer;
      if (video.volume > 0) {
        // 保存当前音量并静音
        this.lastVolume = video.volume;
        video.volume = 0;
        this.isMuted = true;
      } else {
        // 恢复之前的音量
        video.volume = this.lastVolume || this.initialVolume;
        this.isMuted = false;
      }
    },
    getLive(){
      getLive(this.liveId).then(res => {
        if (res.code == 200) {
          if (res.data.isAudit != 1) {
            this.$message.error("当前直播间未经审核");
            return
          }
          this.isAudit = true
          this.status = res.data.status
          if (res.data.status != 2) {
            this.$message.error("当前直播间未直播");
            return
          }
          if (res.data.liveType == 1) {
            this.getLiveUrl();
          } else {
            this.liveType = 2
            this.videoUrl = res.data.videoUrl;
          }
        } else {
          this.$message.error(res.msg)
        }
        this.liveInfo = res.data
      })
    },
    // ... 其他方法 ...
    timeChange(val) {
      this.searchQuery.timeOptions = val
      this.getEchartsTables(this.searchQuery)
      this.initChart()
    },
    timeGranularityChange(val) {
      this.searchQuery.timeGranularity =  val
      this.getEchartsTables()
      this.initChart()
    },
    getEchartsTables() {
      getLiveOrderTimeGranularity(this.searchQuery).then(res => {
        if (res.code == 200) {
          this.echartsXLine = res.hourlySlots
          this.echartsXValue = res.hourlySlotsValue
          this.initChart()
        }
      })
    },
    initChart() {
      const chartDom = this.$refs.chartContainer;
      this.myChart = echarts.init(chartDom);
      const option = {
        tooltip: {trigger: 'axis'},
        legend: {data: ['订单数']},
        xAxis: {type: 'category', boundaryGap: false, data: this.echartsXLine},
        yAxis: {type: 'value'},
        series: [
          {name: '订单数', type: 'line', data: this.echartsXValue}
        ],
      };
      this.myChart.setOption(option);
    },
    getLiveUrl(){
      getLivingUrl(this.liveId).then(res=>{
        if(res.code === 200) {
          this.livingUrl = res.livingUrl
          this.initPlayer()
        } else {
          this.msgError(res.msg);
        }
      })
    },

    handleClickRed(){
      this.$router.push({
        name: 'LiveRedConf',
        query: {
          liveId: this.liveId
        }
      })
    },
    handleClickLottery(){
      this.$router.push({
        name: 'LiveLotteryConf',
        query: {
          liveId: this.liveId
        }
      })
    },
    handleClickGoods(){
      this.$router.push({
        name: 'LiveGoods',
        query: {
          liveId: this.liveId
        }
      })
    },
    handleClickOrder(){
      this.$router.push({
        name: 'LiveOrder',
        query: {
          liveId: this.liveId
        }
      })
    },
    initPlayer(){
      var isUrl = this.livingUrl === null || this.livingUrl.trim() === ''
      if (Hls.isSupported() && !isUrl) {
        const videoElement = this.$refs.livingPlayer
        this.hls = new Hls();
        this.hls.attachMedia(videoElement);
        this.hls.on(Hls.Events.MEDIA_ATTACHED, () => {
          this.hls.loadSource(this.livingUrl);
          this.hls.on(Hls.Events.STREAM_LOADED, (event, data) => {
            videoElement.play();
          });
        });
      }
    },
    handleClick(tab) {

    },
    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 {code,rows,total} = response
        if (code === 200) {
          let totalPage = (total % this.userParams.pageSize == 0) ? Math.floor(total / this.userParams.pageSize) : Math.floor(total / this.userParams.pageSize + 1);
          rows.forEach(row => {
            if (!this.userList.some(u => u.userId === row.userId)) {
              this.userList.push(row)
            }
          })

          // 没加载完继续加载
          if (this.userParams.pageNum < totalPage) {
            this.userParams.pageNum = parseInt(this.userParams.pageNum) + 1;
            this.loadUserList()
          }
        }
      })
    },
    loadMsgList() {
      // 直播间消息
      listLiveMsg({
        liveId:this.liveId,
        pageNum: this.msgParams.pageNum,
        pageSize: this.msgParams.pageSize
      }).then(response => {
          let {code, rows,total} = response;
          if (code === 200) {
            let totalPage = (total % this.msgParams.pageSize == 0) ? Math.floor(total / this.msgParams.pageSize) : Math.floor(total / this.msgParams.pageSize + 1);
            rows.forEach(row => {
              if (!this.msgList.some(m => m.msgId === row.msgId)) {

                let user = this.userList.find(u => u.userId === row.userId)
                if (user) {
                  row.msgStatus = user.msgStatus
                } else {
                  row.msgStatus = 0
                }

                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.msgParams.pageNum < this.loadMsgMaxPage) {
              this.msgParams.pageNum = parseInt(this.msgParams.pageNum) + 1;
              this.loadMsgList()
            }

            // 同步更新消息列表中相同用户的状态
            this.userList.forEach(u => {
              this.msgList.filter(m => m.userId === u.userId).forEach(m => m.msgStatus = u.msgStatus)
            })
          }
        })

      // 添加滚动监听
      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) {
      // 修改状态
      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;
            }
          });

          this.userList.forEach(user => {
            if (user.userId === u.userId) {
              user.msgStatus = u.msgStatus;
            }
          });

          let msg = u.msgStatus === 0 ? "已解禁" : "已禁言"
          this.msgSuccess(msg);
          return
        }
        this.msgError("操作失败");
      })
    },
    connectWebSocket() {
      this.$store.dispatch('initLiveWs', {
        liveWsUrl: this.liveWsUrl,
        liveId: this.liveId,
        userId: this.userId
      })
      this.socket = this.$store.state.liveWs
      this.socket.onmessage = (event) => this.handleWsMessage(event)
    },
    handleWsMessage(event) {
      let { code, data } = JSON.parse(event.data)
      if (code === 200) {
        let { cmd } = data
        if (cmd === 'sendMsg') {
          let message = JSON.parse(data.data)

          let user = this.userList.find(u => u.userId === message.userId)
          if (user) {
            message.msgStatus = user.msgStatus
          } else {
            message.msgStatus = 0
          }
          delete message.params
          this.msgList.push(message)

          // 移动到底部
          this.$nextTick(() => {
            setTimeout(() => {
              this.$refs.manageRightRef.wrap.scrollTop = this.$refs.manageRightRef.wrap.scrollHeight - this.$refs.manageRightRef.wrap.clientHeight
            }, 200)
          })
        }
        else if (cmd === 'entry' || cmd === 'out') {

          let user = data
          if(this.userList.length > 0){
            this.userList = this.userList.filter(u => u.userId !== user.userId)
          }
          this.userList.push(user)
        }
      }
    },
    sendMessage() {
      // 发送前简单校验
      if (this.newMsg.trim() === '') {
        return;
      }

      let msg = {
        msg: this.newMsg,
        liveId: this.liveId,
        userId: this.userId,
        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 = '';
    }
  },
  destroyed() {
    this.socket?.close()
    this.hls?.destroy();
  }
}
</script>

<style scoped>
.talk-list{
  display: flex;
}
  .live-console {
    width: 90vw;
    padding: 10px 0;
    background-color: #f5f4f4;
  }
  .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: 120px;
  }

  .chat-input .el-input {
    flex: 1;
    margin-right: 10px;
  }

  .chat-input .el-textarea__inner {
    resize: none;
    min-height: 100px;
  }
  ::v-deep .el-textarea__inner {
    border: none !important;
    box-shadow: none !important;
    resize: none !important;
  }
  ::v-deep .el-textarea__inner:focus {
    border: none !important;
    box-shadow: none !important;
  }
::v-deep .el-tabs__item {
  padding: 0;
}
.live-console-tab-left ::v-deep .el-tabs__active-bar {
  width: 41px!important;
  margin-left: calc((100% / 1 - 41px) / 2);
  height: 4px;
  border-radius: 4px;
}

/* calc 3是tab数量 */
.live-console-tab-right ::v-deep .el-tabs__active-bar {
  width: 51px!important;
  margin-left: calc((100% / 3 - 51px) / 2);
  height: 4px;
  border-radius: 4px;
}
.custom-video {
  pointer-events: none !important; /* 完全禁止鼠标交互，避免悬停时显示工具栏 */
}

</style>
