'use strict';

/**
 * 标段项目节数据模型
 *
 * @author CaiAoLin
 * @date 2017/12/1
 * @version
 */

module.exports = app => {

    class TenderNode extends app.BaseService {

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

        /**
         * 新增数据
         *
         * @param {Object} data - 新增的数据(可批量)
         * @param {Number} tenderId - 标段id
         * @return {Boolean} - 返回新增的结果
         */
        async add(data, tenderId) {
            let result = false;
            try {
                if (tenderId <= 0) {
                    throw '标段id错误';
                }
                if (data instanceof Array) {
                    // 数组则为批量插入
                    if (data.length <= 0) {
                        throw '插入数据为空';
                    }
                    // 整理数据
                    const insertData = [];
                    for (const tmp of data) {
                        tmp.template_id = tmp.id;
                        tmp.template_pid = tmp.pid;
                        tmp.tender_id = tenderId;
                        delete tmp.id;
                        delete tmp.pid;
                        insertData.push(tmp);
                    }
                    const operate = await this.transaction.insert(this.tableName, insertData);
                    result = operate.affectedRows > 0;
                } else {
                    // 对象则单个插入
                }
            } catch (error) {
                result = false;
            }

            return result;
        }

        /**
         * 根据层级获取数据
         *
         * @param {Number} tenderId - 标段id
         * @param {Boolean} showAll - 是否显示全部
         * @return {Array} - 返回数据
         */
        async getDataByTenderId(tenderId, showAll = false) {
            if (tenderId <= 0) {
                return [];
            }
            const showLevel = !showAll ? 2 : -1;
            this.initSqlBuilder();
            this.sqlBuilder.setAndWhere('tender_id', {
                value: tenderId,
                operate: '=',
            });

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

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

            return data;
        }
    }

    return TenderNode;
};
