let express = require('express');
import schedule from 'node-schedule';

let config = require("./config/config.js");
config.setupDb(process.env.NODE_ENV);
let dbm = require("./config/db/db_manager");

let path = require('path');
let session = require('express-session');
let DBStore = require('connect-mongo')(session);
let fileUtils = require("./modules/common/fileUtils");
let partials = require("express-partials");
let log = require("./logs/log_helper");

let URL = require('url');
let fs = require('fs');

let app = express();
let _rootDir = __dirname;
app.locals.rootDir = _rootDir;

dbm.connect(process.env.NODE_ENV);

//引入报表模块
fileUtils.getGlobbedFiles('./modules/all_models/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath));
});


//config.setupCache();
let cfgCacheUtil = require("./config/cacheCfg");
cfgCacheUtil.setupDftCache();

log.use(app);
app.use(express.static(_rootDir));

app.disable('view cache');

app.set('views', path.join(__dirname, 'web'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('view options', {
    // defaultLayout: 'users/views/layout/layout'
    defaultLayout: false
});
app.use(partials());

let bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({limit: '3mb', extended: true}));
app.use(bodyParser.json({limit: '3mb'}));

app.use(session({
    name: 'usersSession',
    secret: 'session users secret',
    cookie: {maxAge: 3600 * 6 * 1000},
    resave: false,
    rolling: true,
    saveUninitialized: true
    //*
    ,store: new DBStore({
        url: config.getSessionURL(process.env.NODE_ENV)
    })
    //*/
}));


app.use(function (req, res, next) {
    let referer = '';
    if (!/^\/login/.test(req.originalUrl) && !req.session.managerData) {
        if (req.headers["x-requested-with"] != null
            && req.headers["x-requested-with"] == "XMLHttpRequest"
            && req.url != "/login") {
            return res.json({ret_code: 99, ret_msg: '登录信息失效，请您重新登录'});
        } else{
            return res.redirect('/login');
        }
    }
    next();
});

//加载路由文件
fileUtils.getGlobbedFiles('./modules/**/routes/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath))(app);
});

app.use(function(req, res, next) {
    res.status(404).send('404 Error');
});
app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('500 Error');
});

//设置Date Format函数
//备注： 经过测试nodejs 8.9.3版本不支持eval的方式修改prototype，为兼容考虑，把方法调整到stringUtil文件里
require('./public/stringUtil').setupDateFormat();

//定时任务
let sysSchedule = require('./modules/sys_tools/models/sys_model');
schedule.scheduleJob({hour: 3, minute: 30, dayOfWeek: 7}, function(){
    sysSchedule.clearJunkData(function (err) {
        if(err){
            console.log('清除失败');
        }
        else{
            console.log('清除成功');
        }
    })
});

schedule.scheduleJob({hour: 0, minute: 1}, function(){
    sysSchedule.checkUserCompilationStatus(function (err) {
        if(err){
            console.log('更新失败');
        }
        else{
            console.log('更新成功');
        }
    })
});

// schedule.scheduleJob({hour: 10, minute: 0}, function(){
//     sysSchedule.sendCompilationStatusSms(function (err) {
//         if(err){
//             console.log('短信发送失败');
//         }
//         else{
//             console.log('短信发送成功');
//         }
//     })
// });

app.listen(6080, function () {
    console.log("server started!");
});
