<template>
  <div id="roomsDetail">
    <el-row>
      <el-col :span="24" class="video"> </el-col>
    </el-row>
    <van-overlay :show="show" style="{ height: oheight, width: '100%' }">
      <div id="transformid" class="wrapper" :style="{ transform: transform, height: vheight, width: vwidth, padding: vpadding, position: 'absolute' }">
        <div :style="{ height: lheight, width: lwidth }" id="look-video-left" class="video-box col-div look-video-left"></div>
        <div id="look-video-right" :style="{ height: rheight, width: rwidth }" class="video-box col-div look-video-right"></div>
      </div>
      <div class="videoBtn" id="videobtnid" :style="{ top: btop, right: bright }">
        <el-button type="warning" round @click="full()" size="mini"><i class="el-icon-rank"></i></el-button>
      </div>
    </van-overlay>
    <el-row>
      <el-col :span="24" class="info">
        <el-col :span="24" class="title">
          <span>{{ roomInfos.title }}</span>
        </el-col>
        <el-col :span="24" class="num">
          <span>观看：{{ total }}</span>
        </el-col>
        <el-col :span="24" class="advert">
          <el-col :span="24">
            <van-swipe :autoplay="3000">
              <van-swipe-item v-for="(advert, index) in roomInfos.adverts" :key="index">
                <img width="100%" height="100px" v-lazy="advert.imgdir" @click="imgclick(advert.imgurl)" />
              </van-swipe-item>
            </van-swipe>
          </el-col>
        </el-col>
        <el-col :span="24" class="chat">
          <el-col :span="24" class="chatInfo" id="chatSell">
            <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-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_: '',
      roomInfos: {},
      sendmemo: '',
      total: 0,
      transform: 'rotate(0)',
      oheight: '200px',
      vwidth: '100%',
      vheight: '200px',
      rheight: '200px',
      rwidth: '30%',
      lheight: '200px',
      lwidth: '70%',
      show: true,
      vpadding: '0',
      btop: '167px',
      bright: '10px',
      isscreen: false,
      content: '',
      dataList: [],
    };
  },
  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 = '0';
      data.content = this.content;
      data.sendid = this.user.uid;
      data.sendname = this.user.name;
      const res = await this.create(data);
      if (this.$checkRes(res)) {
        //this.$message('发送成功');
        this.content = '';
      }
    },
    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 = '';
      }
      this.$nextTick(() => {
        document.getElementById('chatSell').scrollTop = document.getElementById('chatSell').scrollHeight + 275;
      });
    },
    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);
      }
    },
    onSubmit() {
      console.log(this.sendmemo);
    },
    async initclient() {
      this.userId_ = this.user.uid;
      const res = await this.gensignFetch({ userid: this.userId_ });
      if (this.$checkRes(res)) {
        this.client_ = TRTC.createClient({
          mode: 'live',
          sdkAppId: this.sdkAppId_,
          userId: this.userId_,
          userSig: res.data,
        });
        await this.client_.join({ roomId: this.roomname, role: 'audience' });
        this.client_.on('stream-subscribed', event => {
          const remoteStream = event.stream;
          // 远端流订阅成功，播放远端音视频流
          console.log(remoteStream);
          this.show = true;
          console.log('111' + remoteStream.getType());
          console.log('111' + remoteStream.getUserId());
          console.log('111' + remoteStream.getId());
          const userid_ = remoteStream.getUserId();
          const res_ = userid_.indexOf('-');
          if (res_ === -1) {
            this.rvideoid_ = 'video_' + remoteStream.getId();
            remoteStream
              .play('look-video-right')
              .then(() => {
                // autoplay success
              })
              .catch(e => {
                const errorCode = e.getCode();
                if (errorCode === 0x4043) {
                  // PLAY_NOT_ALLOWED,引导用户手势操作恢复音视频播放
                  remoteStream.resume();
                }
              });
          } else {
            this.lvideoid_ = 'video_' + remoteStream.getId();
            remoteStream
              .play('look-video-left')
              .then(() => {
                // autoplay success
              })
              .catch(e => {
                const errorCode = e.getCode();
                if (errorCode === 0x4043) {
                  // PLAY_NOT_ALLOWED,引导用户手势操作恢复音视频播放
                  remoteStream.resume();
                }
              });
          }
        });
        // 监听远端流增加事件
        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('stream-removed', event => {
          const remoteStream = event.stream;
          console.log('stop----');
          remoteStream.stop();
        });
      }
    },
    imgclick(url) {
      location.href = url;
    },
    full() {
      this.show = true;
      const width = document.documentElement.clientWidth;
      const height = document.documentElement.clientHeight;
      if (!this.isscreen) {
        console.log('全屏');
        this.isscreen = true;
        this.oheight = height;
        const transformid_ = document.getElementById('transformid');
        let style = 'width:' + height + 'px;';
        style += 'height:' + width + 'px;';
        style += '-webkit-transform: rotate(90deg); transform: rotate(90deg);';
        // 注意旋转中点的处理
        style += '-webkit-transform-origin: ' + width / 2 + 'px ' + width / 2 + 'px;';
        style += 'transform-origin: ' + width / 2 + 'px ' + width / 2 + 'px;';
        transformid_.style.cssText = style;
        this.transform = 'rotate(90deg)';
        // this.vwidth = height;
        console.log(height);
        this.vheight = `${width}px`;
        this.vwidth = `${height}px`;
        this.lheight = `${width}px`;
        this.rheight = `${width}px`;

        this.btop = `${height - 40}px`;
        this.bright = `${width - 50}px`;
      } else {
        console.log('退出全屏');
        this.isscreen = false;
        this.oheight = '200px';
        const transformid_ = document.getElementById('transformid');
        let style = 'width:' + width + 'px;';
        style += 'height: 200px;';
        transformid_.style.cssText = style;
        this.transform = 'rotate(0deg)';
        // this.vwidth = height;
        console.log(height);
        this.vheight = `200px`;
        this.vwidth = `${width}px`;
        this.lheight = `200px`;
        this.rheight = `200px`;

        this.btop = `167px`;
        this.bright = `10px`;
      }
    },
  },
  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>
.video {
  top: 0;
  left: 0;
  width: 100%;
  height: 200px;
}
.info {
  .title {
    text-align: center;
    padding: 10px 0;
    font-size: 16px;
    font-weight: bold;
  }
  .num {
    padding: 10px 0;
    font-size: 16px;
  }
  .advert {
    background: #fff;
    padding: 10px;
  }
  .chat {
    height: 260px;
    .chatInfo {
      height: 185px;
      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: 20px 0;
      }
    }
  }
}
.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  line-height: 120px;
  text-align: center;
  background-color: #39a9ed;
}
/deep/.video-js {
  height: 190px !important;
  border-radius: 10px;
}
.look-video-left {
  float: left;
  background: #000;
  grid-area: 1/1/3/4;
  justify-content: flex-end;
}
.look-video-right {
  float: right;
  background: #000;
  grid-area: 1/1/3/4;
  justify-content: flex-end;
}
.wrapper {
  background: #000;
  position: absolute;
  width: 100%;
}
.van-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 200px;
  background-color: rgba(0, 0, 0, 0.7);
}
.videoBtn {
  z-index: 999;
  position: absolute;
}
</style>
