const system = require("../../../system");
const Dao = require("../../dao.base");
class UserDao extends Dao {
  constructor() {
    super(Dao.getModelName(UserDao));
  }

  /**
   * 条件查询
   * @param {} params 
   */
  async findUserBySaasId(params) {
    let sql = [];
    sql.push('select ucid,ucname,uctype,saas_id,isEnabled from uc_user where 1 = 1');
    if (params.ucid) {
      sql.push("AND ucid = :ucid");
    }
    if (params.ucname) {
      sql.push("AND ucname = :ucname");
    }
    if (params.uctype) {
      sql.push("AND uctype = :uctype");
    }
    if (params.saas_id) {
      sql.push("AND saas_id = :saas_id");
    }
    if (params.isEnabled) {
      sql.push("AND saas_id = :isEnabled");
    }

    sql.push(`AND (deleted_at > NOW() or deleted_at is null)`);
    return await this.customQuery(sql.join(" "), params);
  }

  async countByCondition(params) {
    var sql = [];
    sql.push("SELECT");
    sql.push("count(1) as num");
    sql.push("FROM uc_user t1");
    sql.push("INNER JOIN uc_user_info t2 ON t1.id = t2.id");
    sql.push("WHERE 1 = 1");

    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.id, t1.ucid, t1.ucname, t1.uctype, t1.org_id, t1.orgpath,");
    sql.push("t1.isMain, t1.saas_id, t1.isEnabled, t1.created_at,");
    sql.push("t2.mobile, t2.realName");
    sql.push("FROM uc_user t1");
    sql.push("INNER JOIN uc_user_info t2 ON t1.id = t2.id");
    sql.push("WHERE 1 = 1");

    this.setCondition(sql, params);

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

  setCondition(params, sql) {
    if (!params || !sql) {
      return;
    }
    if(params.saas_id) {
      sql.push("AND t1.saas_id = :saas_id");
    }

    if(params.ucnameLike) {
      sql.push("AND t1.ucname LIKE :ucnameLike");
    }

    if(params.mobileLike) {
      sql.push("AND t2.mobile LIKE :mobileLike");
    }

    if(params.realNameLike) {
      sql.push("AND t2.realName LIKE :realNameLike");
    }

    if(params.uctype) {
      sql.push("AND t1.uctype LIKE :uctype");
    }

    if(params.createBegin) {
      sql.push("AND t1.created_at >= :createBegin");
    }
    
    if(params.createEnd) {
      sql.push("AND t1.created_at <= :createEnd");
    }
  }
}
module.exports = UserDao;