'use strict';

/**
 * 账号管理相关控制器
 *
 * @author CaiAoLin
 * @date 2018/1/23
 * @version
 */

const permission = require('../../config/permission');
module.exports = app => {

    class AccountController extends app.BaseController {

        /**
         * 账号管理页面
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async index(ctx) {
            try {
                const sessionProject = ctx.session.sessionProject;
                // 获取当前项目的用户列表
                const accountList = await ctx.service.projectAccount.getAccountByProjectId(sessionProject.id);
                const renderData = {
                    accountList,
                    permissionList: JSON.stringify(permission.permissionList),
                    permissionString: JSON.stringify(permission.permissionString),
                };
                await this.layout('account/index.ejs', renderData);
            } catch (error) {
                this.setMessage(error.toString(), this.messageType.ERROR);
                ctx.redirect(ctx.request.headers.referer);
            }
        }

        /**
         * 停用/启用操作
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async enable(ctx) {
            let accountId = ctx.params.accountId;
            try {
                accountId = parseInt(accountId);
                if (isNaN(accountId) || accountId <= 0) {
                    throw '参数错误!';
                }

                const result = await ctx.service.projectAccount.enableAccount(accountId);
                if (!result) {
                    throw '设置失败';
                }

                this.setMessage('设置成功', this.messageType.SUCCESS);
            } catch (error) {
                this.setMessage(error.toString(), this.messageType.ERROR);
            }
            ctx.redirect(ctx.request.headers.referer);
        }

        /**
         * 保存用户权限
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async savePermission(ctx) {
            let accountId = ctx.params.accountId;
            const permission = ctx.request.body.permission;
            const response = {
                err: 0,
                msg: '',
            };
            try {
                accountId = parseInt(accountId);
                if (isNaN(accountId) || accountId <= 0 || permission === '') {
                    throw '参数错误';
                }
                const result = await ctx.service.projectAccount.save({ permission }, accountId);
                if (!result) {
                    throw '保存权限错误';
                }
            } catch (error) {
                response.err = 1;
                response.msg = error;
            }

            ctx.body = response;
        }

    }

    return AccountController;
};
