/**
 * Created by jimiz on 2017/4/1.
 */
let mongoose = require("mongoose");
let async = require("async");
let counter = require("../../../public/counter/counter.js");
let consts = require('./project_consts');
let projectConsts = consts.projectConst;
let commonConsts = consts.commonConst;
let quantity_detial = require('../facade/quantity_detail_facade');

let ration = mongoose.model("ration");
let baseModel = require('./base_model');

class rationModel extends baseModel {
    constructor () {
        super(ration);
    }

    getData (projectID, callback) {
        ration.find({projectID: projectID}, '-_id', function(err, datas){//{'$or': [{projectID: projectID, deleteInfo: null}, {projectID: projectID, 'deleteInfo.deleted': {$in: [null, false]}}]}
            if (!err) {
                callback(0, projectConsts.RATION, datas);
            } else {
                callback(1, '', null);
            }
        });
    };

    save (user_id, datas, callback) {
        let functions = [];
        let data;
        function saveOne(doc) {
            return function (cb) {
                switch (doc.updateType) {
                    case commonConsts.UT_UPDATE:
                        ration.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID, deleteInfo: null}, doc.updateData, cb);
                        break;
                    case commonConsts.UT_CREATE:
                        ration.create(doc.updateData, cb);
                        break;
                    case commonConsts.UT_DELETE:
                        doc.updateData.deleteInfo = {deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
                        ration.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID}, doc.updateData,{multi: true},cb);
                        break;
                }
            }
        }


        for (let i = 0; i < datas.length; i++){
            data = datas[i];
            functions.push(saveOne(data));
            quantity_detial.quantityEditChecking(data,'ration',functions);
        }
        async.parallel(functions, callback);
    };

    getItemTemplate (callback) {
        let data = new ration;
        /* to do: 需要根据标准配置库填充fees和flags字段，是否需要更多的参数？ */
        callback(0, '', data);
    };

    allocIDs (IDstep, callback) {
        counter.counterDAO.getIDAfterCount(counter.moduleName.ration, IDStep, function(err, highID){
            let lowID = highID - IDStep + 1;
            callback(0, '', {lowID: lowID, highID: highID});
        });
    };
};

module.exports = new rationModel();