/**
 * Created by jimiz on 2017/5/19.
 */
var mongoose = require("mongoose");
var db = require("../db/project_db");
var subSchema = require("./bills_sub_schemas");
var Schema = mongoose.Schema;
var deleteSchema = require('../../../public/models/delete_schema');
var consts = require('./project_consts');
var projectConsts = consts.projectConst;
var commonConsts = consts.commonConst;

var projectPropertiesSchema = new Schema({
    ID: Number,
    unitPriceFileID: Number,
    unitPriceFileVer: Number,
    deleteInfo: deleteSchema
});

var projectProperties = db.model("projectProperties", projectPropertiesSchema, "projectProperties");

var projectPropertiesDAO = function(){};

projectPropertiesDAO.prototype.getData = function(projectID, callback){
    projectProperties.find({'$or': [{ID: projectID, deleteInfo: null}, {ID: projectID, 'deleteInfo.deleted': {$in: [null, false]}}]}, '-_id', function(err, datas){
        if (!err) {
            callback(0, projectConsts.PROPERTIES, datas);
        } else {
            callback(1, '', null);
        };
    });
};

projectPropertiesDAO.prototype.save = function(datas, callback){
    var functions = [];
    var data;

    function saveOne(data) {
        return function (cb) {
            switch (data.updateType) {
                case commonConsts.UT_UPDATE:
                    projectProperties.update({ID: data.ID}, data, cb);
                    break;
                case commonConsts.UT_CREATE:
                    projectProperties.create(data, cb);
                    break;
                case commonConsts.UT_DELETE:
                /* 假删除
                 var item = new GLJ(doc);
                 item.remove(cb);
                 */
            }
        }
    }
    for (var i = 0; i < datas.length; i++){
        data = datas[i];
        functions.push(saveOne(data));
    }

    async.parallel(functions, callback);
};

module.exports = new projectPropertiesDAO();