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, bpostatsid');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    // res.header('Access-Control-Allow-Credentials', 'true');
    res.header('content-type', 'text/html;charset=UTF-8');
    if (req.method == 'OPTIONS') {
      res.send(200); //让options请求快速返回/
    }
    else {
      next();
    }
  });
  if (settings.env == "dev") {
    app.use(session(
      {
        name: 'xggadminsid',
        cookie: { maxAge: 3600000 },
        rolling: true,
        resave: false,
        saveUninitialized: false,
        secret: 'uwotm8',
        store: new RedisStore({
          client: clientRedis,
        }),
      }));
  } else {
    app.use(session(
      {
        name: 'xggadminsid',
        cookie: { maxAge: 3600000 },
        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: req.url,
        content: e.toString(),
        clientIp: system.get_client_ip(req),
        agent: req.headers["user-agent"],
      });
      //logerApp.error("prod error handler",err);
      res.send("link index");
    });
  }

};
