var express = require('express');

var config = require("./config/config.js");
//config.setToLocalDb();
config.setToQaDb();
//config.setupCache();
var cfgCacheUtil = require("./config/cacheCfg");
cfgCacheUtil.setupDftCache();

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

var URL = require('url')

var app = express();
var _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');

var 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) {
    var url = req.originalUrl, referer;
    if (!/^\/login/.test(req.originalUrl) && !req.session.userAccount) {
        if (/\/api/.test(req.originalUrl)) {
            referer = URL.parse(req.headers.referer);
            return res.redirect('/login' + '?referer=' + referer.path);
        } else {
            return res.redirect("/login" + '?referer=' + req.originalUrl);
        }
    }
    next();
});

app.use('/', require('./modules/users/routes/users_route'));
app.use('/feeRates', require('./modules/fee_rates/routes/fee_rates_route'));

app.get('/template/bills', function (req, res) {
    var checkAdmin = function (userAccount) {
        return true;
    }
    if (checkAdmin(req.session.userAccount)) {
        res.render('maintain/templates/html/bills.html',
            {userAccount: req.session.userAccount,
                userID: req.session.userID});
    } else {
        res.redirect('/pm');
    }
});

app.use('/template/bills/api', function (req, res, next) {
    var checkAdmin = function (userAccount) {
        return true;
    }
    if (checkAdmin(req.session.userAccount)) {
        next();
    } else {
        res.json({error: 1, message: '对不起，您无权限操作清单模板。', data: null});
    }
});
var billsTemplateRouter = require('./modules/templates/routes/bills_template_router');
app.use('/template/bills/api', billsTemplateRouter);

app.get('/pm', function(req, res){
    res.render('building_saas/pm/html/project-management.html',
        {userAccount: req.session.userAccount,
            userID: req.session.userID});
});
var pmRouter = require('./modules/pm/routes/pm_route');
app.use('/pm/api', pmRouter);

app.get('/main',  function(req, res) {
    var checkProjectRight = function (userID, projectID) {
        return true;
    }
    if (checkProjectRight(req.session.userID, req.query.project)) {
        res.render('building_saas/main/html/main.html',
            {
                userAccount: req.session.userAccount,
                userID: req.session.userID
            });
    } else {
        res.redirect('/pm');
    }
});

var project_Router = require('./modules/main/routes/project_route');
var bills_Router = require('./modules/main/routes/bills_route');
var ration_Router = require('./modules/main/routes/ration_route');
var GLJ_Router = require('./modules/main/routes/GLJ_route');
app.use('/project', project_Router);
app.use('/bills', bills_Router);
app.use('/ration', ration_Router);
app.use('/glj', GLJ_Router);

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

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

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');
});
app.listen(6060);


