/**
 * Created by Tony on 2017/4/21.
 */
const mongoose = require('mongoose');
let async = require('async');
let moment = require('moment');
let counter = require('../../../public/counter/counter');
let rationRepositoryDao = require('./repository_map');
const rationChapterTreeModel = mongoose.model('std_ration_lib_ration_chapter_trees');
const rationModel = mongoose.model('std_ration_lib_ration_items');
const compleRationSectionTemp = mongoose.model('complementary_ration_section_templates');
var rationChapterTreeDAO = function(){};

rationChapterTreeDAO.prototype.sectionTemplateCount = async function (compilationId) {
    return await compleRationSectionTemp.find({compilationId}).count();
};

rationChapterTreeDAO.prototype.initSectionTemplate = async function (rationLibId, compilationId) {
    let sectionTempCount = await compleRationSectionTemp.find({compilationId}).count();
    if (sectionTempCount > 0) {
        await compleRationSectionTemp.remove({compilationId});
    }
    let bulks = [];
    let stdRationSection = await rationChapterTreeModel.find({rationRepId: rationLibId});
    for (let data of stdRationSection) {
        delete data._doc._id;
        data._doc.compilationId = compilationId;
        bulks.push({insertOne: {document: data}});
    }
    if (bulks.length > 0) {
        await compleRationSectionTemp.bulkWrite(bulks);
    }
};

rationChapterTreeDAO.prototype.getRationChapterTree = function(rationLibId,callback){
    rationChapterTreeModel.find({"rationRepId": rationLibId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
        if(data.length) callback(0,data);
        else  if(err) callback("获取定额树错误！",[])
        else callback(0,[]);
    })
}

rationChapterTreeDAO.prototype.getNewRationTreeID = function (callback) {
    counter.counterDAO.getIDAfterCount(counter.moduleName.rationTree, 1, function(err, result){
        if(err){
            callback(err, null);
        }
        else{
            callback(0, result.sequence_value);
        }
    });
};

rationChapterTreeDAO.prototype.getRationChapterTreeByRepId = function(repId,callback){
    rationChapterTreeModel.find({"rationRepId": repId, "$or": [{"isDeleted": null}, {"isDeleted": false} ]},function(err,data){
        if(data.length) callback(0,data);
        else  if(err) callback("获取定额树错误！",[])
        else callback(false,[]);
    })
}

rationChapterTreeDAO.prototype.createNewNode = function(lastOpr, libId, lastNodeId, nodeData,callback){
    counter.counterDAO.getIDAfterCount(counter.moduleName.rationTree, 1, function(err, result){
        nodeData.rationRepId = libId;
        nodeData.ID = result.sequence_value;
        var node = new rationChapterTreeModel(nodeData);
        async.parallel([
            function (cb) {
                node.save(function (err, result) {
                    if (err) {
                        cb("章节树ID错误！", false);
                    } else {
                        if (lastNodeId > 0) {
                            rationChapterTreeModel.update({ID: lastNodeId}, {"NextSiblingID": nodeData.ID}, function(err, rst){
                                if (err) {
                                    cb("章节树ID错误！", false);
                                } else {
                                    cb(false, result);
                                }
                            });
                        } else cb(false, result);
                    }
                });
            },
            function (cb) {
                rationRepositoryDao.updateOprArr({ID: libId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                    if(err){
                        cb(err);
                    }
                    else{
                        cb(null);
                    }
                });
            }
        ], function (err, result) {
            if(err){
                callback("章节树ID错误！", false);
            }
            else{
                callback(false, result[0]);
            }
        });
    });
},

    rationChapterTreeDAO.prototype.removeNodes = function(repId, lastOpr, nodeIds, preNodeId, preNodeNextId, callback){
        var functions = [];
        if (preNodeId != -1) {
            functions.push((function(nodeId, nextId) {
                return function(cb) {
                    rationChapterTreeModel.update({ID: nodeId}, {"NextSiblingID": nextId}, cb);
                };
            })(preNodeId, preNodeNextId));
        }
        for (var i=0; i < nodeIds.length; i++) {
            functions.push((function(nodeId) {
                return function(cb) {
                    rationChapterTreeModel.update({ID: nodeId}, {"isDeleted": true}, cb);
                };
            })(nodeIds[i]));
        }
        functions.push((function () {
            return function (cb) {
                rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                    if(err){
                        cb(err);
                    }
                    else{
                        cb(null);
                    }
                })
            }
        })());
        async.parallel(functions, function(err, results) {
            callback(err, results);
        });
    }

