'use strict';

/**
 * 台账相关控制器
 *
 * @author CaiAoLin
 * @date 2017/11/30
 * @version
 */

module.exports = app => {

    class LedgerController extends app.BaseController {

        /**
         * 台账列表
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async index(ctx) {
            const rule = ctx.service.tender.rule('add');
            const frontRule = ctx.helper.validateConvert(rule);
            let tender = ctx.request.query.tender;
            tender = parseInt(tender);
            tender = isNaN(tender) ? 0 : tender;

            // 获取标段数据
            const tenderList = await ctx.service.tender.getList();
            // 如果没有指定标段则默认载入第一个
            if (tenderList.length > 0 && tender <= 0) {
                tender = tenderList[0].id;
            }

            // 获取标段项目节点
            const tenderNode = await ctx.service.tenderNode.getDataByTenderId(tender);

            const renderData = {
                tenderList,
                rule: JSON.stringify(frontRule),
                currentTender: tender,
            };
            await this.layout('ledger/index.ejs', renderData);
        }

        /**
         * 添加标段操作
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async addTender(ctx) {
            try {
                const rule = ctx.service.tender.rule('add');
                ctx.validate(rule);

                const result = ctx.service.tender.add(ctx.request.body);
                if (!result) {
                    throw '新增标段失败';
                }
            } catch (error) {
                this.setMessage(error.toString(), this.messageType.ERROR);
            }

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

    return LedgerController;
};
