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

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

  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;
  }

  async countByCondition(params) {
    var sql = [];
    sql.push("SELECT");
    sql.push("count(1) as num");
    sql.push("FROM");
    sql.push(this.model.tableName);
    sql.push("WHERE deleted_at IS NULL");

    this.setCondition(sql, params);

    var list = await this.customQuery(sql.join(" "), params);
    if (!list || list.length == 0) {
      return 0;
    }
    return list[0].num;
  }

  async listByCondition(params) {
    params.startRow = Number(params.startRow || 0);
    params.pageSize = Number(params.pageSize || 10);
    var sql = [];
    sql.push("SELECT");
    sql.push(params.attrs || "*");
    sql.push("FROM");
    sql.push(this.model.tableName);
    sql.push("WHERE deleted_at IS NULL");

    this.setCondition(sql, params);

    sql.push("ORDER BY created_at DESC");
    sql.push("LIMIT :startRow, :pageSize");
    return await this.customQuery(sql.join(" "), params);
  }

  setCondition(sql, params) {
    if (!params || !sql) {
      return;
    }
    if (params.account_id) {
      sql.push("AND account_id = :account_id");
    }
    if (params.trade_no) {
      sql.push("AND trade_no = :trade_no");
    }
    if (params.trade_type) {
      sql.push("AND trade_type = :trade_type");
    }
    if (params.tradeTimeBegin) {
      sql.push("AND created_at >= :tradeTimeBegin");
    }
    if (params.tradeTimeEnd) {
      sql.push("AND created_at <= :tradeTimeEnd");
    }
  }

}

module.exports = AccountTradeDao;
