const system = require("../../../system");
const Dao = require("../../dao.base");

class AccountDao extends Dao {
  constructor() {
    super(Dao.getModelName(AccountDao));
  }

  async incrementBalance(id, balance, t) {
    let sql = [];
    sql.push("UPDATE");
    sql.push(this.model.tableName);
    sql.push("SET");
    sql.push("balance = balance + :balance");
    sql.push("WHERE id = :id AND balance + :balance >= 0");
    let res = await this.customUpdate(sql.join(" "), {id: id, balance: balance}, t);
    console.log(res);
    if (res.length < 2) {
      return 0;
    }
    return res[1] || 0;
  }

  async listByIds(ids, attrs) {
    if (!ids || ids.length == 0) {
      return [];
    }
    var sql = [];
    sql.push("SELECT");
    sql.push(attrs || "*");
    sql.push("FROM");
    sql.push(this.model.tableName);
    sql.push("WHERE id IN (:ids)");
    return await this.customQuery(sql.join(" "), {
      ids: ids
    }) || [];
  }

  async mapByIds(ids, attrs) {
    var result = {};
    if (!ids || ids.length == 0) {
      return result;
    }
    var list = await this.findListByIds(ids, attrs);
    if (!list || list.length == 0) {
      return result;
    }
    for (var item of list) {
      result[item.id] = item;
    }
    return result;
  }



}

module.exports = AccountDao;
