<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs='crumbs'></bread-crumb>
    </div>
    <div class="app-container"  
      v-loading="loading"
      :element-loading-text="loadingtext">

      <div class="customer_plate white-bg">
        <div class="aside">
          <div class="customer_search clearfix">
            <div class="super_searchbox">
              <span class="search_icon"></span>
              <input type="text" class="cus_search_input" v-model="searchname" placeholder="请输入客户名称">
            </div>
          </div>
          <div class="client_list_box">
            <div class="client_list">
              <ul class="users-list">
                <li v-for="(customer, key) in customersMap" v-show="searchname == '' || (customer.name.indexOf(searchname)>=0)" :class="thisCustomer && customer.user_id==thisCustomer.user_id?'Active':''" :key="key" :id="'sessDiv_User_'+customer.user_id" class="item" :data-username="customer.name" @click="chooseThisUser(customer)">
                  <span :id="'badgeDiv_User_'+customer.user_id" class="circle-count" style="" v-show="customer.unread_msg_count"><i class="count">{{customer.unread_msg_count}}</i></span>
                  <figure :id="'faceImg_User_'+customer.user_id" class="session-pic"><img :src="customer.avatar"></figure>
                  <h3 :id="'nameDiv_User_'+customer.user_id" class="nick">{{customer.name}}</h3>
                  <!-- <span class="square-close" title="退出接待" :data-toid="'User_'+customer.user_id">×</span> -->
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="left_content">
          <div class="conversation-admin">
            <span class="nickname">
              <span></span>
            </span>
          </div>
          <div class="message-list-wrap">
            <div class="message-list-item">
              <ul class="message-list">
              
                <li v-for="(messageitem, key) in messageBox" :key="key" :id="'id_'+messageitem.id" class="message-item clearfix">
                    <div class="time"><span v-html="messageitem.time"></span></div>
                    <div class="user " :class="messageitem.float">
                      <figure class="bg-pic circle-bg-pic">
                        <div class="bg-pic-content">
                          <img :src="messageitem.avatar">
                        </div>
                      </figure>
                    </div>
                    <div class="message-body " :class="messageitem.float"><div class="inner" v-html="messageitem.message"></div></div>
                </li>

              </ul>
            </div>
            <div class="no_session">
              <span class="no_session_pic"></span>
              <p class="no_session_txt">没有选中会话哦！</p>
            </div>
          </div>
          <div class="send_box" v-loading="loadingbox" :element-loading-text="loadingboxtext">
            <div class="inputer_actions">
              <!-- <div class="face">
                <span class="face_icon" @click="showEmotionDialog"></span>
              </div> -->
              <div class="picture">
                <span class="picture_icon" @click="selectPicClick"></span>
              </div>
            </div>
            <div id="wl_faces_box" class="wl_faces_box" v-bind:style="{left:'0px', display:facesBoxDisplay}">
              <div class="wl_faces_content">
                <div class="title">
                  <ul>
                    <li class="title_name">常用表情</li>
                    <li class="wl_faces_close">
                      <span @click="facesBoxDisplay='none'">&nbsp;</span>
                    </li>
                  </ul>
                </div>
                <div id="wl_faces_main" class="wl_faces_main">
                  <ul id="emotionUL">
                    <li v-for="(emotion, key) in emotionList" :key="key" @click="chooseThisFace(emotion)">
                      <img :src="emotion.src" :id="emotion.id" alt="" style="cursor:pointer;">
                    </li>
                  </ul>
                </div>
              </div>
              <div class="wlf_icon"></div>
            </div>
            <div class="inputer-area">
              <textarea
                maxlength="500" v-model="message"
                class="message-textarea transparent-txta"
                placeholder
                id="message"
              ></textarea>
            </div>
            <div class="send_box_btn">
              <button class="send_btn" id="sendMessaeg" @click="sendMessage">发送</button>
            </div>
          </div>
        </div>
      </div>

      <el-dialog title="发送图片" :visible.sync="dialogPicModal">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="选择">
            <input type="file" name="filebox" id="upd_pic" @change="fileOnChange(this)">

          </el-form-item>
          <el-form-item label="预览">
          <img :src="dialogImageUrl"  alt="" style="width:100%">
          </el-form-item>
          <el-form-item label="进度">
            <el-progress :text-inside="true" :stroke-width="18" :percentage="percentage" status="success"></el-progress>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="uploadPic">发送</el-button>
        </div>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import BreadCrumb from '../components/bread-crumb'
import {getusersig,GetAllMembers} from "@/api/kefu/tencentim";

