/**
 * ID计数器数据模型
 *
 * @author CaiAoLin
 * @date 2017/6/23
 * @version
 */
import BaseModel from "../../common/base/base_model";
import mongoose from "mongoose";

class CounterModel extends BaseModel {


    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model('counter');
        parent.init();
    }

    /**
     * 获取自增id
     *
     * @param {String} model
     * @return {Number}
     */
    async getId(model = '') {
        if (model === '') {
            return 0;
        }
        let update = {$inc: {sequence_value: 1}};
        let condition = {_id: model};
        let options = {new: true};

        // 先查找更新
        let idData = await this.db.findAndModify(condition, update, options);
        let idResult = idData === null || idData.sequence_value === undefined ? 0 : idData.sequence_value;

        // 如果没有对应记录则新增
        if (idResult === 0) {
            let insertResult = await this.db.create({_id: model, sequence_value: 1});
            idResult = Object.keys(insertResult).length > 0 ? 1 : 0;
        }

        return idResult;
    }

}

export default CounterModel;