<template>
  <el-container id="wechat">
    <el-main>
      <div style="height:100%;">
        <slot>
          <ul class="mychat">
            <div class="wechat">
              <ul class="allLei">
                <!-- 所有消息记录 -->
                <li @click="selecticon(1)">
                  <div>
                    <el-badge :is-dot="noticeCount>0" class="item">
                      <img src="../../assets/xiaotubiao/xiaoxis.svg" v-if="isIcon==1">
                      <img src="../../assets/xiaotubiao/xiaoxib.svg" v-else>
                    </el-badge>
                  </div>
                </li>
                <!-- 好友聊天列表 -->
                <li @click="selecticon(2)">
                  <div>
                    <img src="../../assets/xiaotubiao/lianxis.svg" v-if="isIcon==2">
                    <img src="../../assets/xiaotubiao/lianxib.svg" v-else>
                  </div>
                </li>                <!-- 所有消息记录 -->
                <!--<li @click="selecticon(3)">-->
                <!--<div>-->
                <!--<img src="../../assets/xiaotubiao/tongzhis.svg" v-if="isIcon==3">-->
                <!--<img src="../../assets/xiaotubiao/tongzhib.svg" v-else>-->
                <!--</div>-->
                <!--</li>-->
                <!-- 群组聊天列表 -->
                <!-- 所有消息记录 -->
                <!--<li @click="selecticon(3)">-->
                <!--<div>-->
                <!--<img src="../../assets/xiaotubiao/tongzhis.svg" v-if="isIcon==3">-->
                <!--<img src="../../assets/xiaotubiao/tongzhib.svg" v-else>-->
                <!--</div>-->
                <!--</li>-->
                <!-- 群组聊天列表 -->
                <li @click="selecticon(4)">
                  <div>
                    <img src="../../assets/xiaotubiao/qunzus.svg" v-if="isIcon==4">
                    <img src="../../assets/xiaotubiao/qunzub.svg" v-else>
                  </div>
                </li>
              </ul>
            </div>
            <div class="leftChat">
              <div class="wechat-search">
                <!-- <button @click="close">关闭</button> -->
                <div class="wechat-inner">
                  <el-input placeholder="输入好友名称" v-model="input23" @keyup.enter.native="searchFrienfd">
                    <i slot="prefix" class="el-input__icon el-icon-search" @click="searchFrienfd"></i>
                  </el-input>

                  <el-dropdown @command="handleCommand" trigger="click">
                    <div class="adds">
                      <img src="../../assets/xiaotubiao/jiahaoyou.svg" alt="">
                    </div>
                    <el-dropdown-menu slot="dropdown">
                      <div class="addslist">
                        <div class="sanjiao"></div>
                        <el-dropdown-item command="isAddf" icon="el-icon-circle-plus-outline">加好友</el-dropdown-item>
                        <el-dropdown-item command="isAddg" icon="el-icon-circle-plus-outline">加群聊</el-dropdown-item>
                        <!--<el-dropdown-item command="isAddy" icon="el-icon-message">发邮件</el-dropdown-item>-->
                      </div>
                    </el-dropdown-menu>

                  </el-dropdown>
                </div>

              </div>

              <div class="xiaoxilist" v-show="isIcon==1||isIcon==3">
                <li :class="{isSelect:isSet==index}" v-for="(item,index) in recentSessionList"
                    @click="initDemoApp(item.Type == 1 ? item.To_Account : item.ToAccount,index,item)"
                    @mouseenter="deleteEnter(index)" @mouseleave="deleteLeave">
                  <div>
                    <!--<el-badge is-dot class="item">-->
                    <el-badge :value="item.UnreadMsgCount" :max="99" class="item" v-if='item.UnreadMsgCount > 0'>
                      <!-- 单聊 -->
                      <img :src="'http://101.132.238.98:9090/' + item.C2cImage" class="icons"
                           v-if="item.Type == 1 && (item.C2cImage && item.C2cImage != 'null')"/>
                      <img src="../../assets/maildatou.png" class="icons"
                           v-if="item.Type == 1 && (!item.C2cImage || item.C2cImage == 'null')"/>
                      <!-- 群聊 -->
                      <img :src="item.GroupImage" class="icons"
                           v-if="item.Type == 2 && (item.GroupImage && item.GroupImage != 'null')"/>
                      <img src="../../assets/chat/defaule-group-header.png" class="icons"
                           v-if="item.Type == 2 && (!item.GroupImage || item.GroupImage == 'null')"/>
                    </el-badge>

                    <el-badge class='item' v-if="item.UnreadMsgCount == 0">
                      <!-- 单聊 -->
                      <img :src="'http://101.132.238.98:9090/' + item.C2cImage" class="icons"
                           v-if="item.Type == 1 && (item.C2cImage && item.C2cImage != 'null')"/>
                      <img src="../../assets/maildatou.png" class="icons"
                           v-if="item.Type == 1 && (!item.C2cImage || item.C2cImage == 'null')"/>
                      <!-- 群聊 -->
                      <img :src="item.GroupImage" class="icons"
                           v-if="item.Type == 2 && (item.GroupImage && item.GroupImage != 'null')"/>
                      <img src="../../assets/chat/defaule-group-header.png" class="icons"
                           v-if="item.Type == 2 && (!item.GroupImage || item.GroupImage == 'null')"/>
                    </el-badge>

                  </div>
                  <div class="div-session">
                    <!--<p class="title1">-->
                    <div class="top">
                      <p v-if="item.Type == 1" class="name">{{item.C2cNick}}</p>
                      <p v-if="item.Type == 2" class="name">{{item.GroupNick}}</p>
                      <p class="time">{{timestampToTime(item.MsgTimeStamp)}}</p>
                    </div>
                    <!--</p>-->
                    <p v-if="item.LastMsg.MsgBody[0].MsgContent.Text" class="lastMsg">
                      <span
                        v-html="replace_em(item.LastMsg.MsgBody[0].MsgContent.Text)">{{item.LastMsg.MsgBody[0].MsgContent.Text | selectsa}}</span>
                      <a @click.stop="deleteSes(item)" v-if="deleteindex==index" class="rightsend">删除</a>
                    </p>
                    <p v-if="!item.LastMsg.MsgBody[0].MsgContent.Text" class="lastMsg">
                      <span>[文件]</span>
                      <a @click.stop="deleteSes(item)" v-if="deleteindex==index" class="rightsend">删除</a>
                    </p>
                  </div>
                </li>
              </div>
              <!-- <p v-if="zanwuhh==0">暂无会话记录呦~</p> -->
              <!-- 我的好友列表 start -->
              <friendList ref="friendlist" v-if="isIcon==2||isIcon==5" @chooseFriend='chooseFriend'></friendList>
              <!-- 我的好友列表 end -->

              <!-- 我的群列表 start -->
              <groupList ref="groupslist" v-if="isIcon==4" @chooseFriend='chooseFriend'></groupList>
              <!-- 我的群列表 end -->


            </div>


            <!--<ul class="liebiao" v-if="isIcon==2" v-for="items in letter">
              <p class="nameTitle" :id="gernerateId(items)">{{items}}</p>
              <li v-for="item in userbiao" v-if="item.initials==items">-->
            <!--<p class="zimu">{{item.initials}}</p>-->
            <!--<img :src="item.image" alt="" class="icons">
                <span class="yname">
                          {{item.name}}
                        </span>
              </li>
            </ul>-->
            <li class="rightChat">
              <!--<daibanchat v-if="isIcon!=5&&chat==0"  v-on:isSmall="isSmall"></daibanchat>-->
              <!--<emailchat v-if="isIcon==5" v-on:isSmall="isSmall"></emailchat>-->
              <!-- 我的日程 -->
              <!-- <schedulechat v-if="isSet=='-3'" v-on:isSmall="isSmall"></schedulechat> -->
              <chatroom ref='chatRoomView' v-if="isIcon>=0&&isIcon!=5&&chat==1" v-on:isSmall="isSmall" :name='chatName'
                        :chatObj='checkedChatObj'
                        :isShowMore='isShowMore' @getNewGroup="getNewGroup" @getNewmessage='getNewmessage' :showUpload="options.showUpload" :showVideo="options.showVideo"
                        @getMoreChatRecord='getMoreChatRecord' @isShua="isShualeft" :messages="messagesList"/>
            </li>
          </ul>
        </slot>
      </div>
      <el-dialog title="添加好友" v-dialogDrag :visible.sync="isAdd" width="300px" :modal="false"
                 :close-on-click-modal="false"
                 custom-class="addDialig" :before-close="clearAll">
        <addFriend ref="addfriend" @isShua="isShua"></addFriend>
      </el-dialog>

      <el-dialog title="创建群组" v-dialogDrag :visible.sync="isAdds" width="300px" :modal="false"
                 :close-on-click-modal="false"
                 custom-class="addDialig" :before-close="clearAlls">
        <addGroup ref="addgroup" @isShua="isShuas"></addGroup>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
  import $ from 'jquery'
  import schedulechat from './schedulechat'
  import chatroom from './chatRoom'
  import friendList from './friendList'
  import groupList from './groupList'
  import addFriend from './addFriend'
  import addGroup from './addGroup'
  import {
    getApi,
    postApi,
    getMessage
  } from "../../api/commonApi"