// let webim = require('../../../static/im/sdk/sdk/webim');
import webim from 'webim-tencent'
// let webim = webimSDK.webim;
let selType =  webim.SESSION_TYPE.C2C;
let reqMsgCount = 15; //每次请求的历史消息(c2c获取群)条数
var msgList = [];
var getPrePageC2CHistroyMsgInfoMap = {};
var kgetPrePageC2CHistroyMsgInfoMap = {};

  export default {
    name: 'commentList',
    components:{
      BreadCrumb,
    },
    data(){
      return{
        crumbs: [
          { path: false, name: '客服管理' },
          { path: false, name: '咨询管理' }
        ],
        
        imloginFlag:false,
        customer_id:0,
        searchname:'',
        facesBoxDisplay:'none',
        emotionList:[],
        percentage:0,
        dialogImageUrl:'',
        form:{name:'', region:''},
        dialogPicModal:false,
        loading:false,
        loadingtext:'加载中...',
        loadingbox:true,
        loadingboxtext:'请选择用户',
        selToID:'',
        useradmin:{
          usersig: '',
          Indentifier: '',
          appIDAt3rd:'',
          IdentifierNick:'',
          HeadURL:'',
        },
        loginInfo: {
            sdkAppID: '', //用户所属应用id,必填
            appIDAt3rd: '',
            identifier: '', //当前用户ID,必须是否字符串类型，必填
            accountType: '', //用户所属应用帐号类型，必填
            userSig: '', //当前用户身份凭证，必须是字符串类型，必填
            identifierNick: '', //当前用户昵称，不用填写，登录接口会返回用户的昵称，如果没有设置，则返回用户的id
            headurl: '', //当前用户默认头像，选填，如果设置过头像，则可以通过拉取个人资料接口来得到头像信息
        },
        loginOptions:{},
        userSigFlag:false,
        userListFlag:false,
        customers:[],
        customersUnique:[],
        customersMap:{},
        thisCustomer:null,
        selSess:null,
        message:'',
        messageBox:[],
      }
    },
    methods: {
      
      bindScrollHistoryEvent(axtion){
        var msgflow = document.getElementsByClassName("message-list-item")[0];
        var _this = this;
        if (axtion=='init') {
          msgflow.onscroll = function () {
                if (msgflow.scrollTop == 0) {
                    msgflow.scrollTop = 10;
                    if (selType == webim.SESSION_TYPE.C2C) {
                        _this.getPrePageC2CHistoryMsgs();
                    } 
                }
            }
        }else {
          
              msgflow.onscroll = null;
        }
      },
      selectPicClick() {
        this.dialogPicModal = true;
      },  
      chooseThisFace(face) {
        this.message = this.message + face.id;
        this.facesBoxDisplay='none';
      },
      onProgressCallBack(loadedSize, totalSize) {
          this.percentage = (loadedSize / totalSize) * 100;
      },
      uploadPic(){
        var _this = this;
        var uploadFiles = document.getElementById('upd_pic');
        var file = uploadFiles.files[0];
        var businessType;//业务类型，1-发群图片，2-向好友发图片
        if (selType != webim.SESSION_TYPE.C2C) {//向好友发图片
          this.$message.error('不支持群聊');
          return; 
        } 
        businessType = webim.UPLOAD_PIC_BUSSINESS_TYPE.C2C_MSG;
        //封装上传图片请求
        var opt = {
            'file': file, //图片对象
            'onProgressCallBack': this.onProgressCallBack, //上传图片进度条回调函数
            //'abortButton': document.getElementById('upd_abort'), //停止上传图片按钮
            'To_Account': this.selToID, //接收者
            'businessType': businessType//业务类型
        };
        //上传图片
        webim.uploadPic(opt,
            function (resp) {
                //上传成功发送图片
                _this.sendPic(resp, file.name);
                
            },
            function (err) {
                alert(err.ErrorInfo);
            }
        );
      },
      sendPic(images, imgName) {
        var _this = this;
          if (!this.selToID) {
              alert("请先选择对话用户");
              return;
          }

          if (!this.selSess) {
              this.selSess = new webim.Session(selType, this.selToID, this.selToID, this.thisCustomer.avatar, Math.round(new Date().getTime() / 1000));
          }
          var msg = new webim.Msg(this.selSess, true, -1, -1, -1, this.loginInfo.identifier, 0, this.loginInfo.identifierNick);
          var images_obj = new webim.Msg.Elem.Images(images.File_UUID);
          for (var i in images.URL_INFO) {
              var img = images.URL_INFO[i];
              var newImg;
              var type;
              switch (img.PIC_TYPE) {
                  case 1://原图
                      type = 1;//原图
                      break;
                  case 2://小图（缩略图）
                      type = 3;//小图
                      break;
                  case 4://大图
                      type = 2;//大图
                      break;
              }
              newImg = new webim.Msg.Elem.Images.Image(type, img.PIC_Size, img.PIC_Width, img.PIC_Height, img.DownUrl);
              images_obj.addImage(newImg);
          }
          msg.addImage(images_obj);
          //if(imgName){
          //    var data=imgName;//通过自定义消息中的data字段保存图片名称
          //    var custom_obj = new webim.Msg.Elem.Custom(data, '', '');
          //    msg.addCustom(custom_obj);
          //}
          //调用发送图片消息接口
          webim.sendMsg(msg, function (resp) {
              if (selType == webim.SESSION_TYPE.C2C) {//私聊时，在聊天窗口手动添加一条发的消息，群聊时，长轮询接口会返回自己发的消息
                  _this.addMsg(msg);
              }
          }, function (err) {
              alert(err.ErrorInfo);
          });
      },
      showEmotionDialog(){
        this.facesBoxDisplay = 'block';
      },
      fileOnChange(){
        var file = document.querySelector('input[name=filebox]').files[0]
        if (!window.File || !window.FileList || !window.FileReader) {
            alert("您的浏览器不支持File Api");
            return;
        }

        var fileSize = file.size;

        //先检查图片类型和大小
        if (!this.checkPic(file, fileSize)) {
            return;
        }

        var _this = this;
        //预览图片
        var reader = new FileReader();
        reader.onload = (function (file) {
            return function (e) {
              _this.dialogImageUrl = this.result;
            };
        })(file);
        //预览图片
        reader.readAsDataURL(file);
      },
      
      checkPic(obj, fileSize) {
          var picExts = 'jpg|jpeg|png|bmp|gif|webp';
          var photoExt = obj.name.substr(obj.name.lastIndexOf(".") + 1).toLowerCase();//获得文件后缀名
          var pos = picExts.indexOf(photoExt);
          if (pos < 0) {
            this.$message.error('您选中的文件不是图片，请重新选择');
              return false;
          }
          fileSize = Math.round(fileSize / 1024 * 100) / 100; //单位为KB
          if (fileSize > 30 * 1024) {
            this.$message.error('您选择的图片大小超过限制(最大为30M)，请重新选择');
              return false;
          }
          return true;
      },
      chooseThisUser(customer) {
        if(customer.user_id<=0) {
          this.$message.error('选择对象还未关联用户，无法进行对话');
          return false;
        }
        this.thisCustomer = customer;
        this.selToID = "User_" + customer.user_id;
        this.onSelSess(selType, this.selToID);
        this.loadingbox = false;
      },
      sendMessage(){
        if(this.thisCustomer == null) {
          this.$message.error('请先选择对话用户');
          return false;
        }
        var message = this.message.trim();
        var msgLen = webim.Tool.getStrBytes(message);
        if(message == '') {
          this.$message.error('不能发送空消息');
          return false;
        }
        var maxLen, errInfo;
        if (selType == webim.SESSION_TYPE.C2C) {
          maxLen = webim.MSG_MAX_LENGTH.C2C;
          errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
        } else {
          maxLen = webim.MSG_MAX_LENGTH.GROUP;
          errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)";
        }
        if (msgLen > maxLen) {
          this.$message.error(errInfo);
          return false;
        }
        this.handleMsgSend(message);

      },
      webimlogin(){
        let _this = this;
        let listeners = {
          "onConnNotify": this.onConnNotify //监听连接状态回调变化事件,必填
          ,
          "jsonpCallback": this.jsonpCallback //IE9(含)以下浏览器用到的jsonp回调函数，
          ,
          "onMsgNotify": this.onMsgNotify //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
          ,
          "onProfileSystemNotifys": this.onProfileSystemNotifys //监听资料系统（自己或好友）通知事件，选填
          ,
          "onKickedEventCall": this.onKickedEventCall //被其他登录实例踢下线
          ,
          "onC2cEventNotifys": this.onC2cEventNotifys //监听C2C系统消息通道
        };

        webim.login(this.loginInfo, listeners, this.loginOptions, 
          function(resp){
            _this.$message.success('登录成功');
            _this.imloginFlag = true;
          },
          function(err) {
            _this.$message.error('登录错误');
          }
        );
      
      },
      onConnNotify(){},
      jsonpCallback(){},
      onMsgNotify(newMsgList){
        //监听新消息事件
        var msgList = [];
        var dateStart = null;
        var dateEnd = null;

        //console.warn(newMsgList);
        var sess, newMsg, formId;
        //获取所有聊天会话
        var sessMap = webim.MsgStore.sessMap();

        for (var j in newMsgList) {//遍历新消息

            newMsg = newMsgList[j];
            formId = newMsg.getSession().id();
            if (formId.indexOf("User")<0) {
                continue;
            }else {
                // if (!this.selToID) {//没有聊天对象
                //     this.selToID = newMsg.getSession().id();
                //     selType = newMsg.getSession().type();
                //     this.selSess = newMsg.getSession();
                //     if(this.selToID in this.customersMap) {
                //       this.thisCustomer = this.customersMap[this.selToID];
                //     }
                // }
                if (newMsg.getSession().id() == this.selToID) {//为当前聊天对象的消息
                    this.addMsg(newMsg);
                }
                msgList.push(newMsg.elems[0].content.text);
            }

            
        }


        for (var i in sessMap) {
            sess = sessMap[i];
            if (this.selToID != sess.id() && sess.id() in this.customersMap) {//更新其他聊天对象的未读消息数
              var unread = sess.unread();
              if(unread>99) {
                unread = '99+';
              }
              // var custimerItem = this.customersMap[sess.id()];
              // custimerItem.unread_msg_count = unread;
              var thisdiv = document.getElementById('badgeDiv_'+ sess.id());
              thisdiv.innerHTML = '<i class="count">' + unread + '</i>';
              thisdiv.style.display = 'block';
              this.$set(this.customersMap[sess.id()], 'unread_msg_count', unread);
            }
        }
    
      },
      onProfileSystemNotifys(){},
      onKickedEventCall(){},
      onC2cEventNotifys(){},
      initUnreadMsgCount() {
          var sess;
          var sessMap = webim.MsgStore.sessMap();
          for (var i in sessMap) {
              sess = sessMap[i];
              if (this.selToID != sess.id() && sess.id() in this.customersMap) {//更新其他聊天对象的未读消息数
                var unread = sess.unread();
                if(unread>99) {
                  unread = '99+';
                }
                // var custimerItem = this.customersMap[sess.id()];
                // custimerItem.unread_msg_count = unread;
                
                var thisdiv = document.getElementById('badgeDiv_'+ sess.id());
                thisdiv.innerHTML = '<i class="count">' + unread + '</i>';
                thisdiv.style.display = 'block';
                this.$set(this.customersMap[sess.id()], 'unread_msg_count', unread);
                
                // this.$set(this.customersMap, sess.id(), custimerItem);
              }
          }
      },
      getusersig() {
        getusersig().then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg);
            return false;
          } else {
            this.useradmin = {
              usersig: response.data.data.sig,
              Indentifier: response.data.data.Indentifier,
              appIDAt3rd:response.data.data.appIDAt3rd,
              IdentifierNick:response.data.data.IdentifierNick,
              HeadURL:response.data.data.HeadURL,
            } 
          
            this.loginInfo.appIDAt3rd = this.useradmin.appIDAt3rd
            this.loginInfo.identifier = this.useradmin.Indentifier
            this.loginInfo.userSig = this.useradmin.usersig
            this.loginInfo.identifierNick = this.useradmin.IdentifierNick
            this.loginInfo.headurl = this.useradmin.HeadURL
            this.loginInfo.sdkAppID = response.data.data.sdkAppID
            this.loginInfo.accountType = response.data.data.accountType
            this.userSigFlag = true;
          }
        });
        this.bindWechatDialog = true
      },

      GetAllMembers(){
        GetAllMembers().then(response=>{
          if (response.data.state == 1) { 
            this.customers = response.data.data.members;
            for (const key in this.customers) {
              var custimerItem = this.customers[key];
              var mapKey = "User_" + custimerItem.user_id;
              if(custimerItem.user_id==0 || mapKey in this.customersMap) {
                continue;
              }
              custimerItem['sortno'] = -1;
              custimerItem['unread_msg_count'] = '';
              this.$set(this.customersMap, mapKey, custimerItem);
              this.customersUnique.push(custimerItem);
            }
            this.userListFlag = true;
          } else {

          }
        });
      },
      addMsg(msg, prepage) {
        var messageitem = {
          id:'',
          message:'',
          avatar:'',
          time:'',
          float:''
        };
        var isSelfSend, fromAccount, fromAccountNick, fromAccountImage, sessType, subType;

        //webim.SESSION_TYPE.GROUP-群聊，
        //webim.SESSION_TYPE.C2C-私聊，
        sessType = msg.getSession().type();
        isSelfSend = msg.getIsSend();//消息是否为自己发的
        fromAccount = msg.getFromAccount();
        if (!fromAccount) {
            return;
        }
        if (isSelfSend) {//如果是自己发的消息
          messageitem.avatar = this.loginInfo.headurl;
          messageitem.float = "fr";
        } else {
          messageitem.avatar = this.thisCustomer.avatar;
          messageitem.float = "fl";
        }
        messageitem.id = msg.random;
        messageitem.time = webim.Tool.formatText2Html(webim.Tool.formatTimeStamp(msg.getTime()));
        messageitem.message = this.convertMsgtoHtml(msg)
        this.messageBox.push(messageitem);

        var msgflow = document.getElementsByClassName("message-list-item")[0];
        if (prepage) {
            //300ms后,等待图片加载完，滚动条自动滚动到底部
            if (msgflow.scrollTop == 0) {
                setTimeout(function () {
                    msgflow.scrollTop = 0;
                }, 300);
            }
        } else {
            //300ms后,等待图片加载完，滚动条自动滚动到底部
            setTimeout(function () {
                msgflow.scrollTop = msgflow.scrollHeight;
            }, 300);
        }

      },
      convertMsgtoHtml(msg) {
          var html = "",
              elems, elem, type, content;
          elems = msg.getElems(); //获取消息包含的元素数组
          var count = elems.length;
          for (var i = 0; i < count; i++) {
              elem = elems[i];
              type = elem.getType();//获取元素类型
              content = elem.getContent();//获取元素对象
              switch (type) {
                  case webim.MSG_ELEMENT_TYPE.TEXT:
                      var eleHtml = this.convertTextMsgToHtml(content);
                      //转义，防XSS
                      html += webim.Tool.formatText2Html(eleHtml);
                      break;
                  case webim.MSG_ELEMENT_TYPE.FACE:
                      html += this.convertFaceMsgToHtml(content);
                      break;
                  case webim.MSG_ELEMENT_TYPE.IMAGE:
                      if (i <= count - 2) {
                          var customMsgElem = elems[i + 1];//获取保存图片名称的自定义消息elem
                          var imgName = customMsgElem.getContent().getData();//业务可以自定义保存字段，demo中采用data字段保存图片文件名
                          html += this.convertImageMsgToHtml(content, imgName);
                          i++;//下标向后移一位
                      } else {
                          html += this.convertImageMsgToHtml(content);
                      }
                      break;
                  case webim.MSG_ELEMENT_TYPE.SOUND:
                      html += this.convertSoundMsgToHtml(content);
                      break;
                  case webim.MSG_ELEMENT_TYPE.FILE:
                      html += this.convertFileMsgToHtml(content);
                      break;
                  case webim.MSG_ELEMENT_TYPE.LOCATION:
                      html += this.convertLocationMsgToHtml(content);
                      break;
                  case webim.MSG_ELEMENT_TYPE.CUSTOM:
                      var eleHtml = this.convertCustomMsgToHtml(content);
                      //转义，防XSS
                      html += webim.Tool.formatText2Html(eleHtml);
                      break;
                  case webim.MSG_ELEMENT_TYPE.GROUP_TIP:
                      var eleHtml = this.convertGroupTipMsgToHtml(content);
                      //转义，防XSS
                      html += webim.Tool.formatText2Html(eleHtml);
                      break;
                  default:
                      webim.Log.error('未知消息元素类型: elemType=' + type);
                      break;
              }
          }
          return html;
      },
      convertTextMsgToHtml(content) {
          return content.getText();
      },
      //解析表情消息元素
      convertFaceMsgToHtml(content) {
          var faceUrl = null;
          var data = content.getData();
          var index = webim.EmotionDataIndexs[data];

          var emotion = webim.Emotions[index];
          if (emotion && emotion[1]) {
              faceUrl = emotion[1];
          }
          if (faceUrl) {
              return "<img src='" + faceUrl + "'/>";
          } else {
              return data;
          }
      },
      //解析图片消息元素
      convertImageMsgToHtml(content, imageName) {
          var smallImage = content.getImage(webim.IMAGE_TYPE.SMALL);//小图
          var bigImage = content.getImage(webim.IMAGE_TYPE.LARGE);//大图
          var oriImage = content.getImage(webim.IMAGE_TYPE.ORIGIN);//原图
          if (!bigImage) {
              bigImage = smallImage;
          }
          if (!oriImage) {
              oriImage = smallImage;
          }
          return "<img name='" + imageName + "' src='" + smallImage.getUrl() + "#" + bigImage.getUrl() + "#" + oriImage.getUrl() + "' style='CURSOR: hand' id='" + content.getImageId() + "' bigImgUrl='" + bigImage.getUrl() + "' />";
      },
      onSelSess(sess_type, to_id) {
        var _this = this;
        if(this.selToID != to_id) {
          this.message = '';
        }
        if (sess_type == webim.SESSION_TYPE.GROUP) {
          this.$message.error("不支持群聊");
          return;
        }
        this.messageBox = [];
        this.bindScrollHistoryEvent('reset');
        this.getLastC2CHistoryMsgs(function (msgList) {
            _this.getHistoryMsgCallback(msgList);
            _this.bindScrollHistoryEvent('init');
            //绑定滚动操作
        }, function (err) {
            alert(err.ErrorInfo);
        });
      },
      getHistoryMsgCallback(msgList, prepage) {
          var msg;
          var prepage = prepage || false;

          //如果是加载前几页的消息，消息体需要prepend，所以先倒排一下
          if (prepage) {
              msgList.reverse();
          }

          for (var j in msgList) {//遍历新消息
              msg = msgList[j];
              if (msg.getSession().id() == this.selToID) {//为当前聊天对象的消息
                  this.selSess = msg.getSession();
                  //在聊天窗体中新增一条消息
                  this.addMsg(msg, prepage);
                  var thisdiv = document.getElementById('badgeDiv_'+ this.selToID);
                  thisdiv.innerHTML = '<i class="count"></i>';
                  thisdiv.style.display = 'none';
              }
          }
          //消息已读上报，并将当前会话的消息设置成自动已读
          webim.setAutoRead(this.selSess, true, true);
      },
      getPrePageC2CHistoryMsgs  (cbOk, cbError) {
        var _this = this;
          if (selType == webim.SESSION_TYPE.GROUP) {
            _this.$message.error("当前的聊天类型为群聊天，不能进行拉取好友历史消息操作");
              return;
          }
          var tempInfo = getPrePageC2CHistroyMsgInfoMap[_this.selToID];//获取下一次拉取的c2c消息时间和消息Key
          var lastMsgTime;
          var msgKey;
          if (tempInfo) {
              lastMsgTime = tempInfo.LastMsgTime;
              msgKey = tempInfo.MsgKey;
          } else {
              _this.$message.error("获取下一次拉取的c2c消息时间和消息Key为空");
              return;
          }
          var options = {
              'Peer_Account': _this.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;
                  }
                  getPrePageC2CHistroyMsgInfoMap[_this.selToID] = {//保留服务器返回的最近消息时间和消息Key,用于下次向前拉取历史消息
                      'LastMsgTime': resp.LastMsgTime,
                      'MsgKey': resp.MsgKey
                  };
                  if (cbOk) {
                      cbOk(resp.MsgList);
                  } else {
                      _this.getHistoryMsgCallback(resp.MsgList, true);
                  }
              },
              cbError
          );
      },
      getLastC2CHistoryMsgs (cbOk, cbError) {
        var _this = this;
          var lastMsgTime = 0;//第一次拉取好友历史消息时，必须传0
          var msgKey = '';
          var options = {
              'Peer_Account': this.selToID, //好友帐号
              'MaxCnt': reqMsgCount, //拉取消息条数
              'LastMsgTime': lastMsgTime, //最近的消息时间，即从这个时间点向前拉取历史消息
              'MsgKey': msgKey
          };
          this.selSess = null;
          webim.MsgStore.delSessByTypeId(selType, this.selToID);

          webim.getC2CHistoryMsgs(
              options,
              function (resp) {
                  var complete = resp.Complete;//是否还有历史消息可以拉取，1-表示没有，0-表示有

                  if (resp.MsgList.length == 0) {
                      webim.Log.warn("没有历史消息了:data=" + JSON.stringify(options));
                      return;
                  }
                  getPrePageC2CHistroyMsgInfoMap[_this.selToID] = {//保留服务器返回的最近消息时间和消息Key,用于下次向前拉取历史消息
                      'LastMsgTime': resp.LastMsgTime,
                      'MsgKey': resp.MsgKey
                  };
                  
                  if (cbOk)
                      cbOk(resp.MsgList);
              },
              cbError
          );
      },
      handleMsgSend(msgContent) {
          
          var selSess = new webim.Session(selType, this.selToID, this.selToID, this.thisCustomer.avatar, Math.round(new Date().getTime() / 1000));
          
          var isSend = true; //是否为自己发送
          var seq = -1; //消息序列，-1表示sdk自动生成，用于去重
          var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
          var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
          var subType; //消息子类型
          if (selType == webim.SESSION_TYPE.C2C) {
              subType = webim.C2C_MSG_SUB_TYPE.COMMON;
          } else {
              subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
          }
          var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, this.loginInfo.identifier, subType, this.loginInfo.identifierNick);

          var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
          //解析文本和表情
          var expr = /\[[^[\]]{1,3}\]/mg;
          var emotions = msgContent.match(expr);
          if (!emotions || emotions.length < 1) {
              text_obj = new webim.Msg.Elem.Text(msgContent);
              msg.addText(text_obj);
          } else {
              for (var i = 0; i < emotions.length; i++) {
                  tmsg = msgContent.substring(0, msgContent.indexOf(emotions[i]));
                  if (tmsg) {
                      text_obj = new webim.Msg.Elem.Text(tmsg);
                      msg.addText(text_obj);
                  }
                  emotionIndex = webim.EmotionDataIndexs[emotions[i]];
                  emotion = webim.Emotions[emotionIndex];

                  if (emotion) {
                      face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
                      msg.addFace(face_obj);
                  } else {
                      text_obj = new webim.Msg.Elem.Text(emotions[i]);
                      msg.addText(text_obj);
                  }
                  restMsgIndex = msgContent.indexOf(emotions[i]) + emotions[i].length;
                  msgContent = msgContent.substring(restMsgIndex);
              }
              if (msgContent) {
                  text_obj = new webim.Msg.Elem.Text(msgContent);
                  msg.addText(text_obj);
              }
          }

          msg.PushInfo = {
              "PushFlag": 0,
              "Desc": '测试离线推送内容', //离线推送内容
              "Ext": '测试离线推送透传内容', //离线推送透传内容
              "AndroidInfo": {
                  "Sound": "android.mp3" //离线推送声音文件路径。
              },
              "ApnsInfo": {
                  "Sound": "apns.mp3", //离线推送声音文件路径。
                  "BadgeMode": 1
              }
          };

          msg.PushInfoBoolean = true; //是否开启离线推送push同步
          msg.sending = 1;
          msg.originContent = msgContent;
          // turnoffFaces_box();
          var _this = this;

          webim.sendMsg(msg, function (resp) {
            _this.addMsg(msg);
            _this.message = '';
          }, function (err) {
              console.log(err)
          });
      },
      
    },
    watch:{
      userSigFlag(newValue){
        if(this.userSigFlag) {
          this.webimlogin();
        }
      },
      userListFlag(newValue){
        if(this.userListFlag && this.imloginFlag) {
          this.initUnreadMsgCount();
        }

      },
      imloginFlag(newvalue) {
        if(this.userListFlag && this.imloginFlag) {
          this.initUnreadMsgCount();
        }
      }
    },
    created(){
      
      this.GetAllMembers();
      this.getusersig();

      this.emotionList = [];

      for (var index in webim.Emotions) {
        var item = {
          id:webim.Emotions[index][0],
          src:webim.Emotions[index][1],
        };
        this.emotionList.push(item);
      }

    },
  }
