'use strict';

/**
 * 标段 -- 指标节点业务类
 *
 * @author Mai
 * @date 2018/4/25
 * @version
 */

module.exports = app => {
    class TenderNode extends app.BaseService {
        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局context
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'tender_node';
        }

        async search (tenderId, keyword) {
            const searchKey = '%' + keyword + '%';
            const sql = 'Select * From ??' +
                '  where `lib_id` = ' + tenderId + ' and (`name` like ? or code like ?)';
            const sqlParam = [this.tableName, searchKey, searchKey];
            return await this.db.query(sql, sqlParam);
        }

        async searchClass (tenderId, indexClass, className) {
            if (indexClass === this.app.nodeConst.indexClass.dy) {
                const sql = 'Select * From ' + this.tableName +
                    '  Where `lib_id` = ? and `index_class` = ? and `class_name` = ?';
                const sqlParam = [tenderId, indexClass, className];
                return await this.db.query(sql, sqlParam);
            } else {
                const sql = 'Select * From ' + this.tableName +
                    '  Where `lib_id` = ? and `index_class` = ?';
                const sqlParam = [tenderId, indexClass];
                return await this.db.query(sql, sqlParam);
            }
        }

        async searchParent(tenderId, className) {
            const sql = 'SELECT tn.bills_xid, qb.code, qb.name, qb.units, qb.dgn_quantity1, qb.dgn_quantity2, qb.dgn_price, qb.total_price' +
                '  FROM ' + this.tableName + ' As tn' +
                '  LEFT JOIN ' + this.ctx.service.bills.tableName + ' As qb ON tn.bills_xid = qb.n_id and tn.lib_id = qb.lib_id' +
                '  WHERE tn.`lib_id` = ? and tn.class_name = ?' +
                '  GROUP By tn.bills_xid' +
                '  ORDER By qb.code ASC';
            const param = [tenderId, className];
            return await this.db.query(sql, param);
        }
    };

    return TenderNode;
};