/**
 * Created by zhang on 2020/1/8.
 */

module.exports={
    rationNumberChecking,
    tenderNumberChecking,
    stateChecking,
};

const mongoose = require("mongoose");
const rationModel = mongoose.model("ration");
const pmFacade = require('../../pm/facade/pm_facade');
const online_logs = require('../../../logs/online_logs');
const UserModel = require('../../../modules/users/models/user_model');

async function rationNumberChecking(req, res, next) {
    if(req.session.systemSetting){
        let type = req.session.compilationVersion.indexOf("免费") == -1?"professional":"normal";
        let data = req.body.data;
        if(typeof data === 'object'){
            data = JSON.stringify(data);
        }
        data = JSON.parse(data);
        let projectID = data.projectID;
        let no = await rationModel.find({projectID:projectID}).count();
        if(no >= req.session.systemSetting[type].ration){
            let  result = {error:1,message:"您套用定额个数超限，请联系我们的客服人员。"};
            return  res.json(result);
        }
    }
    next();
}

async function tenderNumberChecking(req, res, next) {
    const data = JSON.parse(req.body.data);
    const tenderCount = data.tenderCount;
    if (tenderCount) {
        const tenderOverrun = await pmFacade.isTenderOverrun(tenderCount, req.session);
        if (tenderOverrun) {
            return res.json({
                error: 1,
                message: '您创建的项目个数超限，请联系我们的客服人员，或者导出建设项目保存到本地备份，删除云上数据。'
            });
        }
    }
    next();

}

function isAjax(req) {
    return req.headers['x-requested-with'] === 'XMLHttpRequest';
}

// 登录状态全局判断
async function stateChecking(req, res, next) {
    const url = req.originalUrl;
    if (url=="\/"|| /^\/login/.test(url) || /\.map|\.ico$/.test(url) || /^\/sms/.test(url) || /^\/cld\/(?!getCategoryStaff)/.test(url) || /^\/captcha/.test(url) || /^\/wap/.test(url)) {
        // 如果是登录页面或短信接口或cld接口则忽略判断数据
        next();
    } else {
        try {
            if (req.query.ssoID !== undefined && req.query.ssoID !== null && req.query.token !== undefined && req.query.token !== null) {
                delete req.session.sessionUser;
                delete req.session.sessionCompilation;
                return res.redirect('/login' + url);
            } else {
                // 判断session
                const sessionUser = req.session.sessionUser;
                if (!sessionUser) {
                    //处理 ajax 请求 session 过期问题
                    if (isAjax(req)) {
                        return res.json({ret_code: 99, ret_msg: '登录信息失效，请您重新登录'});
                    } else {
                        throw 'session error';
                    }
                } else {
                    const userModel = new UserModel();
                    const isValidToken = await userModel.checkToken(sessionUser.id, sessionUser.token);
                    if (!isValidToken) {
                        delete req.session.sessionUser;
                        delete req.session.sessionCompilation;
                        if (isAjax(req)) {
                            return res.json({ ret_code: 99, ret_msg: '' });
                        } else {
                            throw 'session token invalid';
                        }
                    }
                }
                res.locals.sessionUser = sessionUser;
            }
        } catch (error) {
            // 最后一个页面存入session
            req.session.lastPage = url;
            return res.redirect('/login');
        }
        next();
        await online_logs.saveOnlineTime(req);//记录登录时长
    }
}