//  import {
//    mapActions,
//    mapState,
//    mapGetters
//  } from 'vuex';
  import {
    webim
  } from '../../../static/sdk/webim.js'
  import {
    getHandledPermissionList,
    getCookie
  } from "../../utils";
  import {
    setToken,
    setCompanyId
  } from '../../utils/auth'
  export default {
    name: 'wChat',
    filters: {
      selectsa(value) {
        return value.slice(0, 20)
      }
    },
    props: {
      titlex: String,
      id: [String, Number],
//      showUpload: Boolean,
      options: {
        type: Object,
        required: true,
        default: function () {
          return {}
        }
      }
    },
    data() {
      return {
        sessions: [],
        msgMap: {},
        infoMap: {},
        prePageInfo:{},
        messagesList: [],
        zanwuhh: 0,//暂无会话  0 无  1有
        chat: 0,//0 全部提醒 1聊天室
        isAdd: false,
        isAdds: false,
        input23: '', //搜索
        info1: {
          time: '',
          title: '',
          type: '',
          userName: ''
        },
        info2: {
          time: '',
          title: '',
          type: '',
          userName: ''
        },
        info3: {
          time: '',
          title: '',
          type: '',
          userName: ''
        },
        noticeCount: 0,
        scheduleCount: 0,
        mailCount: 0,
        title: '标题',
        selToID: '',
        selectElement: '',
        isSet: '-1',
        isIcon: '1', //1：最新会话       2：好友列表        3：群列表
        websock: null,
        isFullScreen: false,
        nowMarginTop: 0,
        // 字母列表
        letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
          'V', 'W', 'X', 'Y', 'Z'
        ],
        list: [],
        userbiao: [],
        letter: [],
        //当前用户身份
        loginInfo: {
          'sdkAppID': this.options.sdkAppID ? this.options.sdkAppID : '', //用户所属应用id,必填
          'identifier': localStorage.getItem("userId"), //当前用户ID,必须是否字符串类型，必填
          //					'identifier': 27,
          'accountType': this.options.accountType ? this.options.accountType : '', //用户所属应用帐号类型，必填
          'userSig': '', //当前用户身份凭证，必须是字符串类型，必填
          'identifierNick': null, //当前用户昵称，不用填写，登录接口会返回用户的昵称，如果没有设置，则返回用户的id
          'headurl': this.options.headurl ? this.options.headurl : 'img/me.jpg', //当前用户默认头像，选填，如果设置过头像，则可以通过拉取个人资料接口来得到头像信息
          'name': localStorage.getItem("userName")
        },
        //监听事件
        listeners: {
          "onConnNotify": this.onConnNotify, //监听连接状态回调变化事件,必填
          "onMsgNotify": this.onMsgNotify //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
        },
        recentSessionReq: {
          "From_Account": localStorage.getItem('userId'),
          "Count": 50,
        },
        recentSessionList: [], //最近会话列表
        chatName: '', //聊天对方名称或者群名称
        checkedChatObj: {}, //选中的聊天对象
        getChatInfoReq: { //获取数据库聊天记录的请求体
          chatFlag: 2, //1.单聊 2.群聊【必传】
          friendId: '', //好友id或群组id【必传】
          userId: localStorage.getItem('userId'), //用户id【必传】
          queryKey: '', //搜索内容【可选】
          page: 1, //页码【可选】
          limit: 15, //每页条数【可选】
        }, //获取app服务端数据库聊天记录的请求体
        chatType: 1, //聊天类型     1：单聊     2：群聊
        isShowMore: false, //是否展示查看更多消息按钮
        windowHeight: window.screen.height, //分辨率高度
        count: 0,
        deleteindex: '-1',
        unreadCount: 0,

        //群组信息
        myGroupListReq: {
          "Member_Account": localStorage.getItem('userId'),
          "Limit": 200,
          "Offset": 0,
          "GroupBaseInfoFilter": [ // 需要哪些基础信息字段
            "Type", "Name", "Introduction", "Notification", "FaceUrl", "CreateTime", "Owner_Account",
            "LastInfoTime", "LastMsgTime", "NextMsgSeq", "MemberNum", "MaxMemberNum", "ApplyJoinOption", "ShutUpAllMember"
          ],
          "SelfInfoFilter": [ // 需要自身在群内的信息
            "Role", // 群内身份
            "JoinTime", // 入群时间
            "MsgFlag", // 消息屏蔽类型
            "UnreadMsgNum" // 未读消息数量（IM云后台计算得出）
          ],
          "AppDefinedDataFilter_Group": [ // 群成员维度自定义字段过滤，该默认情况是没有的
            "principal"
          ]
        },
        myGroupLists: [],//我的群组列表
        a: {
          heart: 0
        }
      }
    },
    created() {
      if (localStorage.getItem("userId") == null || localStorage.getItem("userId") == undefined) {
        this.login()
      }
      this.initWebSocket()
//			this.getNews()
      if (localStorage.getItem('info1') != undefined) {
        this.Info1 = JSON.parse(localStorage.getItem('info1'))
      }
      if (JSON.parse(localStorage.getItem('info2')) != undefined) {
        this.Info2 = JSON.parse(localStorage.getItem('info2'))
      }
      if (JSON.parse(localStorage.getItem('info3')) != undefined) {
        this.Info3 = JSON.parse(localStorage.getItem('info3'))
      }
      if (localStorage.getItem('groupId') !== undefined && localStorage.getItem('groupId') !== '' && localStorage.getItem('groupId') !== null) {
        this.isIcon = 4
      } else {
        this.isIcon = 2
      }
      //页面刚进入时开启长连接
      this.getUserSign()
      this.getFired()
      //			this.initDemoApp(this.currentSessionId, '-1')
      this.getFiredList()
      // this.initWebSocket();//初始化 ws

      window.addEventListener('setItem', () => {
        let colors = localStorage.getItem('lbcolors');
        console.log(colors)
      })
    },
    computed: {
      dialogVisible: {
        get: function () {
          return this.$store.state.dialogVisible
        },
        set: function (newValue) {
          this.$store.commit('newDialogVisible', newValue)
        }
      },
//      ...mapState([
//        'sessions',
//        'msgMap',
//        'prePageInfo',
//        'messages',
//        'infoMap'
//      ]),
//      ...mapGetters([
//        'unreadMsg'
//      ])
    },
    mounted() {
      let that = this
//      that.$store.dispatch('initSessions');
      that.changeColor('011a3ee6')

      that.timer = setInterval(() => {
        that.a.heart++
        that.websock.send(JSON.stringify(that.a));
      }, 10000)
    },
    watch: {
      '$route': 'getRecentSession'
//      unreadMsg: function () {
//        this.getRecentSession()
//      }
    },
    components: {
//			daibanchat,
      schedulechat,
      chatroom,
      friendList,
      groupList,
      addFriend,
      addGroup
    },
    methods: {
      login() {
        let that = this;
        postApi('/user/userLogin/login', {
          userPhone: '13861329349',
          password: '123456',
          photo: '',
          wxHeadUrl: '',
          wxNickName: '',
          unionId: ''
        }, function(data) {
          that.loginDeal('2', data)
        }, function(data) {
          getMessage(data.msg, 'error')
        });
      },
      loginDeal(code, data) {
        let that = this;
        if (window.require) {
          localStorage.setItem('token',data.userInfo.token)
        }else{
          setToken(data.userInfo.token)
        }
        localStorage.setItem('userId', data.userInfo.userId)
        localStorage.setItem('teamFlag', data.userInfo.teamFlag)
        localStorage.setItem('companyId', data.userInfo.companyId)
        localStorage.setItem('userName', data.userInfo.userName)
        localStorage.setItem('logo', data.userInfo.logo)
        localStorage.setItem('permissionList',JSON.stringify(data.userInfo.permissionList));
        localStorage.setItem('lbcolors',data.userInfo.skin)

        localStorage.setItem('companyProvince', data.userInfo.companyProvince)
        localStorage.setItem('companyAddress', data.userInfo.companyAddress)
        localStorage.setItem('isshow', 1)
        localStorage.setItem('photo', data.userInfo.userIcon)
        localStorage.setItem('mobNo', data.userInfo.userPhone)
        sessionStorage.setItem('level2', '民事')
        var cookie_val = getCookie("token");
        if (cookie_val == "undefined") {
          that.openFullScreen();
          setTimeout(() => {
            this.isError = true;
            this.error = "用户名或密码不正确";
          }, 2000);
        } else {
          localStorage.setItem('isLoginEnterDesktop', 1);
        }
      },
      initWebSocket() { //初始化weosocket
        let that = this
        const h = this.$createElement;
        var userId = localStorage.getItem('userId')

        const wsuri = "wss://v.lawbal.com/lvbao/webSocket/" + userId + 'C';
        // const wsuri = "wss://v.lawbal.com/lvbao/webSocket/" + userId+'C';
        this.websock = new WebSocket(wsuri);
        this.websock.onopen = this.websocketonopen();
        //				this.websock.onerror = this.websocketonerror();　　　


        this.websock.onmessage = function (res) {
          let data = JSON.parse(res.data)
          console.log(data);
        }

        //				this.websock.onclose = this.websocketclose();　　　　
      },
      websocketonopen() {
        console.log("WebSocket连接成功");
      },
      websocketonerror(e) { //错误　　　
        console.log("WebSocket连接发生错误");
      },
      websocketsend(agentData) { //数据发送 　　　　
        this.websock.send(agentData);
      },
      websocketclose(e) { //关闭 　　　　　　
        // console.log("connection closed (" + e.code + ")");
      },
      beforeunloadHandler(e){

      },
      /**
       * 获取最近会话列表
       */
      getRecentSession() {
        // alert('获取')
        // debugger
        let that = this;
        webim.getRecentContactList(
          this.recentSessionReq,
          function (resp) {
            //成功
            that.recentSessionList = resp.SessionItem;

            console.log(that.recentSessionList)

            that.$nextTick(function () {
              that.unreadCount = 0
              for (var i = 0; i < resp.SessionItem.length; i++) {
                that.unreadCount = that.unreadCount + that.recentSessionList[i].UnreadMsgCount
              }
              // that.$emit('count', that.unreadCount)
              that.$nextTick(function () {
                getApi("/message/webSocket", {
                  userId: localStorage.getItem("userId"),
                  type: 7,
                  count: that.unreadCount
                }, function (data) {


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

            })
            that.setUnreadNum();
          },
          function (err) {
            //失败
            that.getRecentSession();
          }
        )
      },

      /**
       * 设置未读数量
       */
      setUnreadNum() {
        //获取所有聊天会话
        let that = this
        let unreadNumArray = JSON.parse(localStorage.getItem('unreadNum'));
        for (let index1 in this.recentSessionList) {
          let item = this.recentSessionList[index1];
          if (unreadNumArray) {
            for (let index in unreadNumArray) {
              let unread = unreadNumArray[index];

              if (unread.fromUid == (item.Type == 1 ? item.To_Account : item.ToAccount)) {
                item.UnreadMsgCount = unread.unread;
                // that.unreadCount=that.unreadCount+unread.unread
              }
            }
          }

        }
        // alert(that.unreadCount)
      },

      getNews() {
        let that = this
        getApi("/system/noticeInfo/msg/count", {
          userId: localStorage.getItem("userId")
        }, function (data) {
          that.noticeCount = data.data.noticeCount
          that.scheduleCount = data.data.scheduleCount
          that.mailCount = data.data.mailCount
          if (data.data.noticeInfo != null) {
            that.info1 = data.data.noticeInfo
          }
          if (data.data.mailInfo != null) {
            that.info2 = data.data.mailInfo
          }
          if (data.data.scheduleInfo != null) {
            that.info3 = data.data.scheduleInfo
          }

        }, function (data) {
        });
      },
      //用户签名
      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.modifyPersonData();
              that.getRecentSession();
              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));
              that.getgruplist()
            },
            function (err) {

              getMessage('网络错误 请稍后重试', 'error')

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

      },
      /**
       * 修改个人资料
       */
      modifyPersonData() {
        let userId = localStorage.getItem('userId');
        let userName = localStorage.getItem('userName');
        let photo = localStorage.getItem('photo') == 'null' ? '' : localStorage.getItem('photo');
        webim.setProfilePortrait({
          "From_Account": userId,
          "ProfileItem": [{
            "Tag": "Tag_Profile_IM_AllowType", //添加好友验证方式
            "Value": 'AllowType_Type_AllowAny' //允许任何人添加自己为好友
          }, {
            "Tag": "Tag_Profile_IM_Nick", //昵称
            "Value": userName
          }, {
            "Tag": "Tag_Profile_IM_Image", //头像
            "Value": photo
          }]
        })
      },

//      ...mapActions(['setMessages', 'setSessions', 'setMsgMap']),
      onConnNotify(resp) {
        var info;
        switch (resp.ErrorCode) {
          case webim.CONNECTION_STATUS.ON:
            webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
            break;
          case webim.CONNECTION_STATUS.OFF:
            info = '连接已断开，无法收到新消息，请检查下你的网络是否正常: ' + resp.ErrorInfo;
            webim.Log.warn(info);
            break;
          case webim.CONNECTION_STATUS.RECONNECT:
            info = '连接状态恢复正常: ' + resp.ErrorInfo;
            webim.Log.warn(info);
            break;
          default:
            webim.Log.error('未知连接状态: =' + resp.ErrorInfo);
            break;
        }

      },

      /**
       * 收到新消息回调
       */
      onMsgNotify(newMsgList) {
        console.log(newMsgList)
        if (localStorage.getItem('chatopid') == newMsgList[0].fromAccount) {
          this.readyidu(newMsgList[0].fromAccount)
        }
        let that = this;
        that.getRecentSession(); //获取最近会话
        var msgList = [];
        var sess, newMsg;
        var selToID, selType, selSess, fromAccountName, fromAccountImage;
        var dateStart, dateEnd;
        let unreadArray = JSON.parse(localStorage.getItem('unreadNum'));
        if (!unreadArray) {
          unreadArray = new Array();
        }
        for (var j in newMsgList) { //遍历新消息
          newMsg = newMsgList[j];
          let selSess = newMsg.getSession();
          // 消息已读上报， 以及设置会话自动已读标记
          webim.setAutoRead(selSess, true, true);
          var self, isGroup;
          //群组
          var pattern = /^[0-9]*$/;
          if (!pattern.test(newMsg.sess.id())) {
            if (newMsg.fromAccount == localStorage.getItem("userId")) { //为当前聊天对象的消息
              self = true
            } else {
              self = false
            }
            isGroup = true;
          } else {
            if (newMsg.fromAccount == newMsg.sess.id()) { //为当前聊天对象的消息
              self = false
            } else {
              self = true
            }
            isGroup = false;
          }

          /**
           * 设置未读消息的数量
           */
          let toUid = isGroup ? newMsg.sess.id() : localStorage.getItem('userId');


          let unreadObj = {
            fromUid: isGroup ? newMsg.sess.id() : newMsg.fromAccount, //发消息的好友id或群id
            fromId: newMsg.fromAccount, //单聊：发消息的好友id     群聊：发消息的群里的成员id
            toId: toUid,
            unread: 0
          };
          let isHave = false;
          for (let index in unreadArray) {
            let unread = unreadArray[index];
            if (unread.fromId == newMsg.fromAccount && unread.toId == toUid) {
              isHave = true;
              unreadObj.unread = unread.unread;
              unreadObj.unread++; //未读数量加1
              unreadArray.splice(index, 1);
            }
          }
          if (!isHave) {
            unreadObj.unread++;
          }
          unreadArray.push(unreadObj);
          isHave = false;
          localStorage.setItem('unreadNum', JSON.stringify(unreadArray));

          //因为新消息的监听有时监听不到 所以自己发的新消息的新增 放在发送消息后 这里不做处理
          if (self)
            return;
          //消息类型  TIMTextElem  TIMFileElem
          let type = newMsg.elems[0].type;
          let url, content;
          if (type == 'TIMTextElem') {
            //文本消息内容
            content = newMsg.elems[0].content.text;
          } else if (type == 'TIMFileElem') {
            //文件消息
            content = newMsg.elems[0].content.name;
            url = newMsg.elems[0].content.downUrl;
          }
          var friend = that.infoMap[newMsg.fromAccount];
          if (friend != undefined) {
            fromAccountName = friend.name;
            fromAccountImage = friend.image;
          }
          //组装后的消息
          let message = {
            type: type == 'TIMTextElem' && !!content ? 1 : 2,
            content: !!content ? content : null,
            url: url,
            self: self,
            time: new Date(),
            fromAccountName: fromAccountName,
            fromAccountImage: fromAccountImage,
            isGroup: isGroup
          };
          if (localStorage.getItem('chatopid') == newMsgList[0].fromAccount) {
            that.messages.push(message);
            //					that.messages.push(newMsgList[j]);
            that.messagesList = that.messages

          }


        }
        //更新好友的未读
        if (!self) {
          for (var i in that.sessions) {
            var sessionTemp = that.sessions[i];
            if (sessionTemp.toUid == newMsg.fromAccount) {
              let unread = sessionTemp.unread + 1
//              that.setSessions(that.sessions)
            }
          }
        }
        setTimeout(function () {
          that.$refs.chatRoomView.scrollTo();
        }, 300);

      },
      getFired() {
        let that = this
        getApi("txCloud/friend/list", {
          userId: localStorage.getItem("userId"),
          page: 1,
          limit: 15
        }, function (data) {
          that.list = data.friendList;
          //		fun(list)
          //存放好友信息的map  头像和名称 用于
          var infoMap = {};
          var pattern = /^[0-9]*$/;
          //					for(let i in list) {
          //						var friend = list[i];
          //						let toUid = friend.toUid; //好友id
          //						if(pattern.test(toUid)) {
          //							let image = friend.image; //好友头像
          //							let name = friend.name; //好友名称
          //							infoMap[toUid] = {
          //								name: name,
          //								image: image
          //							}
          //						}
          //					}

        }, function (data) {
        });
      },
      //获取消息中的好友列表
      getFiredList() {
        let that = this
        getApi("/txCloud/friend/msg/list", {
          userId: localStorage.getItem("userId"),
          page: '1',
          limit: 15
        }, function (data) {
          that.userbiao = data.list
          for (var i = 0; i < data.list.length; i++) {
            for (var j = 0; j < that.letters.length; j++) {
              if (data.list[i].initials === that.letters[j]) {
                if (that.letter.indexOf(that.letters[j]) == -1) {
                  that.letter.push(that.letters[j])
                }

              }
            }

          }
        }, function (data) {
        });
      },
      gernerateId(index) {
        return "div" + index
      },
      closeDialog(e) {
        this.dialogVisible = false
        // alert(this.dialogVisible)
        this.$store.commit('newDialogVisible', false)
      },
      mousedown(event) {

        let nowHight = 0;
        let nowWidth = 0;

        this.selectElement = document.getElementById('wechat')
        var div1 = this.selectElement
        this.selectElement.style.cursor = 'move'
        this.isDowm = true
        var distanceX = event.clientX - this.selectElement.offsetLeft
        var distanceY = event.clientY - this.selectElement.offsetTop

        //双击头部效果
        this.selectElement.ondblclick = (e) => {
          if (!this.isFullScreen) {

            nowHight = this.selectElement.clientHeight;
            nowWidth = this.selectElement.clientWidth;
            this.nowMarginTop = this.selectElement.style.marginTop;
            this.selectElement.style.left = 0;
            this.selectElement.style.top = 0;
            this.selectElement.style.height = "100VH";
            this.selectElement.style.width = "100VW";
            this.selectElement.style.marginTop = 0;
            this.isFullScreen = true;
            this.selectElement.style.cursor = 'initial';
            this.selectElement.onmousedown = null;
          } else {
            this.selectElement.style.height = "80%";
            this.selectElement.style.width = '60%';
            this.selectElement.style.left = "20%";
            this.selectElement.style.top = "10%";
            this.selectElement.style.marginTop = this.nowMarginTop;
            this.isFullScreen = false;
            this.selectElement.style.cursor = 'move';
            this.selectElement.onmousedown = moveDown;
          }
        }

        document.onmousemove = function (ev) {
          var oevent = ev || event
          div1.style.left = oevent.clientX - distanceX + 'px'
          div1.style.top = oevent.clientY - distanceY + 'px'
        }
        document.onmouseup = function () {
          document.onmousemove = null
          document.onmouseup = null
          div1.style.cursor = 'default'
        }
      },
      //选择工具
      selectSet(index) {
        this.isSet = index

      },
      selecticon(index) {
        this.isIcon = index
        if (index != 1) {
          this.chat = 0
        }

      },

      isSmall() {
        this.$emit('isSmall', true)
      },
//      ...mapActions(['selectSession', 'setMessages', 'setMsgMap', 'setPrePageInfo']),
      /**
       * 选择某一个好友
       */
      chooseFriend(val) {
        if (this.isIcon == 4) {
          this.initDemoApp(val.GroupId, val.index, val);
        } else {
          this.initDemoApp(val.item.toUid, val.item.index, val.item);
        }
      },
      //标记已读
      readyidu(toUid){
        // debugger
        let that = this;
        postApi("/chat/chatinfo/modify/readFlag", {
          msgType: 1,
          userId: localStorage.getItem("userId"),
          toUid: toUid,
          readFlag: true
        }, function (data) {
          // getMessage('标记已读', 'success')
          // that.getFiredList()
          that.getserverChatRecord(1);
        }, function (data) {
          getMessage(data.msg, 'error')
        });

      },

      /**
       * 切换会话时触发
       */
      initDemoApp(toUid, index, item) {
        console.log(item)
        localStorage.setItem('chatopid', toUid)
        localStorage.setItem('groupId', toUid)
        // 	console.log(localStorage.getItem('groupId'))
        // sessionStorage.setItem('groupId',toUid)
        this.chat = 1;//显示聊天室
        // 				let message;
        // 				message = {
        // 					flag: 1,
        // 				}
        // 				window.opener.postMessage(message);
        //				this.isShowMore = false;
        let chatType; //聊天类型    1：单聊      2：群聊
        if (this.isIcon == 1 || this.isIcon == 3) { //会话列表
          chatType = item.Type;
          this.chatName = item.Type == 1 ? item.C2cNick : item.GroupNick;
        } else if (this.isIcon == 2) { //好友列表
          chatType = '1';

          this.chatName = item.name;
        } else { //群列表

          chatType = '2';
          this.chatName = item.Name;
        }
        this.checkedChatObj = {
          toUid: toUid, //好友id
          msgType: chatType //聊天类型
        }
        if (chatType == '1') {
          this.readyidu(toUid)
        }

        let unreadNumArray = JSON.parse(localStorage.getItem('unreadNum'));
        if (unreadNumArray) {
          for (let index1 in unreadNumArray) {
            let index2 = parseInt(index1);
            if (unreadNumArray[index2].fromUid == toUid) {
              unreadNumArray.splice(index2, 1);
              localStorage.setItem('unreadNum', JSON.stringify(unreadNumArray));
            }
          }
        }
        let selType = item.Type == 1 ? 'C2C' : 'GROUP';
        webim.MsgStore.delSessByTypeId(selType, toUid);
        this.getRecentSession(); //todo     用设置未读数量的方式不会刷新页面的未读数量
        let that = this;
        that.isSet = index
//        that.selectSession(toUid);
        that.selToID = toUid;
        var pattern = /^[0-9]*$/;
        that.chatType = chatType;
        setTimeout(function () {
          that.$refs.chatRoomView.chatScrollHeight = 100;
          that.getserverChatRecord(1);
        }, 500);


      },

      /**
       * 获取我们后台数据库的聊天记录
       *
       * page：页码
       */
      getserverChatRecord(page) {
        let that = this;
        this.getChatInfoReq.page = page;
        this.getChatInfoReq.chatFlag = this.chatType == 1 ? 1 : 2; //1.单聊 2.群聊【必传】
        this.getChatInfoReq.friendId = this.selToID; //好友id或群组id【必传】
        getApi('/chat/chatinfo/msg/list',
          this.getChatInfoReq,
          function (data) {
            // debugger
            console.log(data)
            //成功
            let messageList = [];
            if ((page > 1 && data.list.length == 0) || (page == 1 && data.list.length < 15)) {
              that.isShowMore = false;
            } else {
              that.isShowMore = true;
            }

            //组装后的消息
            for (let msg of data.list.sort(that.compareInitials('createTime'))) {
              let fileType; //文件类型，后缀名
              if (msg.msgType == '2') { //文件类型
                if (!!msg.content && msg.content.indexOf('.') != -1) {
                  let index = msg.content.lastIndexOf(".");
                  fileType = msg.content.substring(index + 1, msg.content.length);
                }
              }
              let message = {
                type: msg.msgType, //发送消息的类型
                content: msg.content, //发送消息的内容
                url: msg.fileUrl, //发送的文件url
                size: msg.fileSize, //发送的文件大小
                fileType: fileType,
                fileId: msg.fileId,
                sender: msg.sender,
                socialFileId: msg.socialFileId,
                chatId: msg.chatId,
                readFlag: msg.readFlag,//已读未读
                self: that.loginInfo.identifier == msg.sender ? true : false, //是否为自己发送的消息
                time: msg.createTime, //发送消息的时间
                fromAccountName: msg.senderName, //发送消息的用户昵称
                fromAccountImage: msg.senderHeadUrl, //发送消息的用户头像
                isGroup: msg.chatFlag == 1 ? true : false, //是否是群消息
              };
              messageList.push(message);
            }
            if (page > 1) { //获取第一页之后的聊天记录需要拼接之前的
              messageList = messageList.concat(that.messages);
            }
            that.messagesList = messageList
          },
          function (data) {
            //失败
            getMessage('获取聊天记录失败', 'error')
          }
        )
      },

      /**
       * 获取更多聊天记录
       */
      getMoreChatRecord() {
        let page = ++this.getChatInfoReq.page;
        this.getserverChatRecord(page);
      },

      /**
       * 根据列表的某一个属性排序返回排序后的集合
       */
      compareInitials(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          if (/^\d/.test(value1) ^ /^\D/.test(value2)) return value1 > value2 ? 1 : (value1 == value2 ? 0 : -1);
          return value1 > value2 ? -1 : (value1 == value2 ? 0 : 1);
        }
      },

      //获取最近的好友聊天记录
      getLastC2CHistoryMsgs(cbOk, cbError) {

        let that = this;
        if (that.selToID == undefined)
          return;
        var selType = webim.SESSION_TYPE.C2C
        var lastMsgTime = 0; //第一次拉取好友历史消息时，必须传0
        var msgKey = '';
        var account = '';
        account += that.selToID;
        var options = {
          'Peer_Account': account, //好友帐号
          'MaxCnt': 15, //拉取消息条数
          'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
          'MsgKey': msgKey
        };
        var selSess = null;
        webim.MsgStore.delSessByTypeId(selType, account);

        webim.getC2CHistoryMsgs(
          options,
          function (resp) {
            var complete = resp.Complete; //是否还有历史消息可以拉取，1-表示没有，0-表示有
            //						var getPrePageC2CHistroyMsgInfoMap = {}; //保留下一次拉取好友历史消息的信息
            if (resp.MsgList.length == 0) {
              var messageList = []
              that.messagesList = messageList
//              that.setMessages(messageList);
              webim.Log.warn("没有历史消息了:data=" + JSON.stringify(options));
              return;
            }
            that.prePageInfo[account] = { //保留服务器返回的最近消息时间和消息Key,用于下次向前拉取历史消息
              'LastMsgTime': resp.LastMsgTime,
              'MsgKey': resp.MsgKey
            };
//            that.setPrePageInfo(that.prePageInfo);
            if (cbOk)
              cbOk(resp.MsgList);
          },
          cbError
        );
      },
      getHistoryMsgCallback(msgList, prepage) {

        // alert('执行了拉取聊天记录')
        let that = this;
        var msg;
        var pattern = /^[0-9]*$/;
        prepage = prepage || false;
        var selSess = null;

        //如果是加载前几页的消息，消息体需要prepend，所以先倒排一下
        if (prepage) {
          msgList.reverse();
        }
        //组装后的消息列表
        var messageList = [];
        //需要组装的消息列表
        for (var j in msgList) { //遍历新消息
          msg = msgList[j];
          let self, fromAccountNick, fromAccountImage, fromAccountName, isGroup;

          //群组
          if (!pattern.test(that.selToID)) {
            if (msg.fromAccount == localStorage.getItem("userId")) { //为当前聊天对象的消息
              self = true
            } else {
              self = false
            }
            isGroup = true;
          } else {
            if (msg.fromAccount == that.selToID) { //为当前聊天对象的消息
              self = false
            } else {
              self = true
            }
            isGroup = false;
          }
          var friend = that.infoMap[msg.fromAccount];
          if (friend != undefined) {
            fromAccountName = friend.name;
            fromAccountImage = friend.image;
          }

          selSess = msg.getSession();
          var time = msg.time;
          //同一时间发送消息的内容  有可能是多条
          var messages = msg.elems;
          for (var k in messages) {
            //需要组装的消息
            var messageNeed = messages[k];
            //消息类型  TIMTextElem  TIMFileElem
            let type = messageNeed.type;
            let url;
            let content;
            if (type == 'TIMTextElem') {
              //文本消息内容
              content = messageNeed.content.text;
            } else if (type == 'TIMFileElem') {
              //文件消息
              content = messageNeed.content.name;
              url = messageNeed.content.downUrl;
            }

            //组装后的消息
            let message = {
              type: type, //发送消息的类型
              content: content, //发送消息的内容
              url: url, //发送的文件url
              self: self, //是否为自己发送的消息
              time: time, //发送消息的时间
              fromAccountName: fromAccountName, //发送消息的用户昵称
              fromAccountImage: fromAccountImage, //发送消息的用户头像
              isGroup: isGroup, //是否是群消息
            };
            if (message.content != '') {
              messageList.push(message);
            }

          }
        }
        //切换群组
        if (!pattern.test(that.selToID)) {
          if (that.msgMap[that.selToID] == undefined) {
            that.msgMap = {};
            that.msgMap[that.selToID] = messageList;
          } else {
            for (var prop in that.msgMap) {
              if (that.msgMap.hasOwnProperty(prop)) {
                var msgOldList = that.msgMap[prop];
                msgOldList.push(messageList);
                that.msgMap[prop] = msgOldList;
                break;
              }
            }
          }
//          that.setMsgMap(that.msgMap);
        }
        //消息已读上报，并将当前会话的消息设置成自动已读
        webim.setAutoRead(selSess, true, true);
        that.messagesList = messageList;
      },
      getLastGroupHistoryMsgs(cbOk, cbError) {
        let that = this;

        if (that.selToID == undefined)
          return;

        var selType = webim.SESSION_TYPE.GROUP
        var selToID = '' + that.selToID;
        this.getGroupInfo(selToID, function (resp) {
          //拉取最新的群历史消息
          var options = {
            'GroupId': selToID,
            'ReqMsgSeq': resp.GroupInfo[0].NextMsgSeq - 1,
            'ReqMsgNumber': 10
          };
          if (options.ReqMsgSeq == null || options.ReqMsgSeq == undefined || options.ReqMsgSeq <= 0) {
            webim.Log.warn("该群还没有历史消息:options=" + JSON.stringify(options));
            return;
          }
          webim.syncGroupMsgs(
            options,
            function (msgList) {
              if (msgList.length == 0) {
                that.messagesList = that.msgMap[that.selToID]
//                that.setMessages(that.msgMap[that.selToID]);
                webim.Log.error("该群没有历史消息了:options=" + JSON.stringify(options));
                return;
              }
              //			                that.getPrePageGroupHistroyMsgInfoMap[selToID] = {
              //			                	"ReqMsgSeq": msgList[msgList.length - 1].MsgSeq - 1
              //			                };
              if (cbOk)
                cbOk(msgList);
            },
            function (err) {
              //							alert(err.ErrorInfo);
            }
          );
        });
      },
      //读取群组基本资料-高级接口
      getGroupInfo(group_id, cbOK, cbErr) {
        var options = {
          'GroupIdList': [
            group_id
          ],
          'GroupBaseInfoFilter': [
            'Type',
            'Name',
            'Introduction',
            'Notification',
            'FaceUrl',
            'CreateTime',
            'Owner_Account',
            'LastInfoTime',
            'LastMsgTime',
            'NextMsgSeq',
            'MemberNum',
            'MaxMemberNum',
            'ApplyJoinOption',
            'ShutUpAllMember'
          ],
          'MemberInfoFilter': [
            'Account',
            'Role',
            'JoinTime',
            'LastSendMsgTime',
            'ShutUpUntil'
          ]
        };
        webim.getGroupInfo(
          options,
          function (resp) {
            if (resp.GroupInfo[0].ShutUpAllMember == 'On') {
              alert('该群组已开启全局禁言');
            }
            if (cbOK) {
              cbOK(resp);
            }
          },
          function (err) {
            alert(err.ErrorInfo);
          }
        );
      },
      //向上翻页，获取更早的好友历史消息
      getPrePageC2CHistoryMsgs(cbOk, cbError) {
        let that = this;
        var tempInfo = that.prePageInfo[that.selToID]; //获取下一次拉取的c2c消息时间和消息Key
        var lastMsgTime;
        var msgKey;
        if (tempInfo) {
          lastMsgTime = tempInfo.LastMsgTime;
          msgKey = tempInfo.MsgKey;
        } else {
          alert('获取下一次拉取的c2c消息时间和消息Key为空');
          return;
        }
        var options = {
          'Peer_Account': that.selToID, //好友帐号
          'MaxCnt': reqMsgCount, //拉取消息条数
          'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
          'MsgKey': msgKey
        };
        webim.getC2CHistoryMsgs(
          options,
          function (resp) {
            var complete = resp.Complete; //是否还有历史消息可以拉取，1-表示没有，0-表示有
            if (resp.MsgList.length == 0) {
              webim.Log.warn("没有历史消息了:data=" + JSON.stringify(options));
              return;
            }
            that.prePageInfo[selToID] = { //保留服务器返回的最近消息时间和消息Key,用于下次向前拉取历史消息
              'LastMsgTime': resp.LastMsgTime,
              'MsgKey': resp.MsgKey
            };
//            that.setPrePageInfo(that.prePageInfo);
            if (cbOk) {
              cbOk(resp.MsgList);
            } else {
              that.getHistoryMsgCallback(resp.MsgList, true);
            }
          },
          cbError
        );
      },
      close() { //关闭窗口
        // window.close();
        if (navigator.userAgent.indexOf("MSIE") > 0) {
          if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
            window.opener = null;
            window.close();
          } else {
            window.open('', '_top');
            window.top.close();
          }
        } else if (navigator.userAgent.indexOf("Firefox") > 0) {
          window.location.href = 'about:blank '; //火狐默认状态非window.open的页面window.close是无效的
          //window.history.go(-2);
          window.close();
        } else {
          window.opener = null;
          window.open('', '_self', '');
          window.close();
        }


      },

      /**
       * 格式化毫秒时间戳为yyyy-mm-dd hh:mm:ss
       * @param {Object} timestamp
       */
      timestampToTime(timestamp) {
        let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        let HH = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
        let MM = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        return HH + ':' + MM;
      },
      //清空好友列表
      clearAll() {
        this.isAdd = false
        this.$refs.addfriend.clearList()

      },
      //清空添加群组列表
      clearAlls() {
        this.isAdds = false
        // this.$refs.addfriend.clearList()

      },
      //添加好友刷新操作
      isShua() {
        if (this.isIcon == 2) {
          this.$refs.friendlist.getFiredList()
        }
        this.isAdd = false
        this.$refs.addfriend.clearList()
      },
      //重新获取群组
      getNewGroup(){
        this.selecticon(4);
        this.$refs.groupslist.getJoinedGroupList()
      },
      //添加群组刷新操作
      isShuas() {
        if (this.isIcon == 4) {
          this.$refs.groupslist.getJoinedGroupList()
        }
        this.isAdds = false
        this.$refs.addgroup.clearList()
      },
      searchFrienfd() {
        this.isIcon = 2
        this.$refs.friendlist.getFiredList(this.input23)
      },
      // 删除会话列表
      deleteSes(item) {
        console.log(item)
        let a = ''
        if (item.Type == 1) {
          a = item.To_Account
        } else {
          a = item.ToAccount
        }
        let that = this
        webim.deleteChat({
          chatType: item.Type,
          To_Account: a
        }, function (val) {
          console.log(val + '1')
          that.getRecentSession()
        }, function (val) {
          console.log(val + '2')
        })
      },
      goJumpPage() {
        let that = this;
        // window.resizeTo(70, 70);
        // window.moveTo(0, that.windowHeight);
        getApi("/message/webSocket", {
          userId: localStorage.getItem("userId"),
          type: 6
        }, function (data) {


        }, function (data) {
        });
      },
      deleteEnter(index) {
        this.deleteindex = index
      },
      deleteLeave() {
        this.deleteindex = '-1'
      },
      //发送消息刷新
      isShualeft(){
        this.getRecentSession()
      },
      //加好友//加群聊
      handleCommand(command) {
        if (command == 'isAddf') {
          this.isAdd = true
        } else if (command == 'isAddg') {
          this.isAdds = true
        } else if (command == 'isAddy') {
          this.goJumpPage()
        }

      },
      //添加好友
      addFds(){
        // debugger
        let that = this
        let toid = localStorage.getItem('chatopid');
        if (that.isIcon != 4) {
          let friends = [localStorage.getItem('chatopid')]
          postApi("txCloud/friend/add", {
            fromUid: localStorage.getItem("userId"),
            toUidList: friends
          }, function (data) {
            console.log(data)
            //添加成功获取好友信息
            that.getFiredaa(toid)
          }, function (data) {
          });

        } else {
          that.getGoupaa(toid)
        }


      },
      //获取单个好友信息
      getFiredaa(toUid) {
        let that = this;
        getApi("/txCloud/friend/msg/list", {
          userId: localStorage.getItem("userId"),
          toUid: toUid
        }, function (data) {
          //开启聊天
          that.initDemoApp(toUid, 0, data.list[0])
        }, function (data) {

        });
      },
      //获取我的群组列表
      getgruplist(){
        let that = this;
        webim.getJoinedGroupListHigh(that.myGroupListReq,
          function (resp) {
            //成功
            that.myGroupLists = resp.GroupIdList;
            console.log('我的群组列表')
            console.log(that.myGroupLists)

            //获取父级页面localStorage聊天id传值
            if (localStorage.getItem('chatopid') && localStorage.getItem('chatopid') != 0) {

              that.chat = 1
              if (localStorage.getItem('chatopid') && localStorage.getItem('chatopid').indexOf('@TGS') > -1) {
                that.isIcon = 4//群组
              } else {
                that.isIcon = 2//单人
              }

              //添加好友并开启聊天
              that.addFds()
            } else {
              that.chat = 0
            }
          },
          function (err) {
            //获取群组失败

            console.log(err)


          })
      },
      //获取单个群组信息 循环比较群组id 获取腾讯云群组信息
      getGoupaa(toUid){
        let that = this
        for (let i = 0; i < that.myGroupLists.length; i++) {
          if (that.myGroupLists[i].GroupId == toUid) {
            //开启聊天窗口 initDemoApp(群组ID,所在下标,群组详细信息)
            that.initDemoApp(toUid, i, that.myGroupLists[i])
          }
        }
      },
      //字符串转换为表情
      replace_em(str){
        //  debugger
        str = str.replace("\"", "").replace("\"", "")
        str = str.replace(/\"/g, "")
        str = str.replace(/\&quot;/g, '"')
        str = str.replace(/\&lt;/g, '<');
        str = str.replace(/\&gt;/g, '>');
        str = str.replace(/<p>(.*?)<\/p>/g, "$1");
        str = str.replace("<br>", "");
        return str;

        console.log(str)
      },
      getNewmessage(){
        this.getserverChatRecord(1);
      },
//改变主题
      changeColor(color){
        let that = this;
        // alert('aaa')
        console.log(color)
        $('.allLei').css('background', '#' + color)
      }


    }
  }
