/**
 * Created by Mai on 2017/7/25.
 */

let consts = require('../../main/models/project_consts');
let commonConsts = consts.commonConst;

let mongoose = require('mongoose');
let volumePrice = require("./volume_price_schema");
let async = require("async");

let baseModel = require('../../main/models/base_model');

class volumePriceModel extends baseModel {
    constructor (name) {
        super(volumePrice);
        this.collectionName = name;
    };

    getData (projectID, callback) {
        volumePrice.find({'$or': [
            {
                projectID: projectID,
                deleteInfo: null
            }, {
                projectID: projectID,
                'deleteInfo.deleted': {$in: [null, false]}
            }
        ]},(err,datas)=>{
            if(err){
                callback(1, '', null);
            }else {
                callback(0, consts.projectConst.VOLUMEPRICE, datas);
            }
        })
    };

    save (user_id, datas, callback) {
        let funs = [];

        function saveOne(doc) {
            return function (cb) {
                switch (doc.updateType) {
                    case commonConsts.UT_UPDATE:
                        volumePrice.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID}, doc.updateData, cb);
                        break;
                    case commonConsts.UT_CREATE:
                        volumePrice.create(doc.updateData, cb);
                        break;
                    case commonConsts.UT_DELETE:
                        doc.updateData.deleteInfo = {deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
                        volumePrice.update({projectID: doc.updateData.projectID, ID: doc.updateData.ID}, doc.updateData, cb);
                        break;
                }
            }
        }
        for (let data of datas){
            funs.push(saveOne(data));
        }

        async.parallel(funs, callback);
    };

};

module.exports = new volumePriceModel(consts.projectConst.VOLUMEPRICE);