var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
const fs = require("fs");
var formRouter = require('./routes/form');
var processRouter = require('./routes/camunda');
var proxy = require('express-http-proxy');
let config = require('./config');


var app = express();
app.all('*', function(req, res, next) {
　　//设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Origin", "http://www.zilber.cn");
　　//允许的header类型
    res.header('Access-Control-Allow-Headers', 'Content-type, Authorization');
　　//跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
　　//可选，用来指定本次预检请求的有效期，单位为秒。在此期间，不用发出另一条预检请求。
    res.header('Access-Control-Max-Age',1728000);//预请求缓存20天
    if (req.method === 'OPTIONS') {
      res.sendStatus(200); // 对于 OPTIONS 预检请求，返回200状态码并结束响应
      return;
    }
    next(); 
});
app.use(bodyParser.json({limit: '50000mb'}));
app.use(bodyParser.urlencoded({limit: '50000mb', extended: true}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

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

app.use('/process/form', formRouter);
app.use('/process', processRouter);
app.use('/ry', proxy(config.server.ryRedirect));


app.get('/',function(req,res){
  var url = req.url;
  //res.send("Hello word");
  // const filePath = path.join(__dirname,'./front-dist/index.html')
  const filePath = path.join(__dirname, '.', 'dist', 'index.html');
  console.log(filePath);
  fs.readFile( filePath , function(err,data){
    /*
    一参为文件路径
    二参为回调函数
    回调函数的一参为读取错误返回的信息，返回空就没有错误
    二参为读取成功返回的文本内容
    */
    if(err){
      res.writeHeader(404,{
      'content-type' : 'text/html;charset="utf-8"'
    });
    res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
    res.end();
    }else{
      res.writeHeader(200,{
      'content-type' : 'text/html;charset="utf-8"'
      });
      res.write(data);//将index.html显示在客户端
      res.end();
    }
  });
})


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// init();

module.exports = app;
