/**
 * Created by vian on 2017/3/20.
 */
var model = require("./bills_lib_model");
var counter = require("../../../public/counter/counter");
var StdBillsLib = model.stdBillsLibMod;
var Bills = model.billsMod;
var JobContent = model.jobContentMod;
var ItemCharacter = model.itemCharacterMod;

var fieldArr = ["code", "name", "unit", "ruleText", "Expression"];

var billsLibDao = function(){};

billsLibDao.prototype.getMaxNumber = function(gData, callback){
    var billsLibId = gData.billsLibId;
    var field = gData.field;
    if(field === 'jobs'){
        JobContent.find({billsLibId: billsLibId, deleted: false}).sort({code: -1}).limit(1).exec(function(err, result){
            if(err){
                callback(1, 'Error', null);
            }
            else {
                callback(0, '', result);
            }
        });
    }
    else if(field === 'items'){
        ItemCharacter.find({billsLibId: billsLibId, deleted: false}).sort({code: -1}).limit(1).exec(function(err, result){
            if(err){
                callback(1, 'Error', null);
            }
            else {
                callback(0, '', result);
            }
        });
    }
};
//----------StdBillsLib-------------------
billsLibDao.prototype.getABillsLib = function(data, callback){
    var billsLibId = data.billsLibId;
    StdBillsLib.find({billsLibId: billsLibId, deleted: false}, function(err, data){
        if(err){
            callback(1, 'Error', null);
        }
        else {
            callback(0, '', data);
        }
    });
};

billsLibDao.prototype.getStdBillsLib = function(data, callback){
    var userId = data.userId;
    StdBillsLib.find({userId: userId, deleted: false}, "-_id", function(err, data){
        if(err){
            callback(1, "Error", null);
        }
        else{
            callback(0, "", data);
        }
    })
};

billsLibDao.prototype.createStdBillsLib = function(clibData, callback){
    counter.counterDAO.getIDAfterCount(counter.moduleName.billsLib, 1, function(err, result){
        var billsLibId = result.value.sequence_value;
        var userId = clibData.userId;
        var billsLibName = clibData.name;
        var createDate = Date.now();
        var newStdBillsLib = {
            userId: userId,
            billsLibId: billsLibId,
            billsLibName: billsLibName,
            createDate: createDate,
            deleted: false
        };
        StdBillsLib.create(newStdBillsLib, function(err){
            if(err){
                callback(1, "Error", null);
            }
            else {
                StdBillsLib.find({billsLibId: billsLibId}, function(err, data){
                    if(err){
                        callback(1, "Error", null)
                    }
                    else {
                        callback(0, "", data);
                    }
                });
            }
        });
    });
};

billsLibDao.prototype.deleteStdBillsLib = function(billsLibId, callback){
    StdBillsLib.update({billsLibId: billsLibId}, {$set: {deleted: true}}, function(err){
        if(err){
            callback(1, 'Error');
        }
        else{
            callback(0, '');
        }
    });
};

billsLibDao.prototype.renameStdBillsLib = function(renameData, callback){
    var billsLibId = renameData.id;
    var renameVal = renameData.value;
    StdBillsLib.update({billsLibId: billsLibId}, {$set:{billsLibName: renameVal}}, function(err){
        if(err){
            callback(1, "Error");
        }
        else{
            callback(0, "");
        }
    });
};

billsLibDao.prototype.getStdBillsLibName = function(billsLibId, callback){
    StdBillsLib.find({billsLibId: billsLibId, deleted: false}, "-_id", function(err,  data){
        if(err){
            callback(1, "Error", null);
        }
        else {
            callback(0, "", data);
        }
    });
}
//----------------------------Bills---------------------
billsLibDao.prototype.getBills = function (billsLibId, callback) {
    Bills.find({billsLibId: billsLibId, deleted: false}, "-_id",  function(err, billsData){
        if(err){
            callback(1, "Error", null);
        }
        else{
            callback(0, "", billsData);
        }
    });
}

billsLibDao.prototype.createBills = function(cbillsData, callback){
    var newId = cbillsData.newId;
    var pid = cbillsData.ParentID;
    var nid = cbillsData.NextSiblingID;
    var billsLibId = cbillsData.billsLibId;
    var newBills = {
        ID: newId,
        ParentID: pid,
        NextSiblingID: nid,
        billsLibId: billsLibId,
        code: '',
        name: '',
        unit: '',
        ruleText: '',
        Expression: '',
        recharge:'',
        deleted: false
    };
    Bills.create(newBills, function(err){
        if(err){
            callback(1, "Error");
        }
        else{
            callback(0, "");
        }
    });
};


