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

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

  async delById(id) {
    let sql = `DELETE FROM workload_info WHERE id = :id AND status = 0`;
    return await this.customUpdate(sql, {id: id});
  }

  async countHistory(params) {
    var sql = [];
    sql.push("SELECT COUNT(DISTINCT(id_nu)) AS num FROM `workload_info` WHERE status = 1");
    this.setCondition(sql, params);

    let rs = await this.customQuery(sql.join(" "), params);
    if (!rs || rs.length == 0) {
      return 0;
    }

    return rs[0].num || 0;
  }

  async pagecount(params){
    var sql = [];
    sql.push("SELECT COUNT(*) AS num FROM workload_info wi LEFT JOIN user_info ui ON wi.user_id = ui.id WHERE `status`=1");
    this.setpage(sql, params);

    let rs = await this.customQuery(sql.join(" "), params);
    if (!rs || rs.length == 0) {
      return 0;
    }

    return rs[0].num || 0;
  }
  async pageList(params){
    var sql = [];
    sql.push("SELECT wi.*,ui.com_name,ui.mtchId FROM workload_info wi LEFT JOIN user_info ui ON wi.user_id = ui.id WHERE `status`=1");
    this.setpage(sql, params);

    sql.push("ORDER BY wi.id DESC");
    sql.push("LIMIT :startRow, :pageSize");
    return await this.customQuery(sql.join(" "), params);
  }
  async pageHistory(params) {
    var sql = [];
    sql.push("SELECT");
    sql.push("`id`, `username`, `iphone`, `id_nu`, `card_nu`, `send_amount`,");
    sql.push("`created_at`, `updated_time`, `workload`, ");
    sql.push("`created_time`, `updated_at`, `status`,");
    sql.push("sum(send_amount) AS allAmount, COUNT(1) AS times");
    sql.push("FROM `workload_info`");
    sql.push("WHERE status = 1");
    this.setCondition(sql, params);

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

  async findByIdNo(params) {
    var sql = [];
    sql.push("SELECT");
    sql.push("`id`, `username`, `iphone`, `id_nu`, `card_nu`, `send_amount`,");
    sql.push("`created_at`, `updated_time`, `workload`, ");
    sql.push("`created_time`, `updated_at`, `status`");
    sql.push("FROM `workload_info`");
    sql.push("WHERE id_nu = :id_nu AND user_id = :user_id");
    return await this.customQuery(sql.join(" "), params);
  }

  setCondition(sql, params) {
    if (params.user_id) {
      sql.push("AND user_id = :user_id");
    }
    if (params.username) {
      sql.push("AND username = :username");
    }
    if (params.iphone) {
      sql.push("AND iphone = :iphone");

    }
    if (params.id_nu) {
      sql.push("AND id_nu = :id_nu");
    }
  }

  setpage(sql, params) {
    if (params.mtchId) {
      sql.push("AND ui.mtchId = :mtchId");
    }
  }
}

module.exports = WorkloadDao;
