/**
 * Created by CSL on 2017-03-29.
 */

var mg = require('mongoose');
var dbm = require("../../../config/db/db_manager");
var db = dbm.getCfgConnection("scConstruct");

var ratesSchema = new mg.Schema({
    ID: Number,
    ParentID: Number,
    name: String,
    rate: Number,
    memo: String
});

var feeRatesSchema = new mg.Schema({
    ID: Number,
    libID: Number,
    libName: String,
    rates: [ratesSchema]
});

var feeRatesModel = db.model('fee_rates', feeRatesSchema, 'fee_rates');

var FeeRateFile = function(){};

FeeRateFile.prototype.rates = function(fileID, controllerFun){
    feeRatesModel.find({"ID": fileID}, ["rates"], function(err, data){
        if(data.length){
            controllerFun(data);
        }
        else{
            controllerFun(false);
        }
    })
};

// 1 保存成功; 0 保存失败；-1没有找到对应记录。
FeeRateFile.prototype.updateRate = function(rateObj, controllerFun){
    feeRatesModel.findOne({"ID": rateObj.fileID}, ["rates"], function(err, data){
        if(data){
            for (var i = 0; i < data.rates.length; i++) {
                if (data.rates[i].ID == rateObj.rateID) {
                    data.rates[i].rate = rateObj.rateValue;
                    data.save(function (err) {
                        if (err) { controllerFun(0); } else { controllerFun(1); }
                    });
                    break;
                }
            };
        }
        else{ controllerFun(-1); }
    })
};

module.exports = new FeeRateFile();


