'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/4/23
 * @version
 */

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

        /**
         * 导入指标参数
         *
         * @param {Array|Object} datas
         * @param transaction - 事务
         * @returns {Promise<void>}
         */
        async importData(data, transaction, templateId = 1) {
            const datas = data instanceof Array ? data : [data];
            await transaction.delete(this.tableName, {template_id: templateId});
            const insertResult = await transaction.insert(this.tableName, datas);
            if (insertResult.affectedRows !== datas.length) {
                throw '导入指标参数错误';
            }
        }
        async updateNodeMatch(data, condition) {

            /**
             * 保存指标节点匹配规则
             *
             * @param {Object} data
             * @returns {Promise<*>}
             */
            try {
                if (data.match_key && !this.ctx.helper.validMatchCode(data.match_key)) {
                    throw '用于绑定的分项编号有误'
                }
                data.match_type = this.ctx.app.paramConst.matchType.code;
                await this.db.update(this.tableName, data, {where: condition});
            } catch (err) {
                console.log(err);
            }
            return await this.getDataByCondition(condition);
        }
    };

    return TemplateParam;
};