let express = require('express');

let config = require("./config/config.js");
let fileUtils = require("./modules/common/fileUtils");
let dbm = require("./config/db/db_manager");
let log = require("./logs/log_helper");
///config.setToLocalDb();
config.setupDb(process.env.NODE_ENV);

let path = require('path');
let session = require('express-session');
let DBStore = require('connect-mongo')(session);
let fs = require('fs');

let URL = require('url');
import rptCronJob from "./modules/reports/util/rpt_tmp_file_sweep";

dbm.connect(process.env.NODE_ENV);
//这里现在只引入了定额工料机里的models,当其它模块的models修改后使用：./modules/**/models/*.js引入所有的模块
fileUtils.getGlobbedFiles('./modules/all_models/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath));
})
//config.setupCache();
let cfgCacheUtil = require("./config/cacheCfg");
cfgCacheUtil.setupDftCache();


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

app.set('views', path.join(__dirname, 'web'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

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

app.use(session({
    name: 'yanghuSession',
    secret: 'session users secret',
    // @todo 上线前修改回正常值 （目前为24小时）
    cookie: {maxAge: 3600 * 24 * 1000},
    resave: false,
    rolling: true,
    saveUninitialized: true,
    //*
    store: new DBStore({
        url: config.getSessionURL(process.env.NODE_ENV)
    })
    //*/
}));

// 登录状态全局判断
/* const { stateChecking } = require('./modules/main/middleware/index');
app.use(stateChecking); */
app.use(function (req, res, next) {
    // 在内部在调用，而不直接在外部require后直接作为中间件回调函数app.use(stateChecking);的原因：
    // 由于各模块的引用不全是require，有些是import，import是预编译的。外部引用中间件可能会造成一些引用丢失。如：project_model.js中gljFacade.addMixRatioForNew会丢失
    // 不用过分担心性能问题。require有cache机制
    const { stateChecking } = require('./modules/main/middleware/index');
    stateChecking(req, res, next);
});

//加载路由文件
fileUtils.getGlobbedFiles('./modules/**/routes/*.js').forEach(function(modelPath) {
    if(modelPath.indexOf("import/routes")==-1) require(path.resolve(modelPath))(app);//排除掉导出导入服务
});

//app.use(express.static(_rootDir+"/web"));
//app.use(express.static(_rootDir+"/lib"));
//let rations_Router = require("./modules/rationLibEditor/routes/rationLibEditor_route");
//app.use("/rationLibEditor",rations_Router);

//-----------------

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();

app.listen(2060, function(){
    console.log('server started!');
});

//设置schedule job
//1. 报表临时文件
rptCronJob.createJob(null, __dirname + "/tmp");
//2. 其他（待补充）...