</script>

<style scoped>
  /*.app-container .cell.clearfix .time ul li {*/
    /*float: left;*/
    /*list-style: none;*/
    /*cursor: pointer;*/
    /*padding: 6px 20px;*/
    /*color: #606266;*/
    /*border-radius: 4px;*/
    /*margin: 0 8px 0 0;*/
    /*font-size: 14px;*/
    /*text-align: center;*/
  /*}*/

  
.app-container{
  height: 750px;  
}
.customer_plate {
  width: 100%;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -moz-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  height:100%;
}
.customer_plate .aside {
  width: 282px;
  -webkit-flex-shrink: 0;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  position: relative;
  border-right: 1px solid #e5e8ea;
}
.customer_plate .aside .client_list_box {
  position: absolute;
  width: 100%;
  top: 50px;
  left: 0;
  bottom: 0;
  overflow-x: visible;
  overflow-y: auto;
}
.channelswitch-wrap {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.customer_plate .aside .client_list_box .client_list {
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
}
.customer_plate .aside .customer_search {
  margin: 0 10px;
  height: 34px;
}
.customer_plate .aside .super_searchbox {
  padding: 0 8px;
  background-color: #f4f7fa;
  border-radius: 30px;
  margin-top: 15px;
  font-size: 12px;
}
.customer_plate .aside .super_searchbox .cus_search_input {
  border: none;
  background: none;
  width: 224px;
  height: 22px;
  line-height: 22px;
}
.customer_plate .aside .super_searchbox .search_icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  background: url(http://jk.kuyicloud.com/static/images/ico.png) no-repeat;
  float: left;
  background-position: -460px -314px;
  margin: 4px 5px 0 0;
}
.left_content {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -moz-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  position: relative;
  width: 100%;
  justify-content: flex-start;
  flex-direction: column;
}
.left_content .message-list-wrap {
  position: absolute;
  top: 50px;
  overflow: hidden;
  left: 0;
  right: 0;
  border-bottom: 1px #e5e8ea solid;
  bottom: 210px;
}
.left_content .message-list-wrap .message-list-item {
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
}
.left_content .message-list-wrap .message-list {
  padding: 0 12px 20px;
}
.left_content .conversation-admin {
  height: 48px;
  line-height: 48px;
  border-bottom: 1px #e5e8ea solid;
  margin-left: 2px;
  width: 100%;
}
.left_content .conversation-admin .nickname {
  padding-left: 22px;
}
.client_list ul {
  list-style: none;
}
.client_list ul .item {
  padding: 17px 12px 17px 62px;
  min-height: 36px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s linear;
  -webkit-transition: background-color 0.2s linear;
  -moz-transition: background-color 0.2s linear;
  position: relative;
}
.client_list ul .Active {
  background: #f4f7fa;
}
.client_list ul .item .nick {
  font-size: 14px;
  color: #485b6d;
  margin-bottom: 7px;
}
.client_list ul .item:hover {
  background: #dfedfb;
}
.client_list ul .item .time {
  position: absolute;
  top: 14px;
  right: 12px;
  color: #a8b3ba;
}
.client_list ul .item .circle-count {
  padding: 2px;
  background-color: #ff7979;
  text-align: center;
  left: 8px;
  z-index: 2;
  min-width: 17px;
  min-height: 15px;
  line-height: 12px;
  border-radius: 10px;
  position: absolute;
  top: 12px;
  display: inline-block;
}
.client_list ul .item .circle-count .count {
  color: #fff;
  display: inline-block;
  -webkit-transform: scale(0.83);
  -moz-transform: scale(0.83);
  -ms-transform: scale(0.83);
  transform: scale(0.83);
}
.client_list ul .item .session-pic {
  position: absolute;
  top: 17px;
  left: 13px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  display: inline-block;
}
.client_list ul .item .session-pic img {
  width: 40px;
  height: 40px;
}
.client_list ul .item .square-close {
  color: #fff;
  background-color: #d2d2d5;
  display: none;
  width: 14px;
  height: 14px;
  line-height: 12px;
  text-align: center;
  position: absolute;
  top: 0;
  right: 0;
}
.client_list ul .item:hover .square-close {
  display: block;
}
.client_list ul .item .desc {
  color: #a8b3ba;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 150px;
}
.service_fixed {
  position: fixed;
}
.message-list-wrap ul li {
  padding: 12px;
}
.message-list-wrap .message-item .time {
  text-align: center;
  margin: 20px 0 6px 0;
}
.message-list-wrap .message-item .time span {
  font-size: 12px;
  color: #a8b3ba;
}
.message-list .message-item .user .bg-pic {
  display: inline-block;
  margin-right: 20px;
}
.message-list .message-item .message-body {
  background: #e5e8ea;
  padding: 16px 12px 12px 12px;
  border-radius: 4px;
  color: #485b6d;
  max-width: 520px;
}
.message-list .message-item .user .bg-pic .bg-pic-content {
  border-radius: 50%;
  display: inline-block;
  width: 40px;
  height: 40px;
}
.message-list .message-item .user .bg-pic img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: inline-block;
}
.no_session {
  text-align: center;
}
.send_box {
  position: absolute;
  font-size: 13px;
  bottom: 0;
  height: 210px;
  left: 0;
  right: 0;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -moz-box-orient: vertical;
  -moz-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}
