/**
 * 配合比业务模型
 *
 * @author CaiAoLin
 * @date 2017/7/12
 * @version
 */
import BaseModel from "../../common/base/base_model";
import {default as MixRatioSchema, collectionName as collectionName} from "./schemas/mix_ratio";
import CounterModel from "./counter_model"

class MixRatioModel extends BaseModel {

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

    /**
     * 设置场景
     *
     * @param {string} scene
     * @return {void}
     */
    setScene(scene = '') {
        switch (scene) {
            // 新增数据的验证规则
            case 'add':
                this.model.schema.path('glj_id').required(true);
                this.model.schema.path('consumption').required(true);
                this.model.schema.path('unit_price_file_id').required(true);
                this.model.schema.path('connect_code').required(true);
                break;
        }
    }

    /**
     * 新增配合比数据(自动判断是否存在)
     *
     * @param {object} data
     * @return {Promise}
     */
    async add(data) {
        let counterModel = new CounterModel();
        if (data instanceof Array) {
            for(let tmp in data) {
                data[tmp].id = await counterModel.getId(collectionName);
            }
        } else {
            data.id = await counterModel.getId(collectionName);
        }

        this.setScene('add');
        return this.db.model.create(data);
    }

    /**
     * 更新数据
     *
     * @param {Number} id
     * @param {Object} updateData
     * @return {Promise}
     */
    async updateById(id, updateData) {
        id = parseInt(id);
        if (isNaN(id) || id <= 0 || Object.keys(updateData).length <= 0) {
            return false;
        }

        let result = await this.db.update({id: id}, updateData);

        return result.ok !== undefined && result.ok === 1;
    }

}

export default MixRatioModel;
