const fs = require('fs')
/* 引入 公共 工具类 */
const Router = require('express').Router
const router = Router()

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

const conf = require('../config')
const cTool = require('../tools')

const _ = require('lodash')
const axios = require('axios')
const FormData = require('form-data')
const md5 = require('md5-node')

const _op = require('./operate')
const ckupload = require('./ckeditorUpload')
const _cookies = require('./cookies')
const _websocket = require('./websocket')
/* 支持 finally函数 */
require('promise.prototype.finally').shim()

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

/* 通过API统一过拦截器，接口代理转发请求 */
const agentProcessor = () => {
  return (req, res) => {
    let exp = new RegExp(['v', 'i', 'd', 'e', 'o', '-', 's', 't', 'r', 'e', 'a', 'm', 'i', 'n', 'g', '$'].join(''), 'gi')
    if (exp.test(req.baseUrl) && req.body.type) {
      _op.dirOperate(req, res)
      return
    }

    let timestamp = new Date().getTime()
    let json = new Buffer(req.headers['cur-json'] || '', 'base64').toString() || '{}'  // eslint-disable-line
    json = JSON.parse(json)
    const signStr = json.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)
          /* 增加 日期目录 */
          let dateDir = cTool.convertTime.durationToDateString(new Date().getTime())
          /* 增加 学员目录 */
          let stuDir = json.auth || '其他'
          fs.stat(elem.destination + dateDir, (error, stats) => {
            if (error) {
              fs.mkdir(elem.destination + dateDir, (error) => {
                if (error) { console.log(error); return false }
                fs.mkdir(elem.destination + dateDir + '/' + stuDir, (error) => {
                  if (error) { console.log(error); return false }
                  fs.renameSync(elem.destination + elem.originalname, elem.destination + dateDir + '/' + stuDir + '/' + elem.originalname)
                  fs.unlink(elem.destination + elem.originalname, (error) => { if (error) console.log(error) })
                })
              })
            } else {
              fs.stat(elem.destination + dateDir + '/' + stuDir, (error, stats) => {
                if (error) {
                  fs.mkdir(elem.destination + dateDir + '/' + stuDir, (error) => {
                    if (error) { console.log(error); return false }
                    fs.renameSync(elem.destination + elem.originalname, elem.destination + dateDir + '/' + stuDir + '/' + elem.originalname)
                    fs.unlink(elem.destination + elem.originalname, (error) => { if (error) console.log(error) })
                  })
                } else {
                  fs.renameSync(elem.destination + elem.originalname, elem.destination + dateDir + '/' + stuDir + '/' + elem.originalname)
                  fs.unlink(elem.destination + elem.originalname, (error) => { if (error) console.log(error) })
                }
              })
            }
          })
          _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']
      }

      let _cookieStr = headers['cookie'] || ''
      let _cookieArr = _cookieStr.split(';')
      let _SUP = ''
      for (let i = 0; i < _cookieArr.length; i++) {
        if (/_SUP=/gi.test(_cookieArr[i])) {
          _SUP = _cookieArr[i].split('=')[1]
          break
        }
      }
      headers['token'] = _cookies.getTicket(_SUP) // _SUP获取

      axios.defaults.headers = headers
      axios.defaults.withCredentials = true
      /* 日志记录，重新修改 2019.01.17 */
      let _log = {
        reqTime: timestamp, // 请求时长
        sys: json.sys, // 系统
        status: '', // 请求状态
        name: json.name, // 姓名
        auth: json.auth, // 账号
        IP: getClientIP(req), // IP值
        uuid: uuid, // uuid
        url: options.url, // 请求地址
        type: '', // 1:视频 2:课后作业 3:作业内容
        self: '', // 根据类型值，自定义 字符串参数
        param: JSON.stringify(options) // 请求参数 JSON str
      }
      /* 重新转发请求 */
      axios(options).then((data) => {
        _log.reqTime = (new Date().getTime() - _log.reqTime) + 'ms'
        _log.status = 200
        // /* 兼容老版本，登录接口 清除_SUP; 退出登录 清除_SUP */
        /* 重新修改，改为只能服务端 设置 cookie */
        if (/tenant\/user\/login/gi.test(options.url) || /tenant\/user\/code-login/gi.test(options.url)) {
          _cookies.setCookie(data.data.ticket, res)
        }
        if (/v3\/sso\/logout/gi.test(options.url)) {
          res.clearCookie('_SUP', { path: '/', domain: '.ezijing.com' })
          // res.cookie('_SUP', '', { path: '/', domain: '.ezijing.com' })
        }
        // setPorxyHeader(data, res)
        res.status(200).send(data.data)
      }).catch((e) => {
        _log.reqTime = (new Date().getTime() - _log.reqTime) + 'ms'
        _log.status = e.response.status || 500
        /* 未登录，则全部清空 _SUP */
        if (e.response.status === 403) {
          res.clearCookie('_SUP', { path: '/', domain: '.ezijing.com' })
        }
        /* 返回执行代码出错 或者 服务器请求错误 */
        if (e.response && e.response.data) {
          /* 如果未登录 强制 弹出到 登录页 */
          // setPorxyHeader(e.response, res)
          res.status(e.response.status).json(e.response.data)
          console.error(uuid + String.fromCharCode(0x001) + JSON.stringify(options) + String.fromCharCode(0x001) + JSON.stringify(e.response.data))
        } else {
          res.status(500).json({ message: '系统错误，请稍后重试或联系管理员', errMsg: 'Error Proxy Request or BackData Excute Error', code: 500 })
          console.error(uuid, e)
        }
      }).finally(() => {
        let _str = ''
        for (let key in _log) {
          _str += _log[key] + String.fromCharCode(0x001)
        }
        console.log(_str + ' -- end')
      })
    } catch (e) {
      res.status(500).json({ message: '系统错误，请稍后重试或联系管理员', errMsg: 'Network Server Excute Error', code: 500 })
      console.error('system error:', uuid, 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' }))

const getClientIP = (req) => {
  return req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress
}

/* 统一API接口 */
router.post('/api/ckeditor/img/upload', upload.any(), ckupload)
router.post('/api/websocket/send-msg', upload.any(), _websocket.sendMsg)
router.use('/api/*', upload.any(), agentProcessor('api'))

module.exports = router
