<template>
  <div id="detailmetting">
    <el-row>
      <el-col :span="24" class="info">
        <el-col :span="4" class="left">
          <el-col :span="24" class="leftTop">
            <el-image :src="roomInfo.filedir"></el-image>
            <p>{{ roomInfo.title }}</p>
            <p>{{ roomInfo.content }}</p>
          </el-col>
          <el-col :span="24" class="leftDown">
            <el-col :span="8" class="btn" @click.native="shexiangBtn()">
              <i class="iconfont iconshexiangtou"></i>
              <p>摄像头</p>
            </el-col>
            <el-col :span="8" class="btn" @click.native="tianchongBtn()">
              <i class="iconfont iconmaikefeng-tianchong"></i>
              <p>麦克风</p>
            </el-col>
            <el-col :span="8" class="btn" @click.native="lookuserBtn()">
              <i class="el-icon-user"></i>
              <p>成员</p>
            </el-col>
          </el-col>
        </el-col>
        <el-col :span="20" class="right">
          <el-col :span="24" class="rightTop">
            <span @click="liveon"><i class="iconfont iconshexiangtou"></i>直播</span>
            <span @click="liveclose">关闭</span>
          </el-col>
          <el-col :span="18" class="video">
            <el-col :span="24" class="videoMeet">
              <el-col :span="18" class="one">
                <div id="main-video" class="video-box col-div" style="justify-content: flex-end"></div>
              </el-col>
              <el-col :span="6" class="two">
                <el-col :span="24" class="twoOne">
                  <div id="look-video-1" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
                </el-col>
                <el-col :span="24" class="twoOne">
                  <div id="look-video-2" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
                </el-col>
                <el-col :span="24" class="twoOne">
                  <div id="look-video-3" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
                </el-col>
              </el-col>
              <el-col :span="6" class="three">
                <div id="look-video-4" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
              </el-col>
              <el-col :span="6" class="three">
                <div id="look-video-5" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
              </el-col>
              <el-col :span="6" class="three">
                <div id="look-video-6" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
              </el-col>
              <el-col :span="6" class="three">
                <div id="look-video-7" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
              </el-col>
            </el-col>
          </el-col>
          <el-col :span="6" class="noVideo">
            <el-col :span="24" class="chatList">
              <el-col :span="24" class="list" v-for="(item, index) in dataList" :key="index">
                <p>
                  <span :class="item.sendname == user.name ? 'selfColor' : ''">{{ item.sendname }}</span>
                  <span>{{ item.content }}</span>
                </p>
              </el-col>
            </el-col>
            <el-col :span="24" class="chatInput">
              <el-col :span="19" class="input">
                <el-input type="textarea" maxlength="5000" show-word-limit v-model="content"></el-input>
              </el-col>
              <el-col :span="5" class="btn">
                <el-button type="primary" size="mini" @click="chatCreate">发送</el-button>
              </el-col>
            </el-col>
          </el-col>
          <el-col :span="24" class="rightDown"> <!-- 开始直播 --> </el-col>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog title="摄像头" :visible.sync="shexiangDia" width="30%" :before-close="handleClose">
      <el-select @change="cameraChange" v-model="cameraId" filterable placeholder="请选择摄像头">
        <el-option v-for="item in cameras" :key="item.deviceId" :label="item.label" :value="item.deviceId"> </el-option>
      </el-select>
    </el-dialog>
    <el-dialog title="麦克风" :visible.sync="tianchongDia" width="30%" :before-close="handleClose">
      <el-select @change="micrChange" v-model="microphoneId" filterable placeholder="请选择麦克风">
        <el-option v-for="item in microphones" :key="item.deviceId" :label="item.label" :value="item.deviceId"> </el-option>
      </el-select>
    </el-dialog>
    <el-dialog title="成员" :visible.sync="lookuserDia" width="30%" :before-close="handleClose">
      <el-row>
        <el-col :span="24" class="chatList">
          <el-col :span="24" class="list" v-for="(item, index) in userList" :key="index">
            <p>
              <i class="el-icon-user"></i>
              <span class="selfColor">{{ item.username }}</span>
              <span v-if="item.switchrole === 'anchor'"
                ><el-button type="primary" size="mini" @click="lookuserUpdate(item.id, 'audience')">移除</el-button></span
              >
              <span v-else><el-button type="primary" size="mini" @click="lookuserUpdate(item.id, 'anchor')">连麦</el-button></span>
            </p>
          </el-col>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: gensign } = createNamespacedHelpers('gensign');
