/**
 * Created by zhang on 2018/2/24.
 */
let mongoose = require('mongoose');
let rationInstallationModel = mongoose.model('ration_installation');
let consts = require('../models/project_consts');
let projectConsts = consts.projectConst;

module.exports={
    updateRationInstallation:updateRationInstallation,
    applyRuleByIDs:applyRuleByIDs,
    updateFromInstallationFee:updateFromInstallationFee,
    getData:getData,
    deleteByRation:deleteByRation
};

async function updateRationInstallation(data){
    if(data.projectID&&data.ID){
        let result = await rationInstallationModel.findOneAndUpdate({'projectID':data.projectID,'ID':data.ID},data);
        return result
    }else {
        throw  new Error('项目ID或者ID为空，更新失败!');
    }
}

async function applyRuleByIDs(data){
    console.log(data);
    if(data.projectID&&data.IDs){
        return rationInstallationModel.update({projectID: data.projectID, ID:{'$in':data.IDs}},{ruleId:data.ruleId,unifiedSetting:0},{multi: true});
    }else {
        throw  new Error('项目ID或者ID为空，更新失败!');
    }
    //ration.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID}, doc.updateData,{multi: true},cb);

}

async function updateFromInstallationFee(projectID,rationInstallations) {
    let tasks = [];
    for (let ri of rationInstallations){
        let task = {
            updateOne:{
                filter:{
                    ID:ri.ID,
                    projectID:projectID
                },
                update :ri.doc
            }
        };
        tasks.push(task);
    }
    if(tasks.length>0){
        await rationInstallationModel.bulkWrite(tasks);
    }
}
function deleteByRation(data) {
    return function (callback) {
        rationInstallationModel.deleteMany({projectID: data.projectID, rationID: data.ID},(err,result)=>{
            commonCallback(callback,result,err);
        });
    }
}

function commonCallback(callback,result,err) {
    if(err){
        callback(err,'');
    }else {
        callback(null,result);
    }
}


function getData(projectID, callback) {
    rationInstallationModel.find({'projectID': projectID}, (err, datas) => {
        if (err) {
            callback(1, '', null);
        } else {
            callback(0, consts.projectConst.RATION_INSTALLATION, datas);
        }
    })
}