'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;
        }

        /**
         * 切换项目
         *
         * @param {Number} projectId - 项目id
         * @return {Boolean} - 返回切换结果
         */
        async switchProject(projectId) {
            // 获取该用户拥有的项目数据
            const sessionUser = this.ctx.session.sessionUser;
            const projectInfo = await this.ctx.service.projectAccount.getProjectInfoByAccount(sessionUser.account);

            let result = false;
            // 判断切换的项目是否属于对应用户
            if (projectInfo.length < 0) {
                return result;
            }

            let targetProject = {};
            for (const tmp of projectInfo) {
                if (tmp.id === projectId) {
                    result = true;
                    targetProject = tmp;
                }
            }

            // 成功后更改session
            if (result) {
                this.ctx.session.sessionProject = {
                    id: targetProject.id,
                    name: targetProject.name,
                    userAccount: targetProject.user_account,
                };
            }

            return result;
        }

    }

    return Project;
};
