'use strict';

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

module.exports = app => {

    class ProfileController extends app.BaseController {

        /**
         * 账号资料页面
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async info(ctx) {
            // 获取当前用户数据
            const sessionUser = ctx.session.sessionUser;

            // 获取账号数据
            const accountData = await ctx.service.projectAccount.getDataByCondition({ id: sessionUser.accountId });

            // 获取基础数据的字段规则
            const baseRule = ctx.service.projectAccount.rule('profileBase');
            const baseJsValidator = await this.jsValidator.convert(baseRule).setSelector('#base-form').build();

            // 获取修改密码的字段规则
            const passwordRule = ctx.service.projectAccount.rule('modifyPassword');
            const passwordJsValidator = await this.jsValidator.convert(passwordRule).setSelector('#password-form').build();

            const renderData = {
                accountData,
                baseJsValidator,
                passwordJsValidator,
            };
            await this.layout('profile/info.ejs', renderData);
        }

        /**
         * 保存基本信息
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async saveBase(ctx) {
            try {
                // 获取当前用户数据
                const sessionUser = ctx.session.sessionUser;

                // 获取基础数据的字段规则
                const baseRule = ctx.service.projectAccount.rule('profileBase');
                ctx.helper.validate(baseRule);

                const result = await ctx.service.projectAccount.save(ctx.request.body, sessionUser.accountId);
                if (!result) {
                    throw '保存信息失败';
                }

                this.setMessage('修改成功', this.messageType.SUCCESS);
            } catch (error) {
                console.log(error);
                this.setMessage(error.toString(), this.messageType.ERROR);
            }

            ctx.redirect(ctx.request.headers.referer);
        }

        /**
         * 修改密码操作
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async modifyPassword(ctx) {
            const password = ctx.request.body.password;
            const newPassword = ctx.request.body.new_password;

            try {
                const sessionUser = ctx.session.sessionUser;
                let accountId = sessionUser.accountId;
                accountId = parseInt(accountId);
                if (isNaN(accountId) || accountId <= 0) {
                    throw '参数错误';
                }
                // 验证数据
                const passwordRule = ctx.service.projectAccount.rule('modifyPassword');
                ctx.helper.validate(passwordRule);

                const result = await ctx.service.projectAccount.modifyPassword(accountId, password, newPassword);
                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 getCode(ctx) {
            const response = {
                err: 0,
                msg: '',
            };
            try {
                const sessionUser = ctx.session.sessionUser;
                const mobile = ctx.request.body.mobile;
                const rule = { mobile: { type: 'mobile', allowEmpty: false } };
                ctx.helper.validate(rule);

                const result = await ctx.service.projectAccount.setSMSCode(sessionUser.accountId, mobile);
                if (!result) {
                    throw '获取验证码失败';
                }
            } catch (error) {
                response.err = 1;
                response.msg = error.toString();
            }

            ctx.body = response;
        }

        /**
         * 绑定认证手机
         *
         * @param {object} ctx - egg全局变量
         * @return {void}
         */
        async bindMobile(ctx) {
            try {
                const rule = ctx.service.projectAccount.rule('bindMobile');
                ctx.helper.validate(rule);

                const sessionUser = ctx.session.sessionUser;
                const result = await ctx.service.projectAccount.bindMobile(sessionUser.accountId, ctx.request.body);

                if (!result) {
                    throw '绑定手机失败!';
                }
                this.setMessage('绑定成功', this.messageType.SUCCESS);
            } catch (error) {
                console.log(error);
                this.setMessage(error.toString(), this.messageType.ERROR);
            }
            ctx.redirect(ctx.request.headers.referer);
        }
    }

    return ProfileController;
};
