<template>
  <div id="roomsDetail">
    <el-row>
      <el-col :span="24" class="info">
        <el-col :span="24" class="video">
          <el-col :span="24" class="videoMeet">
            <el-col :span="18" class="one">
              <div id="look-video-1" class="video-box col-div lookvideomain" style="justify-content: flex-end"></div>
            </el-col>
            <el-col :span="6" class="two">
              <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 :span="24" class="twoOne">
                <div id="look-video-4" 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-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 :span="6" class="three">
              <div id="look-video-8" class="video-box col-div lookvideo" style="justify-content: flex-end"></div>
            </el-col>
          </el-col>
          <el-col :span="24" class="videoBtn">
            <el-button :type="typevalue" round @click="liveon()" size="mini"><i class="el-icon-camera-solid"></i></el-button>
          </el-col>
        </el-col>
        <el-col :span="24" class="down">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="互动" name="first">
              <el-col :span="24" class="chat">
                <el-col :span="24" class="chatInfo">
                  <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="submit">
                  <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-tab-pane>
          </el-tabs>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import TRTC from 'trtc-js-sdk';
import { mapState, createNamespacedHelpers } from 'vuex';
import Vue from 'vue';
import { Swipe, SwipeItem, Lazyload } from 'vant';
import { Image as VanImage } from 'vant';
Vue.use(Swipe);
Vue.use(SwipeItem);
Vue.use(VanImage);
Vue.use(Lazyload);
const { mapActions: gensign } = createNamespacedHelpers('gensign');
const { mapActions: room } = createNamespacedHelpers('room');
const { mapActions: chat } = createNamespacedHelpers('chat');
export default {
  name: 'roomsDetail',
  props: {},
  components: {},
  data: function() {
    return {
      client_: null,
      localStream_: null,
      sdkAppId_: '1400380125',
      userId_: '',
      userSig_: '',
      roomInfos: {},
      sendmemo: '',
      total: 0,
      content: '',
      dataList: [],
      activeName: 'first',
      iscamera: false,
      typevalue: 'warning',
    };
  },
  created() {
    this.initclient();
    this.lookuserSearch();
    this.lookusercountsel();
    this.chatSearch();
  },
  mounted() {
    this.channel();
  },
  methods: {
    ...gensign(['gensignFetch']),
    ...room(['lookuserFetch', 'fetch', 'lookusercount']),
    ...chat(['query', 'create']),
    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 lookuserSearch() {
      let data = {};
      data.roomid = this.id;
      data.roomname = this.roomname;
      data.userid = this.user.userid;
      data.username = this.user.name;
      const res = await this.lookuserFetch(data);
      // 根据房间id查询房间详细信息
      let result = await this.fetch(this.id);
      if (this.$checkRes(result)) {
        console.log(result.data);
        this.$set(this, `roomInfos`, result.data);
      }
    },
    async lookusercountsel() {
      // 根据房间id查询房间详细信息
      let result = await this.lookusercount({ roomname: this.roomname });
      if (this.$checkRes(result)) {
        console.log(result.total);
        this.$set(this, `total`, result.total);
      }
    },
    async initclient() {
      this.userId_ = this.user.uid;
      const res = await this.gensignFetch({ userid: this.userId_ });
      if (this.$checkRes(res)) {
        this.userSig_ = res.data;
        this.client_ = TRTC.createClient({
          mode: 'live',
          sdkAppId: this.sdkAppId_,
          userId: this.userId_,
          userSig: res.data,
        });
        await this.client_.join({ roomId: this.roomname, role: 'anchor' });
        let i = 0;
        this.client_.on('stream-subscribed', event => {
          const remoteStream = event.stream;
          // 远端流订阅成功，播放远端音视频流
          console.log('111' + remoteStream.getType());
          i = i + 1;
          if (i < 8) {
            const id_ = 'look-video-' + i;
            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');
          });
        });
      }
    },
    async liveon() {
      if (this.iscamera) {
        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(() => {
              // 取消发布本地流成功
            });
          });
        }
        this.iscamera = false;
        this.typevalue = 'warning';
      } else {
        this.iscamera = true;
        this.typevalue = 'success';
        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('look-video-8');
      }
    },
    imgclick(url) {
      location.href = url;
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
  },
  computed: {
    ...mapState(['user']),
    id() {
      return this.$route.query.id;
    },
    roomname() {
      return this.$route.query.roomname;
    },
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped>
.info {
  .video {
    position: relative;
    background: #000;
    height: 280px;
    overflow: hidden;
    .videoMeet {
      .one {
        height: 210px;
        overflow: hidden;
      }
      .two {
        height: 210px;
        overflow: hidden;
        .twoOne {
          height: 70px;
          overflow: hidden;
        }
      }
      .three {
        height: 70px;
        overflow: hidden;
      }
    }
    .videoBtn {
      position: absolute;
      top: 10px;
      left: 10px;
    }
  }
  .down {
    border-top: 1px solid #ccc;
    min-height: 290px;
    background: #fff;
    .chat {
      height: 330px;
      .chatInfo {
        height: 275px;
        overflow-y: auto;
        padding: 0 10px;
        margin: 0 0 10px 0;
        .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%;
          }
        }
      }
      .submit {
        position: absolute;
        bottom: 0;
        .el-button {
          width: 100%;
          padding: 13px 0;
        }
      }
    }
  }
}
/deep/.el-button--mini,
.el-button--mini.is-round {
  padding: 12px 15px;
  border-radius: 0;
}
.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  line-height: 150px;
  text-align: center;
  background-color: #39a9ed;
}
/deep/.video-js {
  height: 190px !important;
  border-radius: 10px;
}
.lookvideomain {
  width: 100%;
  height: 210px;
  grid-area: 1/1/3/4;
}
.lookvideo {
  width: 100%;
  height: 70px;
  grid-area: 1/1/3/4;
}
/deep/.el-textarea__inner {
  padding: 0 15px;
  line-height: 20px;
  border-radius: 0;
}
.selfColor {
  color: #ff0000;
}
</style>
