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


dbm.connect();
//这里现在只引入了定额工料机里的models,当其它模块的models修改后使用：./modules/**/models/*.js引入所有的模块
fileUtils.getGlobbedFiles('./modules/ration_glj/models/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath));
})
//暂时引入其它模块的model
require('./modules/fee_rates/models/fee_rates');

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

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

let app = express();
let _rootDir = __dirname;
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({extended: false}));
app.use(bodyParser.json());

app.use(session({
    name: 'usersSession',
    secret: 'session users secret',
    cookie: {maxAge: 1000*60*30},
    resave: false,
    rolling: true,
    saveUninitialized: true
    //*
    ,store: new DBStore({
        url: 'mongodb://' + config.current.server + ':' + config.current.port + '/usersManages'
    })
    //*/
}));

// 登录状态全局判断
app.use(function (req, res, next) {
    let url = req.originalUrl;
    // @todo 上一个页面跳转
    let referer = '';
    if (/^\/login/.test(url)) {
        // 如果是登录页面则忽略判断数据
        next();
    } else {
        try {
            // 判断session
            let sessionUser = req.session.sessionUser;
            if (!sessionUser) {
                throw 'session error';
            }

            res.locals.sessionUser = sessionUser;
        } catch (error) {
            return res.redirect('/login');
        }

        next();
    }
});

//加载路由文件
fileUtils.getGlobbedFiles('./modules/**/routes/*.js').forEach(function(modelPath) {
    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函数
fs.readFile(__dirname + '/public/web/date_util.js', 'utf8', 'r', function (err, data) {
    eval(data);
    // let dt = new Date();
    // console.log(dt.Format('yyyy-M-dd'));
    // console.log(dt.Format('yyyy 年 M 月 dd 日'));
    // console.log(dt.Format('yyyy 年 M 月 20 日'));
});

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


