import webSocket from '.. /webSocket.js';
export default {
  isIosAndroid() {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1./ / android terminalisiOS = !! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/), / / ios terminal
      isChrome = u.indexOf('Safari'); // On the browser side
    return {
      isAndroid,
      isiOS,
      isChrome
    }
  },
  websocktSend(paramsObj) {
    // this --> store
    // This is used to send information to the back end websocket
    var userId = localStorage.getItem('userId');
    var sendMsg = () = > {
      window.socketServer.send(JSON.stringify(paramsObj)); // Send information to the back end
    }
    if (window.socketServer.readyState == 1) {
      sendMsg();
    } else {
      // This is passed in as $store
      // You don't know this
      webSocket.call(this, wsconPath[sceneParam] + userId).then(() = >{ sendMsg(); }); }},// Time displays minutes, hours, day, yesterday, the day before, and earlier times
  / / the 2019-12-07 09:58:23
  // JS calculates the time difference between two dates in the format of day, hour, minute, second
  showDiffTime: function (startDate) {
    if(! startDate) {return;
    }
    var startDate = startDate.replace(new RegExp(/-/gm), "/");
    var startDateB = new Date(startDate);

    var updateHour = startDateB.getHours(),
      updateMin = startDateB.getMinutes();

    updateHour = updateHour < 10 ? '0' + updateHour : updateHour;
    updateMin = updateMin < 10 ? '0' + updateMin : updateMin;
    var endDate = new Date(a);// The current time
    var diff = endDate.getTime() - startDateB.getTime(); // The number of milliseconds of the time difference
    // Calculate the difference of days
    var days = Math.floor(diff / (24 * 3600 * 1000));
    // 1. HH:MM is displayed on the same day
    // 2. Yesterday: HH:MM
    // 3. The day before yesterday
    // 4. Earlier display: **** ** month ** day HH:MM

    if (days > 0) {
      if (days == 1) {
        return "Yesterday" + updateHour + ':' + updateMin;
      }
      if (days == 2) {
        return "The day before yesterday" + updateHour + ':' + updateMin;
      }
      if (days > 2) {
        return startDate.split(' ') [0] + ' ' + updateHour + ':'+ updateMin; }}if (days == 0) {
      return updateHour + ':'+ updateMin; }},// Frequently triggered events such as scroll, resize, keyup Scroll will cause page jitter and even stutter
  debounce(fn, delay) {
    delay = delay || 200;
    var timer = null;

    return function () {
      var arg = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(this, arg); }, delay); }}},Copy the code
// Heartbeat detection
var heartCheck = {
    timeout: 3000.// Send heartbeat every 3 seconds
    // num: 3, // The heartbeat failed to respond to the reconnection
    timeoutObj: null.reset: function(){// The heartbeat detection countdown is reset to 30 seconds after receiving a successful push
        clearTimeout(this.timeoutObj);// Reset the countdown
        this.start();
    },
    start: function(){
        // Start the heartbeat detection mechanism and set the countdown time to 30 seconds
        this.timeoutObj = setTimeout(function(){
           // A heartbeat message is sent, and the back end returns a heartbeat message,
            // if onMessage receives the returned heartbeat, the connection is normal
            var userId = localStorage.getItem('userId');
            if(! userId){return;
            }
            window.socketServer.send(JSON.stringify({
                photographerObjectId:' '.type:'6'.leavingContent:' '.photographerId:userId  // Leave a message with the photographer id
            })); // Send information to the back end
        },this.timeout)
    }
    If onMessage gets a message from the server within the specified time range,
    // Resets the reset timer, 30 seconds after the last message was received from the backend, and executes the heartbeat check to see if it is broken.
}


/** Establish a connection */
function createWSConnect(path){
    var _store = this;
    
    if (typeof WebSocket === "undefined") {
        alert("Your browser does not support sockets");
    } else { 
        return new Promise((resolve,reject) = >{
            // instantiate the socket
            var socket = new WebSocket(path);
            // Listen for socket connections
            socket.onopen = function(){
                console.log("Socket connection successful!!");   
                window.socketServer = socket;
                resolve(socket);
                // If you want to store the socket, it is up to you

                // Heartbeat detection started
                heartCheck.start();

            };
            socket.onclose = function (e) {
                console.log('WebSocket disconnected:' + e.code + ' ' + e.reason + ' ' + e.wasClean)
                console.log(e);
                reconnect(path);
              }

            // Listen for socket errors
            socket.onerror = function(){
                socket.close();
                reject();
                console.log("Connection error");
                reconnect(path);
            };
              // Listen for socket messages, the data from the back end to the front end
            socket.onmessage = function(res){
                if(res.data==1) {// Check the heartbeat
                    heartCheck.reset();
                    return;
                }   
                var data = res.data && JSON.parse(res.data); 
                // _store.dispatch('UpdateChatBadge',{count:data.count})updateMsgForType.call(_store,data); }; }}})// Re-establish the link
reconnect.lockReconnect = false;// Avoid duplicate connections
reconnect.timer = ' ';
function reconnect(url) {
    if (reconnect.lockReconnect) return;
    reconnect.lockReconnect = true;

    reconnect.timer && clearTimeout(reconnect.timer);
    // Set delay to avoid too many requests
    reconnect.timer = setTimeout(function () {     
        createWSConnect(url);
        reconnect.lockReconnect = false;
    }, 4000);
}

function updateMsgForType(data){
    if(data.error){
        this.$Toast(data.error);
        return;             
    }

    this.dispatch('UpdateChatBadge', {count:data.count})
    switch(data.type){
        case '0':  // 0 One-to-one text exchange
            this.dispatch('communication/addOneToOne',data.siteComm)
        break;
        case '1': //1
            this.dispatch('communication/addOneToOne',data.siteComm)
        break;
        case '2': //2 Total number of unread messages
        break;
        case '3': // Retract the deleted information
            this.dispatch('communication/withdrawOneToOne', {count:data.siteComm})

        break;
        case '4': // Delete one-to-one messages
            this.dispatch('communication/delOneToOne',data.siteComm)
        break;
        case '5': // Delete one-to-one messages in batches
            this.dispatch('communication/delAllOneToOne',data.siteComm)
        break; }}export default createWSConnect;
Copy the code
utils.websocktSend.call(this.$store, paramsObj);
Copy the code