/**
 * Created by Mai on 2017/1/18.
 */
var counter = require("../../../public/counter/counter.js");

var newProjController = require('../controllers/new_proj_controller');
var copyProjController = require('../controllers/copy_proj_controller');

var mongoose = require("mongoose");

var dbm = require("../../../config/db/db_manager");
var db = dbm.getCfgConnection("usersManages");
var Schema = mongoose.Schema;
var deleteSchema = require('../../../public/models/delete_schema');
var ProjectSchema = new Schema({
    "ID": Number,
    "ParentID": Number,
    "NextSiblingID": Number,
    "userID": Number,
    "name": String,
    "projType": String,
    "recentDateTime": Date,
    "createDateTime": Date,
    "deleteInfo": deleteSchema,
    'fullFolder': Array
});
var Projects = db.model("projects", ProjectSchema);

var ProjectsDAO = function(){};

ProjectsDAO.prototype.getUserProjects = function(userId, callback){
    Projects.find({'$or': [{'userID': userId, 'deleteInfo': null}, {'userID': userId, 'deleteInfo.deleted': {'$in': [null, false]}}]}, '-_id', function(err, templates){
        if (err) {
            callback(1, 'Error', null);
        } else {
            callback(0, '', templates);
        }
    });
};

ProjectsDAO.prototype.getUserProject = function (userId, ProjId, callback) {
    Projects.findOne({userID: userId, ID: ProjId}, '-_id', function(err, template){
        if (err) {
            callback(1, '找不到标段数据', null);
        } else {
            callback(0, '', template);
        }
    });
}

ProjectsDAO.prototype.updateUserProjects = function(userId, datas, callback){
    var data, project, updateLength = 0, hasError = false, deleteInfo = null, tempType = 1, i, newProject;
    var updateAll = function (err) {
            if (!err){
                updateLength += 1;
                if (updateLength === datas.length) {
                    callback(0, '', datas);
                }
            } else {
                hasError = true;
                callback(1, '提交数据出错.', null);
            }
        };
    if (datas){
        for (i = 0; i < datas.length && !hasError; i++){
            data = datas[i];
            if (data.updateType === 'update') {
                Projects.update({userID: userId, ID: data.updateData.ID}, data.updateData, updateAll)
            } else if (data.updateType === 'new') {
                data.updateData['userID'] = userId;
                if (data.updateData.projType === 'Tender') {
                    data.updateData['createDateTime'] = new Date();
                }
                newProject = new Projects(data.updateData);
                newProject.save(function (err, result) {
                    if (!err && result._doc.projType === 'Tender') {
                        newProjController.copyTemplateData(tempType, newProject.ID, updateAll);
                    } else {
                        updateAll(err);
                    }
                });
            } else if (data.updateType === 'delete') {
                deleteInfo = {};
                deleteInfo['deleted'] = true;
                deleteInfo['deleteDateTime'] = new Date();
                deleteInfo['deleteBy'] = userId;
                data.updateData['deleteInfo'] = deleteInfo;
                Projects.update({userID: userId, ID: data.updateData.ID}, data.updateData, updateAll);
            } else {
                hasError = true;
                callback(1, '提交数据错误.', null);
            }
        }
    }
};
ProjectsDAO.prototype.copyUserProjects = function (userId, datas, callback) {
    var data, project, updateLength = 0, hasError = false, deleteInfo = null, tempType = 1, i;
    var updateAll = function (err) {
        if (!err){
            updateLength += 1;
            if (updateLength === datas.length) {
                callback(0, '', datas);
            }
        } else {
            hasError = true;
            callback(1, '提交数据出错.', null);
        }
    };
    if (datas) {
        for (i = 0; i < datas.length && !hasError; i++) {
            data = datas[i];
            if (data.updateType === 'update') {
                Projects.update({userID: userId, ID: data.updateData.ID}, data.updateData, updateAll)
            } else if (data.updateType === 'copy') {
                data.updateData['userID'] = userId;
                if (data.updateData.projType === 'Tender') {
                    data.updateData['createDateTime'] = new Date();
                };
                newProject = new Projects(data.updateData);
                newProject['srcProjectId'] = data.srcProjectId;
                newProject.save(function (err, result) {
                    if (!err && result._doc.projType === 'Tender') {
                        copyProjController.copyProjectData(this.newProject.srcProjectId, result._doc.ID, updateAll);
                    } else {
                        updateAll(err);
                    }
                });
            } else {
                haseError = true;
                callback(1, '提交数据错误', null);
            }
        }
    }
};

ProjectsDAO.prototype.rename = function (userId, projectId, newName, callback){
    Projects.update({userID: userId, ID: projectId}, {name: newName}, function(err){
       if (err){
           callback(1, '项目不存在.');
       } else {
           callback(0, '');
       }
    });
};

ProjectsDAO.prototype.beforeOpenProject = function (userId, projectId, updateData, callback){
    updateData['recentDateTime'] = new Date();
    Projects.update({userID: userId, ID: projectId}, updateData, function(err){
        if (err){
            callback(1, '项目不存在.');
        } else {
            callback(0, '');
        }
    });
};

ProjectsDAO.prototype.getNewProjectID = function (count, callback) {
    counter.counterDAO.getIDAfterCount(counter.moduleName.project, count, function (err, result) {
        var highID = result.value.sequence_value;
        if (!err) {
            callback(0, '', {lowID: highID - count + 1, highID: highID});
        } else {
            callback(1, '获取主键失败', null);
        }
    });
}

module.exports = new ProjectsDAO();