/**
 * Created by Mai on 2017/4/14.
 * 清单模板，新建项目使用
 */
let counter = require("../../../public/counter/counter.js");
let mongoose = require('mongoose');
let BillsTemplates = mongoose.model('temp_bills');
let BillsTemplateDAO = function(){};

BillsTemplateDAO.prototype.getTemplate = function (type, callback) {
    if (callback) {
        BillsTemplates.find({'$or': [{tempType: type, deleteInfo: null}, {tempType: type, 'deleteInfo.deleted': {$in: [null, false]}}]}, '-_id').exec()
            .then(function (result, err) {
                if (err) {
                    callback(1, '找不到模板', null);
                } else {
                    callback(0, '', result);
                }
            });
        return null;
    } else {
        return BillsTemplates.find({'$or': [{tempType: type, deleteInfo: null}, {tempType: type, 'deleteInfo.deleted': {$in: [null, false]}}]}, '-_id').exec();
    }
};
BillsTemplateDAO.prototype.updateTemplate = function (userID, tempType, datas, callback) {
    var data, project, updateLength = 0, hasError = false, deleteInfo = null;
    var updateAll = function (err) {
        if (!err){
            updateLength += 1;
            if (updateLength === datas.length) {
                callback(0, '', datas);
            }
        } else {
            hasError = true;
            callback(1, '升级数据出错', null);
        }
    };
    if (datas){
        for (var i = 0; i < datas.length && !hasError; i++){
            data = datas[i];
            if (data.type === 'update') {
                BillsTemplates.update({tempType: tempType, ID: data.data.ID}, data.data, updateAll)
            } else if (data.type === 'new') {
                data.data['tempType'] = tempType;
                newProject = new BillsTemplates(data.data);
                newProject.save(updateAll);
            } else if (data.type === 'delete') {
                deleteInfo = {};
                deleteInfo['deleted'] = true;
                deleteInfo['deleteDateTime'] = new Date();
                deleteInfo['deleteBy'] = userID;
                BillsTemplates.update({ID: data.data.ID}, {deleteInfo: deleteInfo}, updateAll);
            } else {
                hasError = true;
                callback(1, '升级数据出错', null)
            }
        }
    }
};
BillsTemplateDAO.prototype.getNewBillsTemplateID = function (count, callback) {
    counter.counterDAO.getIDAfterCount(counter.moduleName.template_bills, count, function (err, result) {
        var highID = result.sequence_value;
        if (!err) {
            callback(0, '', {lowID: highID - count + 1, highID: highID});
        } else {
            callback(1, '获取主键失败', null);
        }
    });
}

module.exports = new BillsTemplateDAO();