.send_box .inputer_actions {
  padding: 10px;
  background: #f5f5f5;
}

.send_box .inputer_actions .face {
  float: left;
  margin: 0;
  height: auto;
}
.send_box .inputer_actions .face_icon {
  width: 24px;
  height: 22px;
  background: url(http://jk.kuyicloud.com/static/images/ico.png) no-repeat -478px -314px;
  display: inline-block;
  margin-right: 22px;
  cursor: pointer;
}
.send_box .inputer_actions .picture_icon {
  width: 28px;
  height: 24px;
  background: url(http://jk.kuyicloud.com/static/images/ico.png) no-repeat -508px -314px;
  display: inline-block;
  margin-right: 22px;
  cursor: pointer;
}
.inputer-area {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -moz-box-flex: 1;
  -moz-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin: 2px;
  overflow: hidden;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flexbox;
  display: -moz-box;
  display: flex;
  -webkit-box-direction: normal;
  -webkit-box-orient: vertical;
  -webkit-flex-direction: column;
  -moz-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
}
.inputer-area .message-textarea {
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flexbox;
  display: -moz-box;
  display: flex;
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -moz-box-flex: 1;
  -moz-flex: 1;
  -ms-flex: 1;
  flex: 1;
  width: auto;
  height: 100%;
  resize: none;
  margin: 0;
  padding: 9px 4px;
  font-size: 14px;
  line-height: 1.5em;
  border: none;
  overflow-x: hidden;
  overflow-y: auto;
  border-radius: 0;
  -webkit-box-shadow: none;
  box-shadow: none;
  padding: 0 9px 4px;
}
.send_box .send_box_btn {
  position: absolute;
  bottom: 26px;
  right: 40px;
}
.send_box .send_box_btn .send_btn {
  background: #58a2ec;
  color: #fff;
  padding: 12px 55px;
  border-radius: 4px;
  border: none;
  font-size: 14px;
}
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : 2015-7-6, 15:55:30
    Author     : peakerdong
*/

#login {
    display: block;
    margin: 150px auto;
    text-align: center;
}

.aio {
    display: none;
    width: 734px;
    border: 1px black solid;
    padding: 0px;
    background: white;
    margin: 20px auto;
    font: 10px/1.5 "微软雅黑";
}

.titlebar {
    height: 82px;
    background: #5c95b3;
}

.titlebar #p_my_face {
    position: relative;
    width: 60px;
    height: 60px;
    border: 1px white solid;
    margin: 10px;
    float: left;
}

