/**
 * Created by Tony on 2017/4/28.
 */
var mongoose = require("mongoose");
var dbm = require("../../../config/db/db_manager");
var db = dbm.getCfgConnection("rationRepository")
var async = require("async");
var Schema = mongoose.Schema;

var rationGljItemSchema = mongoose.Schema({
    gljId: Number,
    consumeAmt: Number,
    proportion: Number //配合比，暂时无需使用，默认0
}, { _id: false });
var rationItemSchema = mongoose.Schema({
    ID:Number,
    //以下是基于已有access库
    code: String,
    name: String,
    unit: String,
    basePrice: Number,
    sectionId: Number,
    caption: String,
    feeType: Number,
    rationGljList: [rationGljItemSchema]
});
var rationItemModel = db.model("rationItems",rationItemSchema, "rationItems")
var counter = require('../../../public/counter/counter');

var rationItemDAO = function(){};

rationItemDAO.prototype.getRationItemsBySection = function(sectionId,callback){
    rationItemModel.find({"sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
        if(err) callback(true, "Fail to get items", "")
        else callback(false,"Get items successfully", data);
    })
};
rationItemDAO.prototype.mixUpdateRationItems = function(sectionId, updateItems, addItems, rIds, callback){
    var me = this;
    if (updateItems.length == 0 && rIds.length == 0) {
        me.addRationItems(sectionId, addItems, callback);
    } else {
        me.removeRationItems(rIds, function(err, message, docs) {
            if (err) {
                callback(true, "Fail to remove", false);
            } else {
                me.updateRationItems(sectionId, updateItems, function(err, results){
                    if (err) {
                        callback(true, "Fail to save", false);
                    } else {
                        if (addItems && addItems.length > 0) {
                            me.addRationItems(sectionId, addItems, callback);
                        } else {
                            callback(false, "Save successfully", results);
                        }
                    }
                });
            }
        })
    }
};

rationItemDAO.prototype.removeRationItems = function(rIds,callback){
    if (rIds.length > 0) {
        rationItemModel.collection.remove({ID: {$in: rIds}}, null, function(err, docs){
            if (err) {
                callback(true, "Fail to remove", false);
            } else {
                callback(false, "Remove successfully", docs);
            }
        })
    } else {
        callback(false, "No records were deleted!", null);
    }
};

rationItemDAO.prototype.getRationItemsByCode = function(code,callback){
    //
};

rationItemDAO.prototype.addRationItems = function(sectionId, items,callback){
    if (items && items.length > 0) {
        counter.counterDAO.getIDAfterCount(counter.moduleName.rations, items.length, function(err, result){
            var maxId = result.value.sequence_value;
            var arr = [];
            for (var i = 0; i < items.length; i++) {
                var obj = new rationItemModel(items[i]);
                obj.ID = (maxId - (items.length - 1) + i);
                obj.sectionId = sectionId;
                arr.push(obj);
            }
            rationItemModel.collection.insert(arr, null, function(err, docs){
                if (err) {
                    callback(true, "Fail to save", false);
                } else {
                    callback(false, "Save successfully", docs);
                }
            })
        });
    } else {
        callback(true, "Source error!", false);
    }
};

rationItemDAO.prototype.updateRationItems = function(sectionId, items,callback){
    var functions = [];
    for (var i=0; i < items.length; i++) {
        functions.push((function(doc) {
            return function(cb) {
                var filter = {};
                if (doc.ID) {
                    filter.ID = doc.ID;
                } else {
                    filter.sectionId = sectionId;
                    filter.code = doc.code;
                }
                rationItemModel.update(filter, doc, cb);
            };
        })(items[i]));
    }
    async.parallel(functions, function(err, results) {
        callback(err, results);
    });
};

module.exports = new rationItemDAO()

