const fs = require('fs')

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

const axios = require('axios')

/* 支持 finally函数 */
require('promise.prototype.finally').shim()

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 = 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']

    let _fileName = com.Tool.ReqType.toFormData(req, options)

    headers['token'] = com.Tool.Cookie.getTicketByCAS('_SUP', req)
    headers['tenant'] = 'classes'
    headers['apikey'] = 'ITol9gsbkEb85gnaxIu7oWfHDOaKgwbH'
    headers['Host'] = 'ep-api.ezijing.com'
    headers['host'] = 'ep-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')
    }).finally(() => {
      /* 请求结束，删除服务器端 缓存文件 */
      if (_fileName.length) {
        for (let i = 0; i < _fileName.length; i++) {
          fs.unlinkSync(_fileName[i])
        }
      }
    })
  }
}

module.exports = {
  ckeditorUpload: ckeditorUpload
}