.titlebar #t_my_name {
    position: relative;
    top: 10px;
    left: 10px;
    float: left;
    font-size: 20px;
    color: white;
}

.titlebar #t_my_menu {
    width: 150px;
    position: relative;
    top: 5px;
    right: 5px;
    float: right;

}

.sesspart {
    clear: both;
    float: left;
    width: 208px;
    height: 535px;
    background: #d7eaf3;
}

.accordion {
    margin-bottom: 18px;
}

.accordion-group {
    margin-bottom: 2px;
    border: 1px solid #e5e5e5;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.accordion-heading {
    border-bottom: 0;
    background-color: bisque;
}

.accordion-heading .accordion-toggle {
    display: block;
    padding: 8px 15px;
    font-size: medium;
}

.accordion-inner {
    padding: 9px 15px;
    border-top: 1px solid #e5e5e5;
}
.sesslist-recent {
    height: 450px;
    background: #f5f5f5;
    border-width: 0px 1px 0px 0px;
    border-color: #d5d6d7;
    border-style: solid;
}


.sesslist {
    /* height: 400px; */
    height: 450px;
    background: #f5f5f5;
    border-width: 0px 1px 0px 0px;
    border-color: #d5d6d7;
    border-style: solid;
    overflow: auto;
}

.sesslist-group {
    /* height: 400px; */
    height: 450px;
    background: #f5f5f5;
    border-width: 0px 1px 0px 0px;
    border-color: #d5d6d7;
    border-style: solid;
    overflow: auto;
}

