/**
 * Created by Tony on 2017/4/28.
 */
var mongoose = require("mongoose");
var async = require("async");
var rationItemModel = mongoose.model("std_ration_lib_ration_items");
var counter = require('../../../public/counter/counter');
const stdGljListModel = mongoose.model('std_glj_lib_gljList');

var rationItemDAO = function(){};

rationItemDAO.prototype.getRationItemsBySection = function(rationRepId, sectionId,callback){
    rationItemModel.find({"rationRepId": rationRepId, "sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]}, null, {sort: {code: 1}}, function(err,data){
        if(err) callback(true, "Fail to get items", "")
        else callback(false,"Get items successfully", data);
    })
};
rationItemDAO.prototype.getRationGljItemsBySection = async function(sectionId,callback){
    try{
        let rationItems = await rationItemModel.find({"sectionId": sectionId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]}, null, {sort: {code: 1}});
        for(let i = 0, len = rationItems.length; i < len; i++){
            let hint = '';
            let ration = rationItems[i];
            for(let j = 0, jLen = ration.rationGljList.length; j < jLen; j++){
                let rationGlj = ration.rationGljList[j];
                let glj = await stdGljListModel.find({ID: rationGlj.gljId, $or: [{isDeleted: null}, {isDeleted: false} ]}, '-_id code name unit');
                if(glj.length > 0){
                    let unitHint = '' + glj[0].code + ' ' + glj[0].name + '' + glj[0].unit + ' ' + rationGlj.consumeAmt + '</br>';
                    hint += unitHint;
                }
            }
            ration._doc.hint = hint;
        }
        callback(false,"Get items successfully", rationItems);
    }
    catch (err){
        callback(true, "Fail to get items", "")
    }
};
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.matchRation = function (repId, keyword, callback) {
    let filter = {
        'rationRepId': repId,
        'code': keyword,
        '$or': [{'isDeleted': {"$exists":false}}, {'isDeleted': null}, {'isDeleted': false}]
    };
    rationItemModel.findOne(filter, function (err, data) {
        callback(err, JSON.parse(JSON.stringify(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.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 = {
    Dao: new rationItemDAO(),
    Model: rationItemModel
};
//module.exports = new rationItemDAO()

