const Router = require('express').Router
const router = Router()
const bodyParser = require('body-parser')
const multer = require('multer')
const upload = multer({ dest: 'upload_tmp/' })
const FormData = require('form-data')
const axios = require('axios')
const conf = require('../config')
const _ = require('lodash')
const md5 = require('md5-node')
const fs = require('fs')

/**
 * 禁止响应头 中设置 cookie值
 * 这里 代理 全部 没有重置 cookie 值
 */

/* 通过API统一过拦截器，接口代理转发请求 */
const agentProcessor = () => {
  return (req, res) => {
    let timestamp = new Date().getTime()
    const signStr = req.headers['cur-auth'] + ':' + req.params[0] + ':' + timestamp
    const uuid = md5(signStr)

    let headers = _.assignIn({}, req.headers)
    let options = {}
    try {
      options = {
        timeout: 30 * 1000,
        url: req.params[0],
        baseURL: conf.agentApiUrl,
        method: req.method,
        data: req.body,
        params: req.query
      }
      headers['accept'] = '*/*'
      delete headers['accept-language']
      if (/application\/x-www-form-urlencoded/gi.test(headers['content-type'])) {
        let str = ''
        for (let k in options.data) {
          str += k + '=' + options.data[k] + '&'
        }
        options.data = str.substr(0, str.length - 1)
      }
      if (/multipart\/form-data/gi.test(headers['content-type'])) {
        let _obj = _.assignIn({}, req.body)
        req.files.forEach((elem, i) => {
          /* 缓存文件中 名称替换，上传名称一致 会被覆盖 */
          fs.renameSync(elem.path, elem.destination + elem.originalname)
          _obj[elem.fieldname] = fs.createReadStream(elem.destination + elem.originalname)
        })
        let fro = new FormData()
        for (let key in _obj) {
          fro.append(key, _obj[key])
        }
        options.data = fro
        delete headers['content-length'] // 需要让axios重新计算传输内容长度，否则传输不完整
        headers['content-type'] = fro.getHeaders()['content-type']
      }
      axios.defaults.headers = headers
      axios.defaults.withCredentials = true
      console.time(uuid) // 记录接口请求时间
      console.log('[Node] ' + signStr + ' Success Request to Node Server, id:' + uuid)
      console.log(uuid + '-options:' + JSON.stringify(options))

      /* 兼容老版本，登录接口 清除_SUP; 退出登录 清除_SUP */
      if (/tenant\/user\/login/gi.test(options.url) || /tenant\/user\/code-login/gi.test(options.url) || /v3\/sso\/logout/gi.test(options.url)) {
        res.clearCookie('_SUP', { path: '/', domain: '.ezijing.com' })
      }
      /* 重新转发请求 */
      axios(options).then((data) => {
        setPorxyHeader(data, res)
        res.status(200).send(data.data)
        console.log('[Node] ' + signStr + ', status: 200, Success Proxy to Services, id:' + uuid)
        console.timeEnd(uuid)
      }).catch((e) => {
        /* 返回执行代码出错 或者 服务器请求错误 */
        if (e.response && e.response.data) {
          setPorxyHeader(e.response, res)
          res.status(e.response.status).json(e.response.data)
          console.log('[Node] ' + signStr + ', status: ' + e.response.status + ', Success Proxy to Services, id:' + uuid)
          console.log('[node] Proxy to Services backInfo: ' + JSON.stringify(e.response.data))
        } else {
          res.status(500).json({ message: '系统错误，请稍后重试或联系管理员', errMsg: 'Error Proxy Request or BackData Excute Error', code: 500 })
          console.log('[Node]' + signStr + ', status: 500, Error Proxy Request or BackData Excute Error, id:' + uuid)
          console.error(uuid + '-proxyError:' + JSON.stringify(options))
          console.error(e)
        }
        console.timeEnd(uuid)
      })
    } catch (e) {
      res.status(500).json({ message: '系统错误，请稍后重试或联系管理员', errMsg: 'Network Server Excute Error', code: 500 })
      console.log('[Node] ' + signStr + ' Network Server Excute Error, id:' + uuid)
      console.error(uuid + ':' + JSON.stringify(options))
      console.error(e)
    }
  }
}

const setPorxyHeader = (data, res) => {
  if (data.headers['set-cookie']) {
    /* 不准许 服务端设置 _SUP */
    let _sCookie = data.headers['set-cookie'] || []
    for (let i = 0; i < _sCookie.length; i++) {
      if (/_SUP=/gi.test(_sCookie[i])) {
        _sCookie.splice(i, 1)
        break
      }
    }
    for (let key in data.headers) {
      res.append(key, data.headers[key])
    }
  }
}

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

/* 统一API接口 */
router.use('/api/*', upload.any(), agentProcessor('api'))

module.exports = router
