/**
 * Created by zhang on 2018/2/5.
 */
let installation_facade = require('../facade/installation_facade');
let ration_installation_facade = require('../facade/ration_installation_facade');

let logger = require("../../../logs/log_helper").logger;
module.exports={
    updateInstallationFee:updateInstallationFee,
    updateRationInstallation:updateRationInstallation,
    applyRuleByIDs:applyRuleByIDs,
    resetToDefault:resetToDefault
}

async function updateRationInstallation(req, res) {
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let datas= await ration_installation_facade.updateRationInstallation(data);
        result.data=datas;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async function applyRuleByIDs(req, res) {
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let datas= await ration_installation_facade.applyRuleByIDs(data);
        result.data=datas;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async function  updateInstallationFee(req, res) {
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let datas= await installation_facade.updateInstallationFee(data.projectID,data.updateData);
        if(data.hasOwnProperty("rationInstallations")){
            await ration_installation_facade.updateFromInstallationFee(data.projectID,data.rationInstallations);
        }
        result.data=datas;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}

async function  resetToDefault(req, res) {
    let result={
        error:0
    }
    try {
        let data = req.body.data;
        data = JSON.parse(data);
        let returnData= await installation_facade.resetToDefault(data.projectID,data.installFees);
        if(data.rationInstallations && data.rationInstallations.length > 0){
          await ration_installation_facade.updateFromInstallationFee(data.projectID,data.rationInstallations);
        }
        result.data=returnData;
    }catch (err){
        logger.err(err);
        result.error=1;
        result.message = err.message;
    }
    res.json(result);
}