'use strict';
const request = require('superagent');
// const parse = require('async-busboy');
// const path = require('path')
// const fs = require('fs');

const ext = {
   project: [".txt", ".dwg", ".doc", ".docx", ".xls", ".xlsx", ".pdf", ".png", ".jpg", ".svg"],
   report: [".doc", ".docx", ".xls", ".xlsx", ".pdf"],
   data: [".txt", ".xls", ".xlsx"],
   image: [".png", ".jpg", ".svg"],
   three: [".js"],
   video: [".mp4"],
   bpmn: [".bpmn", ".bpmn20.xml", ".zip", ".bar"],
   app: [".apk"],
   excel: ['.xls', '.xlsx', '.csv'],
}

module.exports = {
   entry: function (app, router, opts) {

      const getApiRoot = async function (ctx) {
         const { apiUrl, webPepUrl } = opts;

         ctx.status = 200;
         ctx.body = {
            root: apiUrl,
            webPepUrl
         };
      };

      let download = async function (ctx, next) {
         const { fetchUrl } = opts.qiniu;
         if (ctx.path && ctx.path.includes(fetchUrl)) {
            try {
               const { filename } = ctx.request.query;
               const fkey = decodeURI(ctx.path.slice(fetchUrl.length + 1)).replace(/\.json$/, '.js');
               const publicDownloadUrl = await app.fs.attachment.download(fkey);
               ctx.status = 200;
               if (filename) ctx.attachment(filename);
               ctx.body = request.get(publicDownloadUrl);
            } catch (err) {
               ctx.fs.logger.error(err);
               ctx.status = 404;
               ctx.body = { error: 'file not found.' }
            }
         } else {
            await next();
         }
      }


      let upload = async function (ctx, next) {
         try {
            console.log('-------------');
            const { token } = ctx.request.query
            console.log(token);
            if (token) {
               const { files } = await parse(ctx.req)
               const file = files[0]
               const extname = path.extname(file.filename).toLowerCase()
               const ftype = ctx.query.type;
               if (!(FILE_TYPE[ftype] || []).includes(extname)) {
                  ctx.status = 400
                  ctx.body = { error: '文件格式无效' }
                  return;
               }
               const fileInfo = await app.fs.attachment.upload(file, { uploadPath: ftype }) // uploadPath: 附件存放的文件夹
               ctx.status = 200;
               console.log(fileInfo);
               console.log('0000000000000000000000');

               ctx.body = { uploaded: fileInfo.key } // key: `${uploadPath}/${uuid}/${filename}`
            } else {
               ctx.status = 403
               ctx.body = { name: 'Forbidden', message: 'token无效,禁止访问' }
            }
         } catch (err) {
            ctx.status = 400
            ctx.body = {
               name: 'BadRequest',
               message: 'error happened while uploading file to qiniu.'
            }
         }
      }

      let remove = async function (ctx, next) {
         try {
            const { token } = ctx.request.query
            if (token) {
               const { fkeys } = ctx.request.body
               for (let index = 0; index < fkeys.length; index++) {
                  await app.fs.attachment.remove(fkeys[index])
               }
               ctx.status = 200
               ctx.body = { fkeys }
            } else {
               ctx.status = 403
               ctx.body = { name: 'Forbidden', message: 'token无效,禁止访问' }
            }
         } catch (err) {
            ctx.status = 400
            ctx.body = {
               name: 'BadRequest',
               message: 'error happened while removing file from qiniu.'
            }
         }
      }

      router.use(download);
      router.get('/api/root', getApiRoot);
      router.post('/file/qiniu/upload', upload);
      router.post('/file/qiniu/remove', remove);
   }
};