.sessinfo {
    clear: both;
    height: 50px;
    border-width: 0px 0px 1px 0px;
    border-color: #d5d6d7;
    border-style: solid;
}

.sessinfo-sel {
    clear: both;
    height: 50px;
    border-width: 0px 0px 1px 0px;
    border-color: #d5d6d7;
    border-style: solid;
    background: #d7eaf3;
}

.face {
    float: left;
    width: 40px;
    height: 40px;
    margin: 5px 5px 5px 10px;
}

.name {
    float: left;
    height: 20px;
    text-indent: 2px;
    font-size: 12px;
    color: #1f1f1f;
    margin: 15px 0 0 0;
}

.badge {
    display: none;
    float: right;
    margin: 18px 0 0 0;
    width: 32px;
    height: 20px;
    background: #f00000;
    color: white;
    text-align: center;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

.badge span {
    position: relative;
    top: 1px;
    font-size: 10px;
}

.chatpart {
    float: right;
    width: 526px;
    border: 0px red solid;
    background: #d7eaf3;
    margin-top: -535px;
}

.msgflow {
    width: 525px;
    height: 380px;
    border: 1px rgb(181, 178, 178) solid;
    padding: 20px 6px 0 6px;
    background: #f5f5f5;
    overflow: auto;
}
.msgflow .onemsg{position:relative;}
.msgflow .onemsg .msghead {
    color: green;
    line-height: 12px;
    font-size: 12px;
}

.msgflow .onemsg .msgbody {
    margin: 0 0 0 18px;
    line-height: 13px;
    font-size: 14px;
}

.msgflow .msgbody img {
    max-width: 500px;
}

.editbar {
    width: 526px;
    height: 25px;
}

.chat02_title_btn {
    background: url('http://jk.kuyicloud.com/static/plugins/tencentim/IMSDK_V1.7/img/icon.png') no-repeat 0 0;
    cursor: pointer;
    float: left;
    display: block;
    width: 15px;
    height: 15px;
    margin: 5px 6px;
}

.ctb01 {
    background-position: 0 -90px;
    margin-left: 18px;
    _margin-left: 8px;
}

.ctb03 {
    background-position: 0 -152px;
}

.ctb02 {
    background-position: 0 -457px;
}

.ctb05 {
    background-position: 0 -217px;
}

.ctb04 {
    background-position: 0 -543px;
}

.wl_faces_box {
    background: url('http://jk.kuyicloud.com/static/plugins/tencentim/IMSDK_V1.7/img/wlf_bg.png') repeat 0 0;
    position: relative;
    /*position: absolute;*/
    width: 428px;
    height: 225px;
    bottom: 290px;
    left: -42px;
    display: none;
}

.wl_faces_content {
    background: #fff;
    border: 1px #ccc solid;
    width: 417px;
    height: 216px;
    margin: 3px 4px;
}

.wl_faces_content .title {
    background: url('http://jk.kuyicloud.com/static/plugins/tencentim/IMSDK_V1.7/img/wlf_title_bg.jpg') repeat-x 0 0;
    height: 40px;
    position: relative;
}

.wl_faces_content .title ul {

}

.wl_faces_content .title ul li {
    position: absolute;
    display: block;
}

.wl_faces_content .title ul li.title_name {
    background: url('http://jk.kuyicloud.com/static/plugins/tencentim/IMSDK_V1.7/img/wlf_title_btn.jpg') no-repeat 0 0;
    width: 82px;
    height: 30px;
    bottom: 0;
    _bottom: -2px;
    left: 15px;
    text-align: center;
    line-height: 32px;
    font-weight: bold;
    color: #333;
}

.wl_faces_content .title ul li.wl_faces_close {
    right: 8px;
    top: 15px;
}

.wl_faces_content .title ul li.wl_faces_close span {
    background: url('http://jk.kuyicloud.com/static/plugins/tencentim/IMSDK_V1.7/img/icon.png') repeat-x 0 0;
    cursor: pointer;
    display: block;
    width: 15px;
    height: 15px;
}

.wl_faces_main {

}

.wl_faces_main ul {
    margin: 12px 12px;
    padding: 0px;
    overflow: hidden;
    border-top: 1px #CCC solid;
    border-left: 1px #CCC solid;
    list-style: none;
    width: 393px;
}

.wl_faces_main ul li {
    float: left;
    border-right: 1px #CCC solid;
    border-bottom: 1px #CCC solid;
    height: 28px;
    width: 28px;
    margin: 0px 0px 0px 0px;
    padding: 4px 2px;
    text-align: center;
}

.wl_faces_main ul li img {
    width: 24px;
    height: 24px;
}

.wlf_icon {
    background: url('http://jk.kuyicloud.com/static/plugins/tencentim/IMSDK_V1.7/img/layer_arrow.png') no-repeat 0 0;
    position: absolute;
    width: 22px;
    height: 9px;
    bottom: -4px;
    _bottom: -11px;
    left: 61px;
}

.msgedit {
    width: 525px;
    height: 100px;
    border: 1px rgb(181, 178, 178) solid;
    background: #f5f5f5;
    padding: 6px 6px;
    line-height: 1.5;
}

.sendbar {
    width: 526px;
    height: 30px;
}

.sendbtn {
    float: right;
    width: 80px;
    margin-right: 10px;
    font: 10px/1.5 "微软雅黑";
}

.closebtn {
    float: right;
    width: 80px;
    margin-right: 10px;
    font: 10px/1.5 "微软雅黑";
}

.bottom {
    clear: both;
    height: 3px;
    background: #d7eaf3;
}

#demo_type_desc {
    color: red;
}

