<!-- 直播视频组件，用于邀请其他人与视频，by wuyang -->
<template>
  <div class="roomVideo">
    <div v-if="videoloading" class="roomVideo_dt"></div>
    <p v-if="videoloading" class="roomVideo_zb">正在准备会议...请稍等...</p>
    <Drawer title="邀请加入视频会议" placement="left" :closable="false" v-model="value1">
      <div class="yaoqlist">
        <div class="addVideo">
          <div class="topinput">
            <el-input placeholder="请输入手机号码" v-model="queryKey" class="searchInput" size="mini"
                      @keyup.enter.native="getList">
              <i slot="prefix" class="el-input__icon el-icon-search" @click="getList"></i>
            </el-input>
          </div>
          <div class="list" v-if="isShow">
            <!-- <el-checkbox-group v-model="info.noticeUserIdList"> -->
            <p @click="isFriend=!isFriend" class="title">好友<img src="../../assets/right.png" v-if="!isFriend"
                                                                class="right"><img
              src="../../assets/down.png" v-else class="down"></p>
            <ul v-if="isFriend" class="mains">
              <li v-for="item in friendlist" v-if="item.friendFlag">
                <!-- <el-checkbox :label="item.toUid">{{item.name}}</el-checkbox> -->
                <md-checkbox class="md-primary" v-model="info.noticeUserIdList" :value="item.toUid">{{item.name}}
                </md-checkbox>
              </li>
            </ul>
            <!-- </el-checkbox-group> -->
          </div>
          <div class="list" v-else>
            <p class="dialogcenter">查无此人</p>
          </div>
          <span slot="footer" class="dialog-footer">
            <p class="dialogcenters">
              <el-button icon='el-icon-phone-outline' class="addButton" @click="sendyq">邀请</el-button>
            </p>
		</span>

        </div>

      </div>
    </Drawer>

    <div id="meets">
      <!-- 加载动图... -->

      <el-tooltip content="邀请他人" placement="top" effect="dark">
        <i v-show="islive" @click="openDrawer" class="el-icon-circle-plus-outline yqjr"></i>
      </el-tooltip>
    </div>
    </ul>
  </div>
</template>

