'use strict';

/**
 * 项目相关控制器
 *
 * @author CaiAoLin
 * @date 2017/11/29
 * @version
 */

const officeList = require('../const/cld_office').list;
module.exports = app => {

    class ProjectController extends app.BaseController {

        /**
         * 项目信息页面
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async info(ctx) {
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionProject.id;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }

                // 获取销售人员数据
                const salesmanData = await ctx.service.manager.getDataById(projectData.manager_id);

                // 数据规则
                const rule = ctx.service.project.rule('saveInfo');
                const frontRule = ctx.helper.validateConvert(rule);

                const renderData = {
                    projectData,
                    salesmanData,
                    officeList,
                    rule: JSON.stringify(frontRule),
                };
                await this.layout('project/info.ejs', renderData);
            } catch (error) {
                this.setMessage(error.toString(), this.messageType.ERROR);
                ctx.redirect('/dashboard');
            }
        }

        /**
         * 保存项目信息操作
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async saveInfo(ctx) {
            try {
                // 获取项目数据
                const projectId = ctx.session.sessionUser.projectId;
                const projectData = await ctx.service.project.getDataById(projectId);
                if (projectData === null) {
                    throw '没有对应的项目数据';
                }

                const rule = ctx.service.project.rule('saveInfo');
                ctx.validate(rule);

                const updateData = {
                    name: ctx.request.body.name,
                };
                const result = await ctx.service.project.update(updateData, { id: projectData.id });
                if (!result) {
                    throw '保存项目信息失败';
                }

                this.setMessage('保存成功', this.messageType.SUCCESS);
            } catch (error) {
                this.setMessage(error.toString(), this.messageType.ERROR);
                this.setMessage(error, this.messageType.ERROR);
            }

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

    }

    return ProjectController;
};