rationChapterTreeDAO.prototype.updateExplanation = function (lastOpr, repId, nodeId, explanation, callback) {
    rationChapterTreeModel.update({rationRepId: repId, ID: nodeId}, {$set: {explanation: explanation}}, function (err, result) {
        if(err){
            callback(err);
        }
        else{
            rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                callback(null);
            });
        }
    });
};
rationChapterTreeDAO.prototype.updateRuleText = function (lastOpr, repId, nodeId, ruleText, callback) {
    rationChapterTreeModel.update({rationRepId: repId, ID: nodeId}, {$set: {ruleText: ruleText}}, function (err, result) {
        if(err){
            callback(err);
        }
        else{
            rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                callback(null);
            });
        }
    });
};
rationChapterTreeDAO.prototype.updateSituation = function (lastOpr, repId, nodeId, situation, callback) {
    rationChapterTreeModel.update({rationRepId: repId, ID: nodeId}, {$set: {jobContentSituation: situation}}, function (err, result) {
        if(err){
            callback(err);
        }
        else{
            rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                callback(null);
            });
        }
    });
};
rationChapterTreeDAO.prototype.updateAnnoSituation = function (lastOpr, repId, nodeId, situation, callback) {
    rationChapterTreeModel.update({rationRepId: repId, ID: nodeId}, {$set: {annotationSituation: situation}}, function (err, result) {
        if(err){
            callback(err);
        }
        else{
            rationRepositoryDao.updateOprArr({ID: repId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                callback(null);
            });
        }
    });
};

rationChapterTreeDAO.prototype.updateNodes = function(lastOpr, updateData,callback){
    var functions = [];
    for (var i=0; i < updateData.length; i++) {
        //var md = new rationChapterTreeModel(nodes[i]);
        //md.isNew = false;
        functions.push((function(doc) {
            return function(cb) {
                if(doc.updateType === 'update' && !doc.updateData.isDeleted){
                    rationChapterTreeModel.update({rationRepId: doc.updateData.rationRepId, ID: doc.updateData.ID}, doc.updateData, function (err) {
                        if(err){
                            cb(err);
                        }
                        else {
                            cb(null);
                        }
                    });
                }
                else if(doc.updateType === 'update' && doc.updateData.isDeleted){
                    rationChapterTreeModel.remove({rationRepId: doc.updateData.rationRepId, ID: doc.updateData.ID}, function (err) {
                        if(err){
                            cb(err);
                        }
                        else {
                            rationModel.remove({sectionId: doc.updateData.ID}, function(err){
                                if(err){
                                    cb(err);
                                }
                                else {
                                    cb(null);
                                }
                            });

                        }
                    });
                }
                else if(doc.updateType === 'new'){
                    rationChapterTreeModel.create(doc.updateData, function (err) {
                        if(err){
                            cb(err);
                        }
                        else {
                            cb(null);
                        }
                    });
                }
            };
        })(updateData[i]));
    }
    if(updateData.length > 0){
        functions.push((function () {
            return function (cb) {
                rationRepositoryDao.updateOprArr({ID: updateData[0].updateData.rationRepId}, lastOpr, moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'), function (err) {
                    if(err){
                        cb(err);
                    }
                    else{
                        cb(null);
                    }
                })
            }
        })());
    }
    async.parallel(functions, function(err, results) {
        if(!err){
            err = 0;
        }
        callback(err, results);
    });
};

module.exports = new rationChapterTreeDAO()