/**
 * Created by jimiz on 2017/4/1.
 */
var mongoose = require("mongoose");
var db = require("../db/project_db");
var subSchema = require("./bills_sub_schemas");
var Schema = mongoose.Schema;
var deleteSchema = require('../../../public/models/delete_schema');
var counter = require("../../../public/counter/counter.js");
var consts = require('./project_consts');
var projectConsts = consts.projectConst;
var commonConsts = consts.commonConst;

var rationSchema = new Schema({
    ID: Number,
    projectID: Number,
    billsItemID: Number,
    serialNo: Number,
    libID: Number,
    code: String,
    name: String,
    maskName: String,
    unit: String,
    quantity: String, // Decimal
    programID: Number,
    adjustState: String,
    content: String,
    rationProjName: String,
    comments: String,
    // 费用字段
    fees: [subSchema.feesSchema],
    // 标记字段
    flags: [subSchema.flagsSchema],
    deleteInfo: deleteSchema
});

var ration = db.model("ration", rationSchema, "ration");

var rationDAO = function(){};

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

rationDAO.prototype.save = function(projectId, datas, callback){
    var functions = [];
    var data;

    function saveOne(data) {
        return function (cb) {
            switch (doc.updateType) {
                case commonConsts.UT_UPDATE:
                    ration.update({ID: doc.ID}, doc, cb);
                    break;
                case commonConsts.UT_CREATE:
                    ration.create(doc, cb);
                    break;
                case commonConsts.UT_DELETE:
                /* 假删除
                 var item = new ration(doc);
                 item.remove(cb);
                 */
            }
        }
    }
    for (var i = 0; i < datas.length; i++){
        data = datas[i];
        functions.push(saveOne(data));
    }

    async.parallel(functions, callback);
};

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

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

module.exports = new rationDAO();