var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');

var restRouter = require('./routes/restRouter');
var loginRouter = require('./routes/loginRouter');
var businessRouter = require('./routes/businessRouter');
var pageRouter = require('./routes/pageRouter');
var editRouter=require('./routes/editRouter');
var model=require('./util/model');
require('./util/string');

var app = express();

//模板引擎
var ejs=require('ejs');
app.set('views', path.join(__dirname, 'views/'));
app.engine('html',ejs.__express);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 使用 session 中间件
app.use(session({
  secret: 'secret', // 对session id 相关的cookie 进行签名
  resave: true,
  saveUninitialized: false, // 是否保存未初始化的会话
  cookie: {
    maxAge: 1000 * 60 * 60*8, // 设置 session 的有效时间，单位毫秒
  },
  name:require('./application.json').session_name
}));

//拦截器对登录人进行操作进行拦截
app.use(function (req, res, next) {
  console.log(req.session.user);
  var url = req.originalUrl;
  if (url == "/login" || url == "/logout" || url == "/validateuser") { //登录不拦截
    next();
  } else { //开始拦截
    if (req.session.user) {
      next();
    } else if (req.headers["x-requested-with"] == "XMLHttpRequest") { //ajax的请求返回json提醒
      res.json({
        resultStatus: model.resultStatus.expired
      });
    } else { //非ajax的请求调转登录页
      // res.redirect('/login');
      res.redirect('/login');
    }
  }
});


//restful服务
app.use('/rest', restRouter);
app.use('/edit', editRouter);
app.use('/pagedetail', pageRouter);
app.use('/', loginRouter);
app.use('/business', businessRouter);
app.use('/localx', require("./routes/localRouter"));
app.use('/export', require("./routes/exportRouter"));

// 错误捕获
app.use(function (err,x, req, res, next) {
  // res.json({
  //   resultStatus: model.resultStatus.error(err)
  // });
  res.json(err);
});

module.exports = app;
