'use strict';

/**
 * 标段数据模型
 *
 * @author CaiAoLin
 * @date 2017/11/30
 * @version
 */

const tenderConst = require('../const/tender');
module.exports = app => {

    class Tender extends app.BaseService {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'tender';
        }

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

            return rule;
        }

        /**
         * 获取标段列表
         *
         * @return {Array} - 返回标段数据
         */
        async getList() {
            // 获取当前项目信息
            const sessionProject = this.ctx.session.sessionProject;
            this.initSqlBuilder();
            this.sqlBuilder.setAndWhere('project_id', {
                value: sessionProject.id,
                operate: '=',
            });
            this.sqlBuilder.limit = 10;
            this.sqlBuilder.columns = ['id', 'name', 'status', 'type'];
            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);

            return await this.db.query(sql, sqlParam);
        }

        /**
         * 新增标段
         *
         * @param {Object} postData - 表单post过来的数据
         * @return {Boolean} - 返回新增结果
         */
        async add(postData) {
            // 获取当前用户信息
            const sessionUser = this.ctx.session.sessionUser;
            // 获取当前项目信息
            const sessionProject = this.ctx.session.sessionProject;
            const insertData = {
                name: postData.name,
                status: tenderConst.status.APPROVAL,
                project_id: sessionProject.id,
                user_id: sessionUser.accountId,
                create_time: postData.create_time,
                type: postData.type,
            };
            const operate = await this.db.insert(this.tableName, insertData);
            return operate.insertId > 0;
        }

    }

    return Tender;
};
