'use strict';

/**
 * 指标对比控制器
 *
 * @author Mai
 * @data 2018/4/19
 * @version
 */

const libConst = require('../const/lib');
module.exports = app => {
    class CompareController extends app.BaseController {
        /**
         * 指标对比页面
         *
         * @param {object} ctx - egg全局context
         * @return {void}
         */
        async index (ctx) {
            const libList = await ctx.service.quotaLib.getList(libConst.status.enter);
            const renderData = {
                libList
            };
            await this.layout('compare/index.ejs', renderData, 'compare/modal.ejs');
        }
        async search (ctx) {
            //console.log('start' + new Date());
            const responseData = {
                err: 0,
                msg: '',
                data: [],
            };
            try {
                const data = JSON.parse(ctx.request.body.data);
                const tenders = data.tenders;
                if (!data.keyword || data.keyword === '') {
                    throw '请输入查询关键字';
                }
                for (const tender of tenders) {
                    if (!tender.lib_id) {
                        throw '查询的标段有误或不存在';
                    }
                    tender.data = await ctx.service.tenderNode.search(tender.lib_id, data.keyword);
                    for (const n of tender.data) {
                        const condition = {
                            lib_id: tender.lib_id,
                            node_id: n.node_id,
                        }
                        n.children = await ctx.service.tenderIndex.getAllDataByCondition({where: condition});
                    }
                }
                responseData.data = tenders;
            } catch (err) {
                responseData.err = 1;
                responseData.msg = err.toString();
                console.log(err);
            }

            //console.log('end' + new Date());
            ctx.body = responseData;
        }
    }

    return CompareController;
}