/**
 * Created by Tony on 2017/5/4.
 * 工料机的总库，根据不同定额库分类，参考原gljList表
 */

var mongoose = require("mongoose");
var async = require("async");
var gljTypeModel = mongoose.model("std_glj_lib_gljClass");
var gljItemModel = mongoose.model("std_glj_lib_gljList");
var repositoryMap = require('./repository_map').Dao;
var counter = require('../../../public/counter/counter');

var gljItemDAO = function(){};
gljItemDAO.prototype.getGljTypes = function(rationLibId, callback){
    gljTypeModel.find({"repositoryId": rationLibId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
        if(data.length) callback(false,data);
        else  if(err) callback("获取工料机类型错误！",false)
        else callback(false,false);
    })
};

gljItemDAO.prototype.getGljItemsByRep = function(repositoryId,callback){
    gljItemModel.find({"repositoryId": repositoryId},function(err,data){
        if(err) callback(true, "")
        else callback(false,data);
    })
};

gljItemDAO.prototype.getGljItemByType = function(repositoryId, type, callback){
    gljItemModel.find({"repositoryId": repositoryId, "gljType": type},function(err,data){
        if(err) callback(true, "")
        else callback(false, data);
    })
};

gljItemDAO.prototype.getGljItem = function(repositoryId, code, callback){
    gljItemModel.find({"repositoryId": repositoryId, "code": code},function(err,data){
        if(err) callback(true, "")
        else callback(false, data);
    })
};

gljItemDAO.prototype.getGljItems = function(gljIds, callback){
    gljItemModel.find({"ID": {"$in": gljIds}},function(err,data){
        if(err) callback(true, "")
        else callback(false, data);
    })
};

gljItemDAO.prototype.getGljItemsByCode = function(repositoryId, codes, callback){
    gljItemModel.find({"repositoryId": repositoryId,"code": {"$in": codes}},function(err,data){
        if(err) callback(true, "")
        else callback(false, data);
    })
};

gljItemDAO.prototype.mixUpdateGljItems = function(repId, updateItems, addItems, rIds, callback) {
    var me = this;
    if (updateItems.length == 0 && rIds.length == 0) {
        me.addGljItems(repId, addItems, callback);
    } else {
        me.removeGljItems(rIds, function(err, message, docs) {
            me.updateGljItems(repId, updateItems, function(err, results){
                if (err) {
                    callback(true, "Fail to update", false);
                } else {
                    if (addItems && addItems.length > 0) {
                        me.addGljItems(repId, addItems, callback);
                    } else {
                        callback(false, "Save successfully", results);
                    }
                }
            });
        });
    }
};

gljItemDAO.prototype.removeGljItems = function(rIds, callback) {
    if (rIds && rIds.length > 0) {
        gljItemModel.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);
    }
};

gljItemDAO.prototype.addGljItems = function(repId, items, callback) {
    if (items && items.length > 0) {
        counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, items.length, function(err, result){
            var maxId = result.sequence_value;
            var arr = [];
            for (var i = 0; i < items.length; i++) {
                var obj = new gljItemModel(items[i]);
                obj.ID = (maxId - (items.length - 1) + i);
                obj.repositoryId = repId;
                arr.push(obj);
            }
            gljItemModel.collection.insert(arr, null, function(err, docs){
                if (err) {
                    callback(true, "Fail to add", false);
                } else {
                    callback(false, "Add successfully", docs);
                }
            })
        });
    } else {
        callback(true, "No source", false);
    }
};

gljItemDAO.prototype.updateGljItems = function(repId, 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.repositoryId = repId;
                    filter.code = doc.code;
                }
                gljItemModel.update(filter, doc, cb);
            };
        })(items[i]));
    }
    async.parallel(functions, function(err, results) {
        callback(err, results);
    });
};

gljItemDAO.prototype.updateNodes = function(nodes, callback) {
    var functions = [];
    for (var i=0; i < nodes.length; i++) {
        functions.push((function(doc) {
            return function(cb) {
                gljTypeModel.update({ID: doc.ID}, doc, cb);
            };
        })(nodes[i]));
    }
    async.parallel(functions, function(err, results) {
        callback(err, results);
    });
};
gljItemDAO.prototype.removeNodes =  function(nodeIds, preNodeId, preNodeNextId, callback){
    var functions = [];
    if (preNodeId != -1) {
        functions.push((function(nodeId, nextId) {
            return function(cb) {
                gljTypeModel.update({ID: nodeId}, {"NextSiblingID": nextId}, cb);
            };
        })(preNodeId, preNodeNextId));
    }
    for (var i=0; i < nodeIds.length; i++) {
        functions.push((function(nodeId) {
            return function(cb) {
                gljTypeModel.update({ID: nodeId}, {"isDeleted": true}, cb);
            };
        })(nodeIds[i]));
    }
    async.parallel(functions, function(err, results) {
        callback(err, results);
    });
};

gljItemDAO.prototype.createNewNode = function(repId, lastNodeId, nodeData, callback) {
    return counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, 1, function(err, result){
        nodeData.repositoryId = repId;
        nodeData.ID = result.sequence_value;
        var node = new gljTypeModel(nodeData);
        node.save(function (err, result) {
            if (err) {
                callback(true, "章节树ID错误！", false);
            } else {
                if (lastNodeId > 0) {
                    gljTypeModel.update({ID: lastNodeId}, {"NextSiblingID": nodeData.ID}, function(err, rst){
                        if (err) {
                            callback(true, "章节树ID错误！", false);
                        } else {
                            callback(false, '', result);
                        }
                    });
                } else callback(false, '', result);
            }
        });
    });
};

module.exports = new gljItemDAO();