const { mapActions: chat } = createNamespacedHelpers('chat');
const { mapActions: lookuser } = createNamespacedHelpers('lookuser');
import TRTC from 'trtc-js-sdk';
export default {
  name: 'detailmetting',
  props: {
    roomInfo: null,
  },
  components: {},
  data: function() {
    return {
      // 摄像头
      shexiangDia: false,
      cameraId: '',
      cameras: [],
      // 麦克风
      tianchongDia: false,
      microphoneId: '',
      microphones: [],
      client_: '',
      localStream_: '',
      sdkAppId_: '1400380125',
      content: '',
      userId_: '',
      open_: false,
      dataList: [],
      index: 0,
      userList: [],
      lookuserDia: false,
      isanchor: true,
    };
  },
  created() {
    this.initclient();
    this.getDevices();
    this.chatSearch();
  },
  mounted() {
    this.channel();
  },
  methods: {
    ...gensign(['gensignFetch']),
    ...chat(['query', 'create', 'fetch']),
    ...lookuser(['lookquery', 'lookupdate']),
    async lookuserBtn() {
      this.lookuserDia = true;
      this.lookuserSearch();
    },
    async lookuserSearch({ skip = 0, limit = 1000 } = {}) {
      const info = { roomid: this.id };
      let res = await this.lookquery({ skip, limit, ...info });
      this.$set(this, `userList`, res.data);
    },
    async lookuserUpdate(_id, _switchrole) {
      console.log(_id);
      let data = {};
      data.id = _id;
      data.switchrole = _switchrole;
      const res = await this.lookupdate(data);
      if (this.$checkRes(res)) {
        console.log(res.data);
        this.$message({
          message: '操作成功',
          type: 'success',
        });
        this.lookuserSearch();
      } else {
        this.$message.error(res.errmsg);
      }
    },
    async chatSearch({ skip = 0, limit = 1000 } = {}) {
      const info = { roomid: this.id };
      let res = await this.query({ skip, limit, ...info });
      this.$set(this, `dataList`, res.data);
    },
    async chatCreate() {
      let data = {};
      data.roomid = this.id;
      data.type = '1';
      data.content = this.content;
      data.sendid = this.user.uid;
      data.sendname = this.user.name;
      const res = await this.create(data);
      if (this.$checkRes(res)) {
        console.log(res.data);
      }
    },
    channel() {
      console.log('in function:');
      this.$stomp({
        [`/exchange/public_chat_` + this.id]: this.onMessage,
      });
    },
    onMessage(message) {
      // console.log('receive a message: ', message.body);
      let body = _.get(message, 'body');
      if (body) {
        body = JSON.parse(body);
        this.dataList.push(body);
        this.content = '';
      }
      // const { content, contenttype, sendid, sendname, icon, groupid, sendtime, type } = message.headers;
      // let object = { content, contenttype, sendid, sendname, icon, groupid, sendtime, type };
      // this.list.push(object);
    },
    async getDevices() {
      this.cameras = await TRTC.getCameras();
      this.microphones = await TRTC.getMicrophones();
    },
    async initclient() {
      console.log(this.user.uid);
      this.userId_ = this.user.uid;
      const res = await this.gensignFetch({ userid: this.userId_ });
      if (this.$checkRes(res)) {
        console.log(res.data);
        this.client_ = TRTC.createClient({
          useCloud: 1,
          mode: 'live',
          sdkAppId: this.sdkAppId_,
          userId: this.userId_,
          userSig: res.data,
        });
      }
    },
    async liveon() {
      this.open_ = true;
      console.log('8888--' + this.userId_);
      if (this.cameraId === '' || this.microphoneId === '') {
        this.$message({
          message: '请选择摄像头和麦克风',
          type: 'warning',
        });
        return;
      }
      await this.client_.join({ roomId: this.name, role: 'anchor' });
      this.localStream_ = await TRTC.createStream({
        audio: true,
        video: true,
        cameraId: this.cameraId,
        microphoneId: this.microphoneId,
        userId: this.userId_,
      });
      this.localStream_.setVideoProfile('480p');
      await this.localStream_.initialize();
      console.log('initialize local stream success');
      // publish the local stream
      await this.client_.publish(this.localStream_);
      this.localStream_.play('main-video');
      //$('#mask_main').appendTo($('#player_' + this.localStream_.getId()));
      // 订阅其他用户音视频
      this.client_.on('stream-subscribed', event => {
        const remoteStream = event.stream;
        // 远端流订阅成功，播放远端音视频流
        console.log('111' + remoteStream.getType());
        this.index = this.index + 1;
        console.log('111--index--->' + this.index);
        if (this.index < 8) {
          const id_ = 'look-video-' + this.index;
          remoteStream.play(id_);
        }
      });
      // 监听远端流增加事件
      this.client_.on('stream-added', event => {
        const remoteStream = event.stream;
        console.log('222' + remoteStream.getType());
        // 订阅远端音频和视频流
        this.client_.subscribe(remoteStream, { audio: true, video: true }).catch(e => {
          console.error('failed to subscribe remoteStream');
        });
      });
      this.client_.on('mute-video', event => {
        const remoteStream = event.stream;
        // 订阅远端音频和视频流
        if (this.index > 0) {
          this.index = this.index - 1;
        }

        console.log('333--index---->' + this.index);
      });
    },
    async liveclose() {
      // 关闭视频通话
      console.log(this.open_);
      if (this.open_) {
        const videoTrack = this.localStream_.getVideoTrack();
        if (videoTrack) {
          this.localStream_.removeTrack(videoTrack).then(() => {
            console.log('remove video call success');
            // 关闭摄像头
            videoTrack.stop();
            this.client_.unpublish(this.localStream_).then(() => {
              // 取消发布本地流成功
            });
          });
        }
      }
    },
    async cameraChange() {
      //await this.localStream_.switchDevice('video', this.cameraId);
    },
    async micrChange() {
      //await this.localStream_.switchDevice('audio', this.microphoneId);
    },
    // 选择打开摄像头
    shexiangBtn() {
      this.shexiangDia = true;
    },
    // 选择打开麦克风
    tianchongBtn() {
      this.tianchongDia = true;
    },
    // 关闭摄像头&麦克风
    handleClose(done) {
      done();
    },
  },
  computed: {
    ...mapState(['user']),
    id() {
      return this.$route.query.id;
    },
    name() {
      return this.$route.query.name;
    },
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped>
.info {
  background-color: #2a2b30;
  min-height: 840px;
  .left {
    .leftTop {
      min-height: 540px;
      padding: 0 15px;
      margin: 20px 0;
      p {
        color: #ccc;
      }
      p:nth-child(2) {
        padding: 10px 0;
      }
      p:nth-child(3) {
        line-height: 25px;
      }
    }
    .leftDown {
      padding: 10px 0 0 0;
      border-top: 1px solid #000;
      .btn {
        margin: 0 0 15px 0;
        color: #cccccc;
        text-align: center;
      }
      .btn:hover {
        cursor: pointer;
      }
    }
  }
  .right {
    .rightTop {
      height: 100px;
      background-color: #232428;
      text-align: right;
      color: #ccc;
      line-height: 100px;
      span {
        margin: 0 10px 0 0;
      }
      span:hover {
        cursor: pointer;
        color: #409eff;
      }
    }
    .video {
      min-height: 640px;
      background-color: #000;
      overflow: hidden;
      position: relative;
      .videoMeet {
        .one {
          height: 480px;
          overflow: hidden;
        }
        .two {
          height: 480px;
          overflow: hidden;
          .twoOne {
            height: 160px;
            overflow: hidden;
          }
        }
        .three {
          height: 160px;
          overflow: hidden;
        }
      }
    }
    .noVideo {
      position: relative;
      min-height: 640px;
      background-color: #000;
      border-left: 1px solid #fff;
      color: #fff;
      .chatList {
        height: 598px;
        padding: 5px 5px 5px 0px;
        overflow-y: auto;
        .list {
          margin: 0 0 10px 0;
          span:first-child {
            float: left;
            width: 17%;
            text-align: center;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            // font-weight: bold;
          }
          span:last-child {
            float: right;
            width: 82%;
          }
        }
      }
      .chatInput {
        position: absolute;
        bottom: 0;
        .el-button {
          width: 100%;
          padding: 13px 0;
        }
      }
    }
    .rightDown {
      height: 100px;
      background-color: #232428;
    }
  }
}
/deep/.el-dialog__body {
  min-height: 100px;
}
#main-video {
  width: 100%;
  height: 480px;
  min-height: 480px;
  grid-area: 1/1/3/4;
}
.lookvideo {
  width: 100%;
  height: 160px;
  min-height: 160px;
  grid-area: 1/1/3/4;
}
/deep/.el-textarea__inner {
  padding: 0 15px;
  line-height: 20px;
  border-radius: 0;
}
.selfColor {
  color: #ff0000;
}
</style>
