const ServiceBase = require("../../sve.base");
const system = require("../../../system");

class MerchantaccountService extends ServiceBase {
    constructor() {
        super("merchant", ServiceBase.getDaoName(MerchantaccountService));
    }

    async addtomerchantrmb(merchant_id, amount) {
        return await this.dao.addtomerchantrmb({
            merchant_id: merchant_id,
            amount: amount
        })
    }


    async reduceaccountbalance(params) {
        try {
            if (!params.merchant_id) {
                return system.getResultFail(-1, "请提供商户ID");
            }
            if (!params.amount) {
                return system.getResultFail(-1, "请提供金额");
            } else if (0 > params.amount) {
                return system.getResultFail(-1, "交易金额错误");
            }

            var amount = await this.dao.findOne({merchant_id: params.merchant_id});

            if (!amount) {
                return system.getResultFail("-1", "请先充值");
            }

            if (0 > (amount.balance_amount - params.amount)) {
                return system.getResultFail(-1, "余额不足");
            }

            var data = await this.dao.addordelmerchantrmb(params);
            return system.getResultSuccess(data);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }

    async addordelavailable(params) {
        try {
            if (!params.merchant_id) {
                return system.getResultFail(-1, "请提供商户ID");
            }
            if (!params.amount) {
                return system.getResultFail(-1, "请提供金额");
            }

            var amount = await this.dao.findOne({merchant_id: params.merchant_id});
            if (!amount) {
                return system.getResultFail("-1", "请先充值");
            }

            if (0 > params.amount) {
                let toam = Math.abs(params.amount);
                if (0 > (amount.available_amount - toam)) {
                    return system.getResultFail(-1, "可用余额不足");
                }
            }

            var data = await this.dao.addordelavailable(params);
            return system.getResultSuccess(data);
        } catch (e) {
            console.log(e);
            return system.getResultFail();
        }
    }

}

module.exports = MerchantaccountService;
