var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var cookierParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');
var settings = require('./settings');
var System = require('../base/system');
var routes = require('./routes');
const logCtl=System.getObject("web.common.oplogCtl");
const clientRedis= System.getObject("util.redisClient").client;
//const tm=System.getObject("db.taskManager");
module.exports = function (app) {
    app.set('port', settings.port);
    app.set('views', settings.basepath + '/app/front/entry');
	  app.set('view engine', 'ejs');
    app.use(methodOverride());
		app.use(cookierParser());
		app.use(bodyParser.json({limit:'50mb'}));
		app.use(bodyParser.urlencoded({limit:'50mb',extended:true}));
    routes(app);//初始化路由
    app.use(express.static(path.join(settings.basepath, '/app/front/entry/public')));
    app.all('*',function (req, res, next) {
			  req.objs=System;
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
        res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
        // res.header('Access-Control-Allow-Credentials', 'true');
        if (req.method == 'OPTIONS') {
          res.send(200); /让options请求快速返回/
        }
        else {
          next();
        }
　});
  if(settings.env=="dev"){
    app.use(session(
      {
        name:'pmsid',
        cookie: {maxAge: 3600000},
        rolling:true,
        resave: false,
        saveUninitialized: false,
        secret: 'uwotm8',
        store: new RedisStore({
            client:clientRedis,
        }),
    }));
  }else{
  app.use(session(
    {
      name:'pmsid',
      cookie: {maxAge: 3600000,domain:'track.gongsibao.com'},
      rolling:true,
      resave: false,
      saveUninitialized: false,
      secret: 'uwotm8',
      store: new RedisStore({
          client:clientRedis,
      }),
  }));
  }
  	// development only
    if ('development' == app.get('env')) {
      app.use(errorHandler());
    }else{
        app.use(function(err,req,res){
            console.log("prod error handler................................>>>>>>>>>>>>>>>>>");
						console.log(err);
						logCtl.error({
							 optitle:"environment 调用异常error:",
							 op:classPath+"/"+methodName,
							 content:e.toString(),
							 clientIp:System.get_client_ip(req),
							 agent:req.headers["user-agent"],
						 });
						//logerApp.error("prod error handler",err);
            res.send("link admin");
        });
    }

};
