'use strict';

/**
 *
 *
 * @author EllisRan.
 * @date 2018/4/25
 * @version
 */

module.exports = app => {

    class Bills extends app.BaseService {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'quota_bills';
        }

        /**
         * 根据层级获取数据
         *
         * @param {Number} tenderId - 标段id
         * @param {Number} showLevel - 显示层数
         * @return {Array} - 返回数据
         */
        async getDataByLibId(libId, showLevel = 4) {
            if (libId <= 0) {
                return [];
            }
            this.initSqlBuilder();
            this.sqlBuilder.setAndWhere('lib_id', {
                value: libId,
                operate: '=',
            });

            if (showLevel > 0) {
                this.sqlBuilder.setAndWhere('n_level', {
                    value: showLevel,
                    operate: '<=',
                });
            }

            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
            const data = await this.db.query(sql, sqlParam);

            return data;
        }

        /**
         * 根据 父节点id 获取子节点
         * @param tenderId
         * @param nodeId
         * @return {Promise<*>}
         */
        async getChildrenByParentId(libId, nodeId) {
            if (libId <= 0 || !nodeId) {
                return undefined;
            }
            const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
            if (nodeIds.length === 0) {
                return [];
            }

            this.initSqlBuilder();
            this.sqlBuilder.setAndWhere('lib_id', {
                value: libId,
                operate: '=',
            });
            this.sqlBuilder.setAndWhere('n_pid', {
                value: nodeIds,
                operate: 'in',
            });
            this.sqlBuilder.orderBy = [['n_order', 'ASC']];

            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
            const data = await this.db.query(sql, sqlParam);

            return data;
        }
    }

    return Bills;
}