'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

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

        /**
         * 更新参数取值
         * @param data
         * @returns {Promise<boolean>}
         */
        async updateCalcValue(data) {
            const transaction = await this.db.beginTransaction();
            try {
                const condition = {
                    lib_id: parseInt(data.lib_id),
                    node_id: data.node_id,
                    code: data.code
                };
                if (condition.lib_id < 0 || condition.node_id < 0) {
                    throw '提交数据错误';
                }
                const updateData = {
                    calc_value: parseFloat(data.value),
                };
                await transaction.update(this.tableName, updateData, {where: condition});
                // to do 计算
                await transaction.commit();
                return true;
            } catch (err) {
                await transaction.rollback();
                throw err;
            }
        }

        /**
         * 重置参数取值
         * @param data
         * @returns {Promise<boolean>}
         */
        async resetCalcValue(data) {
            try {
                const condition = {
                    lib_id: parseInt(data.lib_id),
                    node_id: data.node_id,
                    code: data.code,
                };
                if (condition.lib_id < 0 || condition.node_id < 0) {
                    throw '提交数据错误';
                }
                const param = await this.getDataByCondition(condition);
                data.value = param.match_value;
                await this.updateCalcValue(data);
                return true;
            } catch (err) {
                throw err;
            }

        }
    };

    return TenderParam;
};