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

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

  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("st_order");
    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("t1.*");
    sql.push("FROM");
    sql.push("st_order");
    sql.push("WHERE deleted_at IS NULL");

    this.setCondition(sql, params);

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

  setCondition(sql, params) {
    if (!params || !sql) {
      return;
    }
    if (params.saas_id) {
      sql.push("AND saas_id = :saas_id");
    }
    if (params.saas_merchant_id) {
      sql.push("AND saas_merchant_id = :saas_merchant_id");
    }
    if (params.saas_merchant_ids) {
      sql.push("AND saas_merchant_id IN (:saas_merchant_ids)");
    }
    if (params.out_trade_no) {
      sql.push("AND out_trade_no = :out_trade_no");
    }
    if (params.trade_status) {
      sql.push("AND trade_status = :trade_status");
    }
    if (params.check_status) {
      sql.push("AND check_status = :check_status");
    }
    if (params.acc_type) {
      sql.push("AND acc_type = :acc_type");
    }
    if (params.createBegin) {
      sql.push("AND created_at >= :createBegin");
    }
    if (params.createEnd) {
      sql.push("AND created_at <= :createEnd");
    }
  }
}

module.exports = StOrderDao;
