const express = require('express');
const http = require('http');
const path = require('path');
const config = require('config');

// middlewares
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const timeInterval = config.get('timeInterval');

const scheduleproc = require('./lib/scheduleproc');

var app = express();

var login = require('./routers/login');
var pay = require('./routers/pay');
var tools = require('./routers/tools');
var main = require('./routers/main');
var data_service = require('./routers/data_service');


//X-Frame-Options: Allow-From http://www.growingio.com
app.use('*', function (req, res, next) {
    res.setHeader('X-Frame-Options', 'ALLOW-FROM https://www.growingio.com');
    next();
})


// 给app配置bodyParser中间件
// 通过如下配置再路由种处理request时，可以直接获得post请求的body部分
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const aes = require('./lib/aes');
const token = require('./lib/token')
app.use(function (req, res, next) {

    if (req.body.data) {
        try {
            req.body = aes.aesDecrypt(req.body.data)
            if (!req.body) {
                return res.send({code: 199, msg: '系统错误'})
            }
            req.body = JSON.parse(req.body)
        } catch (e) {
            console.log(e)
            return res.send({code: 199, msg: '系统错误'})
        }
    }
    // if (!/login/.test(req.path)) {
    //     try {
    //         let test = token.decode(req.headers.authorization)
    //         if (test) {
    //             req.body.userId = test.userId
    //         }
    //     }catch(e) {
    //         return res.send({code: -1, msg: '无效的authorization token'})
    //     }
    // }
    console.log(req.path, ': ', req.body)
    next()
})

// 注册路由
app.use('/login', login);
app.use('/tools', tools);
app.use('/data', main);
app.use('/pay', pay);
app.use('/dataService', data_service);


const httpPort = config.get('httpPort')

var Server = http.createServer(app);
Server.listen(httpPort, function () {
    console.log((new Date()) + ' server start http server and listen on: ' + JSON.stringify(Server.address()));
});


// 定时清理日志任务
scheduleproc.BeginCleanLogWork(timeInterval);