<script>
  import $ from 'jquery';
  import {
    getApi,
    postApi,
    getMessage
  } from "../../api/commonApi";
  import {
    webim
  } from '../../../static/sdk/webim.js'
  import {
    mapActions,
    mapState,
    mapGetters
  } from 'vuex';
  //  import {
  //   RemoteControl,
  //   setupScreenSharingForWindow,
  //   setupAlwaysOnTopRender,
  //   initPopupsConfigurationRender,
  //   setupWiFiStats
  // } from 'jitsi-meet-electron-utils';
  export default {
    data() {
      return {
        msgInfo: {
          fromUid: localStorage.getItem("userId"),
          toUid: '', //好友id
          msg: '',
          msgType: '1'
        },
        chatObj: {
          msgType: '1'
        },
        loginInfo: {
          'sdkAppID': 1400099911, //用户所属应用id,必填
          'identifier': localStorage.getItem("userId"), //当前用户ID,必须是否字符串类型，必填
          //					'identifier': 27,
          'accountType': 28447, //用户所属应用帐号类型，必填
          'userSig': '', //当前用户身份凭证，必须是字符串类型，必填
          'identifierNick': null, //当前用户昵称，不用填写，登录接口会返回用户的昵称，如果没有设置，则返回用户的id
          'headurl': 'img/me.jpg', //当前用户默认头像，选填，如果设置过头像，则可以通过拉取个人资料接口来得到头像信息
          'name': localStorage.getItem("userName")
        },
        saveChatInfoReq: { //保存数据库聊天记录的请求体
          "chatFlag": 1, //chatFlag:1.单聊 2.群聊【必传】
          "content": "", //发送内容
          "msgType": "1", //消息类型   1.文本 2.文件 3.语音 4.视频
          "receiver": "", //聊天对象id
          "sender": localStorage.getItem('userId'), //发送者id
          "fileUrl": '', //上传本地文件的文件Url
          "fileName": '', //上传本地文件的文件名称
          "fileSize": '', //文件大小
          "businessFileId": '', //上传网盘文件的文件id
          "system": true, //是否是网盘文件
          "fileId": '',//文件id
        },
        listeners: {
          "onConnNotify": this.onConnNotify, //监听连接状态回调变化事件,必填
          "onMsgNotify": this.onMsgNotify //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
        },
        islive: false,
        value1: false,
        isVide: false,
        queryKey: '',
        friendlist: [],
        isInside: false,
        isOnside: false,
        isFriend: false,
        checkList: [],
        allList: [],
        isShow: true,
        sindex: '-1',
        info: {
          content: '',
          type: '1',
          createUser: localStorage.getItem('userId'),
          noticeUserIdList: []
        },
        ads: true,
        videoloading: false,//视频加载...
        huiylist: []
      };
    },
    created() {
      this.videoloading = true;
      this.getList()
      this.getUserSign()
    },
    watch: {},
    mounted() {
      this.getInfo()
    },
    methods: {
      onMsgNotify(newMsgList) {

      },
      onConnNotify(resp) {
      },
      ...mapActions(['selectSession', 'setMessages', 'setMsgMap', 'setPrePageInfo']),
      openDrawer() {
        this.value1 = true
      },
      //开启视频(创建会议室)
      getInfo() {
        // debugger
        localStorage.setItem("noticeUserIdList", [0])
        let that = this;

        let userHeard = null;//用户头像
        let userName = null;//用户名
        let userNames = null;
        console.log()
        if (localStorage.getItem('photo') != null) {
          userHeard = localStorage.getItem('photo')
        }
        if (localStorage.getItem('userName') != null) {
          userNames = localStorage.getItem('userName')
        }
        let str = localStorage.getItem('video')
        let result = str.substr(30, str.length);//截取后台返回的房间地址
        console.log(result)

        const domain = "conference.lawbal.com";
        const options = {
          roomName: result,
          width: '100%',
          height: '100%',
          parentNode: document.querySelector('#meets')
        }
        const api = new JitsiMeetExternalAPI(domain, options);//初始化视频会议房间
        api.executeCommands({
          displayName: userNames,//设置本地会议名字
          avatarUrl: userHeard, //设置本地会议头像
        });
        // initPopupsConfigurationRender(api);
        // const iframe = api.getIFrame();
        // setupScreenSharingForWindow(iframe);
        // new RemoteControl(iframe); // eslint-disable-line no-new
        // setupAlwaysOnTopRender(api);
        // setupWiFiStats(iframe);

        function incomingMessageListener(object) {//他人加入触发事件
          console.log('有人加入了')
          console.log('获取房间内所有对象')
          console.log(object)
          that.getAllnameList(api.getAllRoomUsers())
          console.log(api.getAllRoomUsers())//获取房间内所有的人

        }

        function outgoingMessageListener(object) {//他人离开触发事件
          console.log('有人离开了')
          console.log('获取房间内所有对象')
          console.log(object)
          that.getAllnameList(api.getAllRoomUsers())
          console.log(api.getAllRoomUsers())//获取房间内所有的人
        }

        function videoConferenceLefts(object) {//自己离开触发事件
          console.log('自己离开了')
          console.log(object)
          // window.close() //关闭当前视频窗口
        }

        function videoConferenceJoineds(object) {//自己加入触发事件
          console.log('自己加入了')
          console.log('获取房间内所有对象')
          that.getAllnameList(api.getAllRoomUsers())
          console.log(api.getAllRoomUsers())
          console.log(object)
          that.videoloading = false;
          that.islive = true;
        }

        api.addEventListeners({
          participantJoined: incomingMessageListener,//他人加入监听
          participantLeft: outgoingMessageListener,//他人离开监听
          videoConferenceLeft: videoConferenceLefts,//自己离开监听
          videoConferenceJoined: videoConferenceJoineds//自己加入监听
        });


      },
      //获取所有人列表(好友，所内，所外)
      getList() {
        let that = this
        that.friendlist = []
        getApi("txCloud/friend/msg/list", {
          userId: localStorage.getItem("userId"),
          allFlag: true,
          queryKey: that.queryKey
        }, function (data) {
          if (that.queryKey != '') {
            that.isInside = true
            that.isOnside = true
            that.isFriend = true
          } else if (that.queryKey == '' && that.ads) {
            that.isInside = false
            that.isOnside = false
            that.isFriend = false
          }
          if (data.list.length == 0 && data.allUser.length == 0) {
            that.isShow = false
          } else {
            that.isShow = true
          }
          //获取列表后剔除房间中已有人员
          if (that.huiylist.length != 0 && that.huiylist != undefined) {
            that.allList = that.array_diff(data.allUser, that.huiylist)
            that.friendlist = that.array_diff(data.list, that.huiylist)
          } else {
            that.allList = data.allUser
            that.friendlist = data.list
          }
        }, function (data) {

        });
      },
      //清空列表
      clearList() {
        this.queryKey = ''
        this.info.noticeUserIdList = []
        this.getList()
      },
      mouseAdd(id) {
        this.sindex = id
      },
      mouseLeave() {
        this.sindex = '-1'
      },
      //发送邀请
      sendyq(){
        let that = this;
//        console.log(
//          that.info.noticeUserIdList
//        )
        if (that.info.noticeUserIdList.length == 0) {
          getMessage('请至少选择一个人', 'warning');
          return
        }

        localStorage.setItem("noticeUserIdList", that.info.noticeUserIdList)//存储会议人员id list

        that.info.content = localStorage.getItem('video')
        for (let item of that.info.noticeUserIdList) {
          that.goSendMsg('1', item)
        }
//        postApi('/system/noticeInfo/generate', that.info,
//          function (data) {
        getMessage('发送邀请成功', 'success')
        that.ads = true
        that.info.noticeUserIdList = []
        that.getList()
//          },
//          function (data) {
//            getMessage(data.msg, 'error')
//            that.info.noticeUserIdList = []
//
//          });
      },
      getUserSign() {
        let that = this;
        getApi('/txCloud/user/sign', {
          //					identifier: 27
          identifier: localStorage.getItem("userId")
        }, function (data) {
          that.loginInfo.userSig = data.userSig;
          var options = {
            'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
            'isLogOn': true //是否开启控制台打印日志,默认开启，选填
          };
          webim.login(
            that.loginInfo, that.listeners, options,
            function (resp) {
              that.loginInfo.identifierNick = resp.identifierNick; //设置当前用户昵称
              if (resp.headurl == 'null') {
                that.loginInfo.headurl = ''; //设置当前用户头像
              } else {
                that.loginInfo.headurl = resp.headurl; //设置当前用户头像
              }
              localStorage.setItem("loginInfo", JSON.stringify(that.loginInfo));
            },
            function (err) {
              getMessage('网络错误 请稍后重试', 'error')

            }
          )
        }, function (data) {
        });

      },
      goSendMsg(msgType, item, fileUrl, fileName, fileSize) {
        let str = localStorage.getItem('video')
        let result = str.substr(30, str.length);//截取后台返回的房间地址
        let that = this;
        let selSess = new webim.Session(this.chatObj.msgType == 1 ? webim.SESSION_TYPE.C2C : webim.SESSION_TYPE.GROUP, item, item, '',
          Math.round(new Date().getTime() / 1000));
        let msg = new webim.Msg(selSess, true, -1, Math.round(Math.random() * 4294967296), Math.round(new Date().getTime() /
          1000), this.loginInfo.identifier, webim.GROUP_MSG_SUB_TYPE.COMMON, this.loginInfo.identifierNick);
        let text_obj;
        text_obj = new webim.Msg.Elem.Text('lb://meeting.' + result);
        msg.addText(text_obj);
        console.log(msg)
        webim.sendMsg(msg, function (resp) {
          //发送成功
//           alert('发送成功')
          //保存记录到后台数据库
          that.saveChatInfo(msgType, fileUrl, fileName, fileSize, item);
          //组装后的消息
        }, function (err) {
          //发送失败
//           alert('发送失败' + JSON.stringify(err))
        })
      },
      /**
       * 保存一条聊天记录到数据库
       *
       * msgType   消息类型    1.文本 2.文件 3.语音 4.视频
       * isSystem  要上传的是否是网盘文件
       * fileUrl  要上传的本地文件Url
       * businessFileId  要上传的网盘文件id
       * fileName  要上传的本地文件名称
       * fileSize  文件大小
       */
      saveChatInfo(msgType, fileUrl, fileName, fileSize, item) {
        let fileType; //文件类型，后缀名
        this.saveChatInfoReq.msgType = msgType; //消息类型
        this.saveChatInfoReq.chatFlag = this.chatObj.msgType == 1 ? 1 : 2; //1.单聊 2.群聊【必传】
        this.saveChatInfoReq.content = msgType == 1 ? this.msgInfo.msg : fileName; //发送内容
        this.saveChatInfoReq.receiver = item; //聊天对象id
        this.saveChatInfoReq.fileUrl = fileUrl;
        this.saveChatInfoReq.fileName = fileName;
        this.saveChatInfoReq.fileSize = fileSize;
        let that = this;
        postApi('/chat/chatinfo/save',
          this.saveChatInfoReq,
          function (data) {
            let message = {
              type: msgType,
              content: msgType == 1 ? that.msgInfo.msg : fileName,
              url: fileUrl, //发送的文件url,如果是网盘文件不用加前缀，因为网盘文件返回的fileUrl是全路径
              size: fileSize, //发送的文件大小
              fileType: fileType,
              self: true,
              socialFileId: data.chatInfo.socialFileId,
              time: new Date(),
              fromAccountName: that.loginInfo.name,
              fromAccountImage: that.loginInfo.headurl,
              isGroup: that.chatObj.msgType == 1 ? true : false
            };
//            that.messages.push(message);
//            that.setMessages(that.messages);
          },
          function (data) {
            //失败
            getMessage(data.msg, 'error');
          })
      },
      //添加好友
      addFriend(id) {
        let that = this
        let toUidList = []
        toUidList.push(id)
        postApi("txCloud/friend/add", {
          fromUid: localStorage.getItem("userId"),
          toUidList: toUidList
        }, function (data) {
          getMessage('添加成功', 'success')
          that.ads = false
          that.getList()
        }, function (data) {
          getMessage(data.msg, 'error')
        });
      },
      //数组去除(求差集)
      array_diff(a, b) {
        for (let i = 0; i < b.length; i++) {
          for (let j = 0; j < a.length; j++) {
            if (a[j].name == b[i]) {
              a.splice(j, 1);
              j = j - 1;
            }
          }
        }
        return a;
      },// 获取房间内所有人员的namelist
      getAllnameList(val){
        this.huiylist = [];
        for (let i in val) {
          this.huiylist.push(val[i].displayName)
          console.log(val[i].displayName)
        }
        console.log(this.huiylist)
        this.getList()

      }

    }
  }
</script>

<style scoped="scoped">
  @import 'addVideo.css';
  @import 'video.css';

  .roomVideo {
    position: relative;
    height: 100%;
    width: 100%;
  }

  .roomVideo_dt {
    position: absolute;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('../../assets/line_plane.gif');
    filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale')";
    -moz-background-size: 100% 100%;
    background-size: 100% 100%;
    z-index: 9999;
  }

  .roomVideo_zb {
    position: absolute;
    z-index: 10000;
    top: 83%;
    left: 42%;
  }
</style>

<style>
  .addVideo .md-checkbox {
    margin: 0;

  }

</style>
