'use strict';

/**
 *
 *
 * @author Zhong
 * @date 2018/5/24
 * @version
 */

import fs from 'fs';
import path from 'path';
import multiparty from 'multiparty';
import BaseController from "../../common/base/base_controller";

//import sysSchedule from '../models/sys_model';
let sysSchedule = require('../models/sys_model');
let callback = function(req, res, err, message, data){
    res.json({error: err, message: message, data: data});
};
const shareDir = 'public/share/';
class SysTools extends BaseController{
    clearJunkData(req, res){
        sysSchedule.clearJunkData(function (err) {
            let msg = '清除成功';
            let errCode = 0;
            if(err){
                msg = '清除失败';
                errCode = 1;
            }
            callback(req, res, errCode, msg, null);
        });
    }

    clearFakeData(req, res){
        sysSchedule.clearFakeData(function (err) {
            let msg = '清除成功';
            let errCode = 0;
            if(err){
                msg = '清除失败';
                errCode = 1;
            }
            callback(req, res, errCode, msg, null);
        });
    }
    //上传文件:用户手册、升级说明pdf文件
    /*
     * 这两个文件在前台帮助下拉中使用，与产品绑定，即一个养护产品（重庆养护、浙江xx...）只有一份文件
     * 所以保存到的文件夹直接分为两个：userGuide和upgradeGuide，前台到对应文件夹直接获取文件
     * */
    async uploadFile(req, res) {
        const validTrigger = {
            userGuide: 'userGuide', //用户手册
            upgradeGuide: 'upgradeGuide' //升级说明
        };
        let uploadDir = path.join(req.app.locals.rootDir, shareDir);
        let form = new multiparty.Form({uploadDir: uploadDir});
        form.parse(req, async function(err, fields, files){
            try {
                const file = typeof files.file !== 'undefined' ? files.file[0] : null;
                if(err || !file) {
                    throw '上传失败';
                }
                //文件类型
                const trigger = typeof fields.trigger !== 'undefined' && fields.trigger.length > 0 ? fields.trigger[0] : null;
                if (!trigger || !trigger in validTrigger) {
                    throw '该操作没有上传权限'
                }
                if (!fs.existsSync(uploadDir)) {
                    fs.mkdirSync(uploadDir);
                }
                //根据触发源放置文件到相关文件夹
                let triggerPath = path.join(uploadDir, trigger);
                if (!fs.existsSync(triggerPath)) {
                    fs.mkdirSync(triggerPath);
                }
                //文件后缀
                let px = file.originalFilename.split('.').pop();
                //重命名
                let newFileName = trigger + '.' + px;
                let newPath = path.join(triggerPath, newFileName);
                fs.renameSync(file.path, newPath);
                //返回图片域名后的url
                res.json({error: 0, data: `${shareDir}/${trigger}/${newFileName}`, message: 'success'});
            } catch (err) {
                console.log(err);
                res.json({error: 1, data: null, message: err});
            }
        });
    }
}

export {SysTools as default};