let express = require('express');

let config = require("./config/config.js");
let fileUtils = require("./modules/common/fileUtils");
let dbm = require("./config/db/db_manager");
//config.setToLocalDb();
config.setToQaDb();
//config.setupCache();
let cfgCacheUtil = require("./config/cacheCfg");
cfgCacheUtil.setupDftCache();

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

let app = express();
let _rootDir = __dirname;
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,
    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();
    }
});

// 用户相关路由区域
//app.use('/', require("./modules/users/routes/login_route"));

require("./modules/users/routes/login_route")(app);
require("./modules/users/routes/boot_route")(app);
require("./modules/users/routes/user_route")(app);


// 项目工料机相关
require("./modules/glj/routes/glj_router")(app);

require('./modules/fee_rates/routes/fee_rates_route')(app);


require('./modules/templates/routes/bills_template_router')(app);


require('./modules/pm/routes/pm_route')(app);

require('./modules/main/routes/main_route')(app);

require('./modules/main/routes/project_route')(app);


let bills_Router = require('./modules/main/routes/bills_route');
let ration_Router = require('./modules/main/routes/ration_route');
let GLJ_Router = require('./modules/main/routes/GLJ_route');

app.use('/bills', bills_Router);
app.use('/ration', ration_Router);
app.use('/glj_bak', GLJ_Router);

//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.get("/stdBillsmain", function(req, res){
    if(!req.session.sessionUser){
        res.redirect('/login');
    }
    else {
        res.render("maintain/bills_lib/html/main.html",
            {userAccount: req.session.userAccount,
                userID: req.session.sessionUser.ssoId});
    }
});
app.get("/stdBills", function(req, res){
    res.render("maintain/bills_lib/html/qingdan.html");
});
app.get('/stdJobs', function(req, res){
    res.render('maintain/bills_lib/html/neirong.html');
});
app.get('/stdItems', function(req, res){
    res.render('maintain/bills_lib/html/tezheng.html');
});
let billsLibRouter = require("./modules/bills_lib/routes/bills_lib_routes");
app.use("/stdBillsEditor", billsLibRouter);

let rationRouter = require("./modules/ration_repository/routes/ration_front_end_routes");
app.use("/rationRepository/api", rationRouter);

let rpt_Router = require("./modules/reports/routes/report_router");
app.use("/report_api", rpt_Router);
let rptTpl_Router = require("./modules/reports/routes/rpt_tpl_router_fe");
app.use("/report_tpl_api", rptTpl_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!');
});