</script>


<style scoped>
  @import "../wechat/wechat.css";

  .wechat {
    float: left;
  }

  .adds {
    width: 30px;
    height: 30px;
    background: #f3f3f3;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
    margin-left: 10px;

  }

  .adds > img {
    width: 100%;
    height: 100%;
  }

  .wechat-search {
    display: flex;
    padding-left: 3%;
    padding-right: 3%
  }

  .allLei {
    text-align: center;
    width: 65px;
    padding-top: 15px;
  }

  .allLei li {
    list-style: none;
  }

  .leftChat li {
    display: flex;
    padding: 10px;
    border-bottom: 1px solid rgb(242, 242, 242);
    cursor: pointer;
  }

  .leftChat li:hover {
    background: #f9f9ff
  }

  .sanjiao {
    width: 0;
    height: 0;
    border-right: 10px solid transparent;
    border-left: 10px solid transparent;
    border-bottom: 10px solid #4C4C4C;
    position: absolute;
    left: 38px;
    top: -8px;
    z-index: 99999;

  }

  .xiaoxilist {
    height: 100%;
    overflow: auto;
    padding-bottom: 100px;
  }

  /*定义滚动条轨道*/

  .xiaoxilist::-webkit-scrollbar-track {
    border-radius: 0;
    background: 0 0;
    -webkit-box-shadow: inset 0 0 5px transparent
  }

  /*定义滚动条高宽及背景*/

  .xiaoxilist::-webkit-scrollbar {
    width: 10px;
    height: 5px
  }

  /*定义滚动条*/

  .xiaoxilist::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: hsla(0, 0%, 100%, .1);
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, .3)
  }
