'use strict';

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

module.exports = app => {

    class LedgerController extends app.BaseController {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            ctx.showProject = true;
            ctx.showTitle = true;
            ctx.showTender = true;
        }

        /**
         * 台账分解页面
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        async explode(ctx) {
            let tenderId = ctx.session.sessionUser.tenderId;
            if (!tenderId) {
                // 根据标段列表获取默认tenderId
                const tenderList = await ctx.service.tender.getList();
                if (tenderList && tenderList.length > 0) {
                    tenderId = tenderList[0].id;
                    ctx.session.sessionUser.tenderId = tenderId;
                } else {
                    throw '项目无标段数据';
                }
            }
            const ledgerData = await ctx.service.ledger.getDataByTenderId(tenderId);
            const renderData = {
                ledger: JSON.stringify(ledgerData)
            };
            await this.layout('ledger/explode.ejs', renderData);
        }

        async getChildren(ctx) {
            const responseData = {
                err: 0,
                msg: '',
                data: []
            };
            try {
                const tenderId = ctx.session.sessionUser.tenderId;
                if (!tenderId) {
                    throw '当前未打开标段';
                }
                const data = JSON.parse(ctx.request.body.data);
                const id = data.id;
                if (isNaN(id) || id <= 0) {
                    throw '参数错误';
                }

                responseData.data = await ctx.service.ledger.getChildrenByParentId(tenderId, id);
            } catch (err) {
                responseData.err = 1;
                responseData.msg = err;
            }

            ctx.body = responseData;
        }
    }

    return LedgerController;
};