#myself_type_desc {
    display: none;
    color: red;
}

#qcloudLink {
    color: blue;
}

#sdkAppIdDiv {
    display: none;
}

#accountTypeDiv {
    display: none;
}

.pic_thumb {
    width: 200px;
    height: 200px;
}



.spinner {
    width: 60px;
    text-align: center;
    position: absolute;
    right: 10px;
    top: 32px;
    text-align: right;
}

.spinner > div {
  width: 6px;
  height: 6px;
  background-color: #333;

  border-radius: 100%;
  display: inline-block;
  -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
  animation: sk-bouncedelay 1.4s infinite ease-in-out both;
}

.spinner .bounce1 {
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}

.spinner .bounce2 {
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}

@-webkit-keyframes sk-bouncedelay {
  0%, 80%, 100% { -webkit-transform: scale(0) }
  40% { -webkit-transform: scale(1.0) }
}

@keyframes sk-bouncedelay {
  0%, 80%, 100% {
    -webkit-transform: scale(0);
    transform: scale(0);
  } 40% {
    -webkit-transform: scale(1.0);
    transform: scale(1.0);
  }
}

.headurlClass{
    height: 30px;
    width: 30px;
    border-radius: 50%;
}

.delChat{
    color: red;
    width: 50px;
    padding: 16px 0;
    float: right;
    margin-right: 5px;
}
figure {
  margin: 0;
}
</style>