'use strict';

/**
 * 自定义启动文件
 *
 * @author CaiAoLin
 * @date 2017/8/29
 * @version
 */
const Uglyfy = require('uglify-es');
const fs = require('fs');
const BaseService = require('./app/base/base_service');
const BaseController = require('./app/base/base_controller');
module.exports = app => {
    // 数据模型基类
    app.BaseService = BaseService;

    // 控制器基类
    app.BaseController = BaseController;

    // 自定义手机校验规则
    app.validator.addRule('mobile', (rule, value) => {
        try {
            const regPhone = /^1([34578]\d)\d{8}$/;
            const allowEmpty = rule.allowEmpty === true;
            if (allowEmpty && value === '') {
                return true;
            }
            if (!(value.length === 11 && regPhone.test(value))) {
                throw 'please enter the correct phone number';
            }
        } catch (error) {
            return error;
        }
    });

    // 自定义手机IP规则
    app.validator.addRule('ip', (rule, value) => {
        try {
            const allowEmpty = rule.allowEmpty === true;
            if (allowEmpty && value === '') {
                return true;
            }
            const regIP = /^(\d{2,})\.(\d+)\.(\d+)\.(\d+)$/;
            if (!regIP.test(value)) {
                throw 'please enter the correct ip address';
            }
        } catch (error) {
            return error;
        }
    });

    //压缩前端js
    if (app.config.min) {
        app.minify = (file) => {
            const files = file instanceof Array ? file : [file];
            for (const f of files) {
                const fileName = app.baseDir + '/app/public/js/' + f;
                const code = fs.readFileSync(fileName, 'utf8');
                fs.writeFileSync(fileName.replace('.js', '.min.js'), Uglyfy.minify(code, { mangle: true }).code);
            }
        };
        app.minify(['spreadjs_rela/spreadjs_zh.js', 'path_tree.js']);
    }
};
