/**
 * Created by jimiz on 2017/4/9.
 */
let rationData = require('../models/ration');
let ration_glj_facade = require('../../ration_glj/facade/ration_glj_facade');
let ration_ass_facade = require('../../ration_glj/facade/ration_ass_facade');
let ration_facade = require('../facade/ration_facade');
let bill_facade = require('../facade/bill_facade');
let project_facade = require("../facade/project_facade");
let logger = require("../../../logs/log_helper").logger;
const GLJController = require("../../glj/controllers/glj_controller");
const pmFacade = require('../../pm/facade/pm_facade');
const { ShareLibType } = require('../../../public/common_constants');
const compleRationLib = 'compleRationLib';
let controller = {
    insertGLJAsRation:async function (req){
        let data = req.body.data;
        data = JSON.parse(data);
        return await ration_glj_facade.insertGLJAsRation(data,req.session.sessionCompilation);
    },
    replaceRations:async function (req) {
        let data = req.body.data;
        data = JSON.parse(data);
        let userID = req.session.sessionUser.id;
        const compilationID = req.session.sessionCompilation._id;
        if (data.libIDs && !data.libIDs.includes(compleRationLib)) {
            const rationLibUsers = await pmFacade.getReceiveLibList(userID, compilationID, ShareLibType.RATION_LIB);
            data.libIDs.push(compleRationLib);
            rationLibUsers.forEach(user => {
                data.libIDs.push(`${compleRationLib}*${user._id}`);
            });
        }
        return await ration_facade.replaceRations(userID,data,req.session.sessionCompilation);
    },
    addNewRation:async function(req) {
        let data = req.body.data;
        if(typeof data === 'object'){
            data = JSON.stringify(data);
        }
        data = JSON.parse(data);
        data.sessionUserID = req.session.sessionUser.id;
        let result = await ration_facade.addNewRation(data,req.session.sessionCompilation);
        //合并取项目工料机数据的情求，用于刷新项目工料机数据，当有添加、替换项目工料机的情况，才需要刷新
       /* if(result.ration_gljs && result.ration_gljs.length > 0 && data.newData){
            result.projectGLJDatas =  await getProjectGLJData(data.newData.projectID);
        }*/
        return result;
    },
    addMultiRation: async function (req) {
        let data = req.body.data;
        if(typeof data === 'object'){
            data = JSON.stringify(data);
        }
        data = JSON.parse(data);
        return await ration_facade.addMultiRation(data.newDatas,req.session.sessionCompilation);
    },
    getSameSectionRations:async function(req){//取同个章节相邻的定额
        let data = req.body.data;
        data = JSON.parse(data);
        return await ration_facade.getSameSectionRations(data,req.session.sessionUser.id, req.session.sessionCompilation._id);
    },
    //取定额默认的取费专业
    getDefaultProgramID:async function(req){
        let data = req.body.data;
        data = JSON.parse(data);
        data.userID = req.session.sessionUser.id;
        data.compilationId = req.session.sessionCompilation._id;
        return await ration_facade.getDefaultProgramID(data);


    },
    //应用定额关联子目
    applyTemplate:async function(req){
        let data = req.body.data;
        data = JSON.parse(data);
        let updateDatas =[];
        let applyTasks = [
            ration_facade.addMultiRation(data.rations.create,req.session.sessionCompilation),//先生成新定额
            bill_facade.createNewBills(data.bills.create),
            ration_facade.deleteMultiRation(data.rations.delete)
        ];
        //整理更新的数据，调用一个方法更新
        updateDatas.push(data.ration_template);
        if(data.rations.update.length > 0)  prepareUpdateNodes(data.rations.update,updateDatas,"ration");
        if(data.bills.update.length > 0)  prepareUpdateNodes(data.bills.update,updateDatas,"bills");
        applyTasks.push(project_facade.updateNodes(updateDatas));
        let [rationResult,billsResult,deleteResult,updates] = await Promise.all(applyTasks);
        return {rationResult:rationResult,billsResult:billsResult,updateDatas:updateDatas};
    },
    //更新辅助定额
    updateRationAss:async function(req){
        let data = req.body.data;
        data = JSON.parse(data);
        return ration_ass_facade.updateRationAss(data);
    },
    //勾选定额调整系数
    updateCoeAdjust:async function(req){
        let data = req.body.data;
        data = JSON.parse(data);
        let result = await ration_facade.updateCoeAdjust(data,req.session.sessionCompilation);
        //合并取项目工料机数据的情求，用于刷新项目工料机数据，当有添加、替换项目工料机的情况，才需要刷新
     /*   if(result.add.length > 0 || result.replace.length > 0){
            result.projectGLJDatas =  await getProjectGLJData(data.projectID);
        }*/
        return result;
    }
};

async function getProjectGLJData(projectID) {
    let gljController = new GLJController();
    let responseData = await gljController.getProjectGLJsByProjectID(projectID);
    return responseData.data;
}

function prepareUpdateNodes(datas,nodes,type) {
    for(let d of datas){
        nodes.push({type:type,data:d});
    }

}



//统一回调函数
let callback = function(req, res, err, message, data){
    res.json({error: err, message: message, data: data});
};

module.exports = {
    getData: function(req, res){
        var data = JSON.parse(req.body.data);
        rationData.getData(data.projectId, function(err, message, rationList){
            if (err === 0) {
                callback(req, res, err, message, rationList);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },

    getItemTemplate: function(req, res){
        //var data = JSON.parse(req.body.data);
        rationData.getItemTemplate(function(err, message, rationItem){
            if (billsItem) {
                callback(req, res, err, message, rationItem);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },

    allocIDs: function(req, res){
        rationData.allocIDs(function(err, message, data){
            if (err) {
                callback(req, res, err, message, data);
            } else {
                callback(req, res, err, message, null);
            }
        });
    },
    action:async function(req,res){//自动跳转到URL对应的controller方法
        let result={
            error:0
        }
        try {
            let functionName = req.url.replace(/\//g,"");
            result.data = controller[functionName]?await controller[functionName](req):"";
        }catch (err){
            logger.err(err);
            result.error=1;
            result.message = err.message;
        }
        res.json(result);
    }
};




