/**
 * 单价文件显示业务模型(用于选择单价文件操作)
 *
 * @author CaiAoLin
 * @date 2017/7/5
 * @version
 */
import BaseModel from "../../common/base/base_model";
import CounterModel from "./counter_model";
import {default as UnitPriceFileSchema, collectionName as collectionName} from "./schemas/unit_price_file";

class UnitPriceFileModel extends BaseModel {

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

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

    /**
     * 新增单价文件
     *
     * @param {object} data
     * @return {Promise}
     */
    async add(data) {
        let result = false;
        try {
            if (Object.keys(data).length <= 0) {
                throw '数据为空';
            }
            result = await this.db.create(data);
        } catch (error) {
            result = false;
        }

        return result;
    }

    /**
     * 根据项目id获取单价文件数据
     *
     * @param {Number} projectId
     * @return {Promise}
     */
    async getDataByProject(projectId) {
        let result = null;
        projectId = parseInt(projectId);
        try {
            if (isNaN(projectId) || projectId <= 0) {
                throw '标段id有误';
            }
            result = await this.findDataByCondition({project_id: projectId});

            // 如果没有找到则新增一条记录
            if (!result) {
                let data = {
                    // @todo 后续再项目中获取
                    name: 'projectName',
                    project_id: projectId
                };
                result = await this.add(data);
            }
        } catch (error) {
            console.log('error:' + error);
        }

        return result;
    }

    /**
     * 新增单条工料机数据
     *
     * @param {object} data
     * @return {Promise}
     */
    async add(data) {
        if (Object.keys(data).length <= 0) {
            throw '新增数据为空';
        }

        let counterModel = new CounterModel();
        data.id = await counterModel.getId(collectionName);

        this.setScene('add');
        let result = await this.db.create(data);
        return result;
    }
}

export default UnitPriceFileModel;