const fs = require('fs')

const conf = require('../config')
const datetime = require('@god/node-com').datetime

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

const ckeditorUpload = (req, res) => {
  /* 文件上传 ckeditor4.5以上返回格式 */
  function sendHtml (url, msg) {
    res.json({
      'uploaded': url ? 1 : 0,
      'fileName': 'image',
      'url': url,
      'error': {
        'message': msg
      }
    })
  }
  if (req.files.length) {
    if (!req.files[0].mimetype.startsWith('image')) { sendHtml('', '文件类型错误，请上传图片'); return }
    if (req.files[0].size > 10 * 1024 * 1024) { sendHtml('', '图片大小超限'); return }
    let headers = _.assignIn({}, req.headers)
    let options = {}
    options = {
      timeout: 30 * 1000,
      url: 'util/upload-image',
      baseURL: conf.agentApiUrl,
      method: req.method,
      data: req.body,
      params: req.query
    }
    headers['accept'] = '*/*'
    delete headers['accept-language']
    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 = 'ckeditor ' + datetime.timestampToFormatDateStr(new Date().getTime())
        /* 异步 处理文件 */
        fs.stat(elem.destination + dateDir, (error, stats) => {
          if (error) {
            fs.mkdir(elem.destination + dateDir, (error) => {
              if (error) { console.log(error); return false }
              fs.renameSync(elem.destination + elem.originalname, elem.destination + dateDir + '/' + elem.originalname)
            })
          } else {
            fs.renameSync(elem.destination + elem.originalname, elem.destination + dateDir + '/' + elem.originalname)
          }
        })
        _obj['image'] = 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 s = ''
    let arr = headers.cookie.split('; ')
    for (let i = 0; i < arr.length; i++) {
      if (/^_SUP/g.test(arr[i])) {
        s = arr[i].split('=')[1]
        break
      }
    }
    s = decodeURIComponent(s || '')
    let ticket = ''
    s = s.match(/"([\d\w=]+)";\}$/)
    if (s && s.length === 2) {
      s = new Buffer(s[1], 'base64').toString() // eslint-disable-line
      s = s.slice(12, s.search('-TGT') + 4)
      ticket = s.split('').reverse().join('')
    }
    headers['token'] = ticket
    headers['tenant'] = 'sofia'
    headers['apikey'] = 'mwLyCymyEVCcKTn7nKDjYIMPBwScbugX'
    headers['Host'] = 'lms-api.ezijing.com'
    headers['host'] = 'lms-api.ezijing.com'
    axios.defaults.headers = headers

    /* 重新转发请求 */
    axios(options).then((data) => {
      if (data.data.success) {
        sendHtml(data.data.url, '')
      } else {
        sendHtml('', '上传错误，请重试')
      }
      req.files.forEach((elem, i) => {
        fs.stat(elem.destination + elem.originalname, (error, stats) => {
          if (error) { return }
          fs.unlink(elem.destination + elem.originalname, (error) => { if (error) console.log(error) })
        })
      })
    }).catch((e) => {
      sendHtml('', '上传错误，请重试1')
    })
  }
}

module.exports = {
  ckeditorUpload: ckeditorUpload
}