billsLibDao.prototype.updatePNId= function(upData, callback){
    var billsLibId = upData.billsLibId;
    var updateDatas = upData.updateData;
    var success = true;
    if(updateDatas.length > 0){
        updateDatas.forEach(function(data){
            if(data.ID.length >1){
                data.ID.forEach(function(id){
                    if(data.ParentID && data.NextSiblingID){
                        Bills.update({billsLibId: billsLibId, ID: id}, {$set: {ParentID: data.ParentID, NextSiblingID: data.NextSiblingID}}, function(err){
                            if(err){
                                callback(1, "Error")
                                success = false;
                            }
                        });
                    }
                    else if(data.ParentID && !data.NextSiblingID){
                        Bills.update({billsLibId: billsLibId, ID: id}, {$set: {ParentID: data.ParentID}}, function(err){
                            if(err){
                                callback(1, 'Error');
                                success = false;
                            }
                        });
                    }
                    else if(!data.ParentID && data.NextSiblingID){
                        Bills.update({billsLibId: billsLibId, ID: id}, {$set: {NextSiblingID: data.NextSiblingID}}, function(err){
                            if(err){
                                callback(1, 'Error');
                                success = false;
                            }
                        });
                    }
                });
            }
            else {
                if(data.ParentID && data.NextSiblingID){
                    Bills.update({billsLibId: billsLibId, ID: data.ID}, {$set: {ParentID: data.ParentID, NextSiblingID: data.NextSiblingID}}, function(err){
                        if(err){
                            callback(1, "Error")
                            success = false;
                        }
                    });
                }
                else if(data.ParentID && !data.NextSiblingID){
                    Bills.update({billsLibId: billsLibId, ID: data.ID}, {$set: {ParentID: data.ParentID}}, function(err){
                        if(err){
                            callback(1, 'Error');
                            success = false;
                        }
                    });
                }
                else if(!data.ParentID && data.NextSiblingID){
                    Bills.update({billsLibId: billsLibId, ID: data.ID}, {$set: {NextSiblingID: data.NextSiblingID}}, function(err){
                        if(err){
                            callback(1, 'Error');
                            success = false;
                        }
                    });
                }
            }
        });
    }
    if(success){
        callback(0, '');
    }
}

