/**
 * Created by jimiz on 2017/4/1.
 */
var mongoose = require("mongoose");
var db = require("../db/project_db");
var Schema = mongoose.Schema;
var counter = require("../../../public/counter/counter.js");
var deleteSchema = require('../../../public/models/delete_schema');
var consts = require('./project_consts');
var projectConsts = consts.projectConst;
var commonConsts = consts.commonConst;

var GLJSchema = new Schema({
    ID: Number,
    GLJID: Number,
    rGLJID: Number,
    rationID: Number,
    billsItemID: Number,
    projectID: Number,
    orgRQuantity: String, //Decimal
    rQuantity: String, //Decimal
    customQuantity: String, //Decimal
    quantity: String, //Decimal
    rationItemQuantity: String, //Decimal
    rationPrice: String, //Decimal
    adjustPrice: String,            // 调整基价 (建筑有个专门的发文公布调整基价，且该单价会被计算引用，不是用户调的那个)
    marketPrice: String,            // 市场单价 （等同于公路的预算价）
    price: String,                  // 最终的单价（用户自定义修改单价在这里）
    tenderQuantity: String, //Decimal
    tenderPrice: String, //Decimal
    type: Number,
    deleteInfo: deleteSchema
    // to do

});

var GLJ = db.model("GLJ", GLJSchema, "GLJ");

var GLJDAO = function(){};

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

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

    function saveOne(data) {
        return function (cb) {
            switch (data.updateType) {
                case commonConsts.UT_UPDATE:
                    GLJ.update({ID: data.ID}, data, cb);
                    break;
                case commonConsts.UT_CREATE:
                    GLJ.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);
};

GLJDAO.prototype.getItemTemplate = function(callback){
    var data = new bills;
    /* to do: 需要根据标准配置库填充fees和flags字段，是否需要更多的参数？ */
    callback(0, '', data);
};

GLJDAO.prototype.allocIDs = function(IDStep, callback){
    counter.counterDAO.getIDAfterCount(counter.moduleName.GLJ, IDStep, function(err, highID){
        var lowID = highID - IDStep + 1;
        callback(0, '', {lowID: lowID, highID: highID});
    });
};

module.exports = new GLJDAO();