#include "DaoUser.h"
#include "database/DaoEntity.h"
#include "common/Snowflake.h"

bool DaoUser::insert_user(DataFields& fields)
{
    fields.check(DMAccount::BALANCE, "", "0");
    fields.check(DMAccount::STATUS, "", "NULL");
    fields.check(DMAccount::TYPE, "", "NULL");
    fields.remove(DMAccount::CREATE_TIME);
    fields.remove(DMAccount::UPDATE_TIME);
    fields.set(DMAccount::USER_ID, "U" + Snowflake::instance().next_id_str());
    DaoEntity dao(DMAccount::TABLENAME);
    return dao.insert_fields(fields);
}

bool DaoUser::update_user(std::string user_id, DataFields& fields)
{
    fields.check(DMAccount::BALANCE, "", "0");
    fields.check(DMAccount::STATUS, "", "NULL");
    fields.check(DMAccount::TYPE, "", "NULL");
    fields.remove(DMAccount::USER_ID);
    fields.remove(DMAccount::CREATE_TIME);
    fields.remove(DMAccount::UPDATE_TIME);
    DaoEntity dao(DMAccount::TABLENAME);
    string sql_c = "where " + DMAccount::USER_ID + "='" + user_id + "'";
    return dao.update_fields(fields, sql_c);
}

bool DaoUser::query_user(PageInfo& pageinfo, vector<DataFields>& result, string sql_c/*=""*/)
{
    // 查询数据库
    DaoEntity dao(DMAccount::TABLENAME);
    return dao.query_fields("*", sql_c, pageinfo, result);
}

bool DaoUser::query_user_by_car_num(string car_num, vector<DataFields>& result)
{
    string sql = "SELECT car.id, car.car_no, car.brand, car.model, car.battery_model, car.batt_code, battery.model batt_model, battery.lock_type,"
        "account.user_id, account.name, account.phone, account.balance FROM car "
        "LEFT JOIN battery ON battery.code=car.batt_code "
        "LEFT JOIN account ON account.user_id=car.user_id "
        "where car_no = '" + car_num + "';";
    return DaoEntity::exec_once(sql, result);
}