billsLibDao.prototype.updateBills = function(ubillsData, callback){
    var billsLibId = ubillsData.billsLibId;
    var updateId = ubillsData.updateId;
    var updateField = ubillsData.field;
    var updateData = ubillsData.data;
    if(updateField === "code"){
        Bills.update({billsLibId: billsLibId, ID: updateId}, {$set: {code: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else {
                callback(0, "");
            }
        });
    }
    else if(updateField === "name"){
        Bills.update({billsLibId: billsLibId, ID: updateId}, {$set: {name: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else {
                callback(0, "");
            }
        });
    }
    else if(updateField === "unit"){
        Bills.update({billsLibId: billsLibId, ID: updateId}, {$set: {unit: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else {
                callback(0, "");
            }
        });
    }
    else if(updateField === "ruleText"){
        Bills.update({billsLibId: billsLibId, ID: updateId}, {$set: {ruleText: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else {
                callback(0, "");
            }
        });
    }
    else if(updateField === "jobs"){
        Bills.update({billsLibId: billsLibId, ID: updateId}, {$addToSet: {jobs: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else {
                callback(0, "");
            }
        });
    }
    else if(updateField === "items"){
        Bills.update({billsLibId: billsLibId, ID: updateId}, {$addToSet: {items: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else {
                callback(0, "");
            }
        });
    }
}

billsLibDao.prototype.updateBillsArr = function(updateData, callback){
    var billsLibId = updateData.billsLibId;
    var updateId = updateData.updateId;
    var orgId = updateData.orgId;
    var newId = updateData.newId;
    var classify = updateData.classify;
    var type = updateData.type;
    var success = true;
    if(classify === 'jobs'){
        if(orgId && newId && type === 'update'){
            Bills.update({billsLibId: billsLibId, ID: updateId, jobs: orgId}, {$set: {'jobs.$': newId}}, function(err){
                if(err){
                    callback(1, 'Error');
                }
                else {
                    callback(0, '');
                }
            });
        }
        if(orgId && !newId && type === 'delete'){
            orgId.forEach(function(oid){
                Bills.update({billsLibId: billsLibId, ID: updateId}, {$pull: {jobs: oid}}, function(err){
                    if(err){
                        callback(1, 'Error');
                    }
                });
            });
        }
        //todo: test
        if(orgId && !newId && type === 'deleteAll'){
            updateId.forEach(function(uid){
                orgId.forEach(function(oid){
                    Bills.update({billsLibId: billsLibId, ID: uid}, {$pull: {jobs: oid}}, function(err){
                        if(err){
                            callback(1, 'Error');
                        }
                    });
                });
            });
        }
    }
    else if(classify === 'items'){
        if(orgId && newId && type === 'update'){
            Bills.update({billsLibId: billsLibId, ID: updateId, items: orgId}, {$set: {'items.$': newId}}, function(err){
                if(err){
                    callback(1, 'Error');
                }
                else {
                    callback(0, '');
                }
            });
        }
        if(orgId && !newId && type === 'delete'){
            orgId.forEach(function(oid){
                Bills.update({billsLibId: billsLibId, ID: updateId}, {$pull: {items: oid}}, function(err){
                    if(err){
                        callback(1, 'Error');
                    }
                });
            });
        }
        if(orgId && !newId &&  type === 'deleteAll'){
            updateId.forEach(function(uid){
                orgId.forEach(function(oid){
                    Bills.update({billsLibId: billsLibId, ID: uid}, {$pull: {items: oid}}, function(err){
                        if(err){
                            callback(1, 'Error');
                        }
                    });
                });
            });
        }
    }
};

billsLibDao.prototype.pasteBills = function(pData, callback){
    var datas = pData.datas;
    datas.forEach(function(data){
        Bills.update({billsLibId: data.billsLibId, ID: data.ID}, {$set: {code: data.code, name: data.name, unit: data.unit, ruleText: data.ruleText}}, function(err){
            if(err){
                callback(1, 'Error');
            }
        });
    });
}

billsLibDao.prototype.updateRecharge = function(uData, callback){
    var billsLibId = uData.billsLibId;
    var updateIds = uData.updateIds;
    var data = uData.data;
    var success = true;
    updateIds.forEach(function(id){
        Bills.update({billsLibId: billsLibId, ID: id}, {$set: {recharge: data}}, function(err){
            if(err){
                callback(1, 'Error');
                success = false;
            }
        });
    });
    if(success){
        callback(0, '');
    }
};

billsLibDao.prototype.deleteBills = function(delData, callback){
    var deleteIds = delData.deleteIds;
    var billsLibId = delData.billsLibId;
    var success = true;
    if(deleteIds){
        deleteIds.forEach(function(delId){
            Bills.update({billsLibId: billsLibId, ID: delId}, {$set: {deleted: true}}, function(err){
                if(err){
                    success = false;
                    callback(1, 'Error');
                }
            });
        });
        if(success){
            callback(0, '');
        }
    }
}

//--------------JobContent------------------

billsLibDao.prototype.getJobContent = function(gJobData, callback){
    var billsLibId = gJobData.billsLibId;
    JobContent.find({billsLibId: billsLibId, deleted: false}, '-_id').sort({code: 1}).exec(function(err, result){
        if(err){
            callback(1, 'Error', null);
        }
        else {
            callback(0, '', result);
        }
    });
}

billsLibDao.prototype.createJobContent = function(cJobData, callback){
    var field = cJobData.field;
    var data = cJobData.data;
    var billsLibId = cJobData.billsLibId;
    var serialNo = cJobData.serialNo;
    counter.counterDAO.getIDAfterCount(counter.moduleName.billsLib, 1, function(err, result){
        var id = result.value.sequence_value;
        var newJobContent;
            newJobContent = {
                id: id,
                billsLibId: billsLibId,
                code: serialNo,
                content: data,
                deleted: false
            }
        JobContent.create(newJobContent, function(err){
            if(err){
                callback(1, "Error", null);
            }
            else{
                callback(0, "", id);
            }
        });
    });
}

billsLibDao.prototype.updateJobContent = function(uJobData, callback){
    var field = uJobData.field;
    var updateData = uJobData.data;
    var updateid = uJobData.updateId;
    if(field == "code"){
        JobContent.update({id: updateid}, {$set: {code: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else{
                callback(0, "");
            }
        });
    }
    else if(field == "content"){
        JobContent.update({id: updateid}, {$set: {content: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else{
                callback(0, "");
            }
        });
    }
}

billsLibDao.prototype.deleteJobContent = function(data, callback){
    var delIds = data.ids;
    var success = true;
    delIds.forEach(function(id){
        /*JobContent.remove({id: id}, function(err){
            if(err){
                callback(1, "Error");
            }
        });*/
        JobContent.update({id: id}, {$set: {deleted: true}}, function(err){
            if(err){
                success = false;
                callback(1, 'Error');
            }
        });
    });
}


//----------------------ItemCharacter---------------------
billsLibDao.prototype.getItemCharacter = function(gdata, callback){
    var billsLibId = gdata.billsLibId;
    ItemCharacter.find({billsLibId: billsLibId, deleted: false}, '-_id').sort({code: 1}).exec(function(err, result){
        if(err){
            callback(1, 'Error', null);
        }
        else {
            callback(0, '', result);
        }
    });
}

billsLibDao.prototype.createItemCharacter = function(cItemData, callback){
    var field = cItemData.field;
    var data = cItemData.data;
    var billsLibId = cItemData.billsLibId;
    var serialNo = cItemData.serialNo;
    var newItemCharacter;
    counter.counterDAO.getIDAfterCount(counter.moduleName.billsLib, 1, function(err, result){
        var id = result.value.sequence_value;
            newItemCharacter = {
                id: id,
                billsLibId: billsLibId,
                content: data,
                code: serialNo,
                deleted: false
            }
        ItemCharacter.create(newItemCharacter, function(err){
            if(err){
                callback(1, "Error", null);
            }
            else{
                callback(0, "", id);
            }
        });
    });
}

billsLibDao.prototype.updateItemCharacter = function(uItemData, callback){
    var field = uItemData.field;
    var updateData = uItemData.data;
    var id = uItemData.updateId;
    if(field === "code"){
        ItemCharacter.update({id: id}, {$set: {code: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else{
                callback(0, "");
            }
        });
    }
    else if(field === "content"){
        ItemCharacter.update({id: id}, {$set: {content: updateData}}, function(err){
            if(err){
                callback(1, "Error");
            }
            else{
                callback(0, "");
            }
        });
    }
};

billsLibDao.prototype.updateValue = function(uData, callback){
    var type = uData.type;
    var updateId = uData.updateId;
    var data = uData.data;
    var deleteCodes = uData.deleteCodes;
    if(type === 'create'){
        ItemCharacter.update({id: updateId}, {$addToSet: {itemValue: data}}, function(err){
            if(err){
                callback(1, 'Error');
            }
            else{
                callback(0, '');
            }
        });
    }
    else if(type === 'update'){
        if(data.field === 'code'){
            ItemCharacter.update({id: updateId,  'itemValue.code': data.code}, {$set: {'itemValue.$.code': data.newData}}, function(err){
                if(err){
                    callback(1, 'Error');
                }
                else{
                    callback(0, '');
                }
            });
        }
        else {
            ItemCharacter.update({id: updateId,  'itemValue.code': data.code}, {$set: {'itemValue.$.value': data.newData}}, function(err){
                if(err){
                    callback(1, 'Error');
                }
                else{
                    callback(0, '');
                }
            });
        }
    }
    //delete
    else {
        if(deleteCodes.length > 0){
            deleteCodes.forEach(function(code){
                ItemCharacter.update({id: updateId}, {$pull: {itemValue: {code: code}}}, function(err){
                    if(err){
                        callback(1, 'Error');
                    }
                });
            });
        }
    }
};

billsLibDao.prototype.deleteItemCharacter = function(data, callback){
    var delIds = data.ids;
    var success = true;
    delIds.forEach(function(id){
        /*ItemCharacter.remove({id: id}, function(err){
            if(err){
                callback(1, "Error");
            }
        });*/
        ItemCharacter.update({id: id}, {$set: {deleted: true}}, function(err){
            if(err){
                success = false;
                callback(1, 'Error');
            }
        });
    });
}
//


module.exports = new billsLibDao();
