'use strict';

/**
 * 项目数据模型
 *
 * @author CaiAoLin
 * @date 2017/11/16
 * @version
 */

module.exports = app => {

    class Project extends app.BaseService {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'project';
            // 状态相关
            this.status = {
                TRY: 1,
                NORMAL: 2,
                DISABLE: 3,
            };
        }

        /**
         * 数据规则
         *
         * @param {String} scene - 场景
         * @return {Object} - 返回数据规则
         */
        rule(scene) {
            let rule = {};
            switch (scene) {
                case 'saveInfo':
                    rule = {
                        name: { type: 'string', required: true, min: 2 },
                    };
                    break;
                default:
                    break;
            }
            return rule;
        }

        /**
         * 根据项目code获取项目数据
         *
         * @param {String} code - 项目code
         * @return {Object} - 返回项目数据
         */
        async getProjectByCode(code) {
            // 获取项目状态为非禁止的项目
            this.initSqlBuilder();
            this.sqlBuilder.setAndWhere('code', {
                value: this.db.escape(code),
                operate: '=',
            });
            this.sqlBuilder.setAndWhere('status', {
                value: this.status.DISABLE,
                operate: '<',
            });
            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
            const projectData = await this.db.queryOne(sql, sqlParam);
            return projectData;
        }
    }

    return Project;
};
