const Router = require('express').Router
const router = Router()

const bodyParser = require('body-parser')
const multer = require('multer')
const upload = multer({ dest: 'upload_tmp/' })

const _ck = require('../controller/ckeditorMonitor')
const _op = require('../controller/DirMonitor')
const _websocket = require('../controller/SocketMonitor')
const _proxy = require('../controller/ProxyMonitor')

router.use(bodyParser.json({ limit: '600mb' }))
router.use(bodyParser.urlencoded({ extended: true, limit: '600mb' }))

router.use((req, res, next) => {
  /* 设置允许哪些外域访问此服务器。如果你要发送cookies，不要将其赋值为'*' */
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*')
  /* 设置允许发送cookies。可选值：true,如果不允许就省略此字段 */
  res.header('Access-Control-Allow-Credentials', 'true')
  if (req.method === 'OPTIONS') {
    /* 设置允许那些方法访问此服务器 */
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
    /* 设置允许那些头文件访问此服务器，数组中可以设置一些自定义首部 */
    let strArr = ['token', 'tenant']
    for (let k in req.headers) { strArr.push(k) }
    res.header('Access-Control-Allow-Headers', strArr.join(', '))
    /* 设置单个接口 OPTIONS 的最大有效时长 */
    res.header('Access-Control-Max-Age', 600)
    /* 以下设置OPTIONS返回并给空内容 */
    res.header('Content-Type', 'text/plain charset=UTF-8')
    res.header('Content-Length', 0)
    res.status(204).end()
    return
  }
  next()
})

/* 统一API接口 */
router.post('/api/ckeditor/img/upload', upload.any(), _ck.ckeditorUpload)
router.post('/api/websocket/send-msg', upload.any(), _websocket.sendMsg)
router.post('/api/dir/send-msg', upload.any(), _op.dirOperate)
router.use('/api/*', upload.any(), _proxy.agentProcessor())

module.exports = router
