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

var rationGljItemSchema = mongoose.Schema({
    gljId: Number,
    consumeAmt: Number,
    proportion: Number //配合比，暂时无需使用，默认0
}, { _id: false });

var rationAssItemSchema = mongoose.Schema({
    name: String,
    assistID: Number,
    assistCode: String,
    stdValue: String,
    stepValue: String,
    decimal: Number,
    carryBit: String,
    minValue: String,
    maxValue: String
}, { _id: false });

var rationItemSchema = mongoose.Schema({
    ID:Number,
    code: String,
    name: String,
    unit: String,
    basePrice: Number,
    sectionId: Number,
    rationRepId: Number,
    caption: String,
    feeType: Number,
    rationGljList: [rationGljItemSchema],
    rationCoeList: Array,
    rationAssList: [rationAssItemSchema]
});
var rationItemModel = db.model("std_ration_lib_ration_items",rationItemSchema, "std_ration_lib_ration_items")
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(rationLibId, sectionId, updateItems, addItems, rIds, callback){
    var me = this;
    if (updateItems.length == 0 && rIds.length == 0) {
        me.addRationItems(rationLibId, sectionId, addItems, callback);
    } else {
        me.removeRationItems(rIds, function(err, message, docs) {
            if (err) {
                callback(true, "Fail to remove", false);
            } else {
                me.updateRationItems(rationLibId, sectionId, updateItems, function(err, results){
                    if (err) {
                        callback(true, "Fail to save", false);
                    } else {
                        if (addItems && addItems.length > 0) {
                            me.addRationItems(rationLibId, 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(repId, code,callback){
    rationItemModel.find({"rationRepId": repId, "code": {'$regex': code, $options: '$i'}, "$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.findRation = function (repId, keyword, callback) {
    var filter = {
        'rationRepId': repId,
        '$and': [{
            '$or': [{'code': {'$regex': keyword, $options: '$i'}}, {'name': {'$regex': keyword, $options: '$i'}}]
        }, {
            '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
        }]
    };
    rationItemModel.find(filter, function (err, data) {
        if (err) {
            callback(true, 'Fail to find ration', null);
        } else {
            callback(false, '', data);
        }
    })
}

rationItemDAO.prototype.getRationItem = function (repId, code, callback) {
    if (callback) {
        rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec()
            .then(function (result, err) {
                if (err) {
                    callback(1, '找不到定额“' + code +'”' , null);
                } else {
                    callback(0, '', result);
                }
            });
        return null;
    } else {
        return rationItemModel.findOne({rationRepId: repId, code: code, "$or": [{"isDeleted": null}, {"isDeleted": false}]}, '-_id').exec();
    }
};

rationItemDAO.prototype.addRationItems = function(rationLibId, 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;
                obj.rationRepId = rationLibId;
                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(rationLibId, 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;
                    if (rationLibId) filter.rationRepId = rationLibId;
                    filter.code = doc.code;
                }
                rationItemModel.update(filter, doc, cb);
            };
        })(items[i]));
    }
    async.parallel(functions, function(err, results) {
        callback(err, results);
    });
};

module.exports = new rationItemDAO()

