import { Message, MessageBox } from 'element-ui'
import store from '@/store'
// import signalR from 'signalr';// 在线客服
let hubConnection = null // SignalR实例
let lockReconnect = false // 避免重复连接
const signalR = window.signalR
const transportType = signalR.TransportType.WebSockets
// console.log(transportType)
// const signalrUrl = 'http://' + process.env.LineChat_SOCKET_IP + ':' + process.env.LineChat_SOCKET_PORT + '/chathub'
export function CreateSignalR() {
  try {
    // 服务器监听所有客户端，并返回该新连接对象
    Connects()
  } catch (e) {
    ReConnect()
  }
}

function Connects() {
  const signalrUrl = 'http://' + store.getters.serverConfig.LineChat_SOCKET_IP + ':' + store.getters.serverConfig.LineChat_SOCKET_PORT + '/chathub'
  const httpConnection = new signalR.HttpConnection(signalrUrl, {
    transport: transportType
  })
  hubConnection = new signalR.HubConnection(httpConnection)
  hubConnection.on('ReceiveMessage', data => {
    heartCheck.reset().start()
    console.log(new Date() + '  SignalR Receive :' + data)
    delGetData(JSON.parse(data))
  })

  hubConnection.onclose(data => {
    console.log(new Date() + ' SignalR close:' + data)
    ReConnect()
  })

  hubConnection.start().catch(error => {
    console.log(new Date() + 'SignalR  error:' + error)
    ReConnect()
  })
}

// 重连
function ReConnect() {
  if (!lockReconnect) {
    lockReconnect = true
    // 没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function() {
      console.log(new Date() + '  SignalR  ' + '重连中……')
      lockReconnect = false
      Connects()
    }, 2000)
  }
}

// 注册
function Registers(userCode) {
  const scoketDatas = {
    'action': 'serconn',
    'usercode': userCode,
    'channel': 1 // 渠道
  }
  Sends(scoketDatas)
}
// 发送
export function Sends(scoketDatas) {
  if (hubConnection.connection.connectionState === 1) {
    console.log(new Date() + '  Signalr Send: ' + JSON.stringify(scoketDatas))
    hubConnection.invoke('ReceiveMessage', JSON.stringify(scoketDatas))
  } else {
    ReConnect()
  }
}

// 心跳检测
const heartCheck = {
  timeout: 25000, // 25秒
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function() {
    clearTimeout(this.timeoutObj)
    clearTimeout(this.serverTimeoutObj)
    return this
  },
  start: function() {
    const _self = this
    this.timeoutObj = setTimeout(function() {
      // 这里发送一个心跳，后端收到后，返回一个心跳消息，
      // onmessage拿到返回的心跳就说明连接正常
      _self.sendHeart()
      _self.serverTimeoutObj = setTimeout(function() { // 如果超过一定时间还没重置，说明后端主动断开了
        hubConnection.stop()
      }, _self.timeout)
    }, this.timeout)
  },
  sendHeart: function() {
    const scoketDatas = {
      action: 'heart'
    }
    Sends(scoketDatas)
  }
}
// 点击左侧用户列表
export function selectSession(msg) {
  store.dispatch('getSelectSessionId', msg) // 改变store 中currentSessionId的值
}

// 处理接收到的信息数据
function delGetData(msgData) {
  if (msgData) {
    const type = msgData.action
    // let sessionUsercode= msgData.usercode
    switch (type.toLowerCase()) {
      case 'conn': // 建立连接
        lockReconnect = false
        Registers(store.getters.usercode) // 当前登录工号注册客服
        break

      case 'disconn': // 连接关闭
        console.error(new Date() + ' SingnalR  ' + '连接关闭')
        ReConnect()
        break

      case 'serconn': // 连接
        if (!msgData.state) {
          store.dispatch('errorMsg', msgData.message) // 返回错误信息
        } else {
          store.dispatch('getChatUserCode', msgData.usercode)
        }
        break

      case 'sersend': // 发送消息
        if (msgData.state) {
          const now = new Date()
          let strHours = now.getHours()
          let strMinutes = now.getMinutes()
          if (strHours >= 0 && strHours <= 9) {
            strHours = '0' + strHours
          }
          if (strMinutes >= 0 && strMinutes <= 9) {
            strMinutes = '0' + strMinutes
          }
          const msgs = {
            message: msgData.message,
            sessionid: msgData.sessionid,
            isSelf: true,
            'date': strHours + ':' + strMinutes
          }
          //  store.dispatch('appendMsg',msgs);  //添加收到的消息
          const session = store.getters.userList.find(item => item.sessionid === msgData.sessionid)
          session.message.push(msgs)
        } else {
          store.dispatch('getNoticeMsg', msgData.message) // 接受提示信息
          Message.error(msgData.message)
        }
        break

      case 'serreceive': { // 接收消息
        const now = new Date()
        let strHours = now.getHours()
        let strMinutes = now.getMinutes()
        if (strHours >= 0 && strHours <= 9) {
          strHours = '0' + strHours
        }
        if (strMinutes >= 0 && strMinutes <= 9) {
          strMinutes = '0' + strMinutes
        }
        if (!msgData.state) {
          store.dispatch('getNoticeMsg', msgData.message) // 接受提示信息
          // append(ele, "notice", data.msg)
          const users = {
            'sessionid': msgData.sessionid,
            'newMsg': '',
            'newMsgCount': 0,
            'user': {
              'headimgurl': msgData.headimgurl,
              'name': msgData.name,
              'dotShow': false
            },
            'message': []
          }
          store.dispatch('getUserList', users)
        // var obj={
        //   action :"loglist",
        //   code :msgData.usercode
        // }
        // Sends(obj)
        } else {
          let newMsgCount
          const msgs = {
            'headimgurl': msgData.headimgurl,
            'message': msgData.message,
            'sessionid': msgData.sessionid,
            'isSelf': false,
            'date': strHours + ':' + strMinutes
          }
          // store.dispatch('appendMsg',msgs);  //添加收到的消息
          const session = store.getters.userList.find(item => item.sessionid === msgData.sessionid)
          session.message.push(msgs)
          // debugger
          if (session.user.dotShow) {
            newMsgCount = 1
          } else {
            newMsgCount = parseInt(session.newMsgCount) + parseInt(1)
          }
          session.user.dotShow = false
          session.newMsg = msgData.message
          session.newMsgCount = newMsgCount
        }
        break
      }
    }
  }
}