</style>
<style>
  #wechat .el-main {
    padding: 0 !important;
    height: 100%;
  }

  #wechat .el-dialog {
    overflow: hidden !important;
  }

  #wechat .el-badge {
    margin-top: 10px;
    padding: 0;
  }

  .wechat-inner .el-input__inner {
    outline: none !important;
    background-color: #f9f9f9;
    height: 30px;
    line-height: 30px;
    width: 80%;
  }

  .wechat-inner .el-input__icon {
    line-height: 30px;
    height: 30px;
  }

  .wechat-inner .el-input {
    flex: 1;
    margin: 0 10px 0 5px;
  }

  .addDialig {
    padding-top: 94px;
    height: 300px;
    padding-bottom: 45px;
    background: #F9F9F9 !important;
  }

  .addDialig .el-dialog__header {
    margin-top: -94px;
    background: #FFFFFF !important;
  }

  .addDialig .el-dialog__body {
    height: 100%;
    padding: 20px !important;

  }

  .addslist {
    background-color: #4C4C4C !important;
    height: 100%;
    border-radius: 5px;
    padding: 5px 0;
    position: relative;
  }

  .el-dropdown-menu {
    overflow: visible !important;
    padding: 0;
    text-align: center;
  }

  .addslist .el-dropdown-menu__item {
    color: #ffffff !important;
    line-height: 30px !important;
  }

  .addslist.popper__arrow::after {
    border-bottom-color: #4C4C4C !important;
  }

  .el-dropdown-menu__item:not(.is-disabled):hover {

    background-color: #cccccc !important;
    color: #333333 !important;

  }
</style>
