#include "DaoSwap.h"

#include "app/Constant.h"
#include "app/Global.h"
#include "common/spdlogger.h"
#include "common/TimeUtils.h"
#include "common/Snowflake.h"
#include "database/DaoEntity.h"
#include "Device.h"

std::string DaoSwap::create_swap_record(std::string biz_id, DeviceSwapEntity* swap_entity)
{
    auto& appdata = Global::data();
    if (!swap_entity)
    {
        Spdlogger::error("create swap record failed: swap_entity is null, biz_id={}", biz_id);
        return "";
    }

    swap_entity->info.biz_id = biz_id;
    Spdlogger::info("[SWAP] create swap biz record: biz_id={}", swap_entity->info.biz_id);

    DataFields fields;
    fields.set(DMSwapRecord::ID, swap_entity->info.biz_id);
    fields.set(DMSwapRecord::SWAP_MODE, (int)swap_entity->work_mode);
    fields.set(DMSwapRecord::BATT_MODEL, swap_entity->info.car_battery_model);
    fields.set(DMSwapRecord::CAR_NUM, swap_entity->info.car_no);
    fields.set(DMSwapRecord::USER_ID, swap_entity->info.user_id);
    fields.set(DMSwapRecord::BATT_DOWN_ID, swap_entity->info.car_batt_code);
    fields.set(DMSwapRecord::BATT_ON_ID, swap_entity->info.new_batt_code);
    fields.set(DMSwapRecord::BATT_ON_SOC, swap_entity->info.soc);
    fields.set(DMSwapRecord::STATUS, swap_entity->info.status);
    fields.set(DMSwapRecord::CAUSE, PV::NODE_CAR_VERIFY);
    fields.set(DMSwapRecord::OPEN_TIME, TimeUtils::ts2datetime(swap_entity->info.open_time));

    DaoEntity dao(DMSwapRecord::TABLENAME);
    bool res = dao.insert_fields(fields);
    if (!res)
    {
        Spdlogger::error("create swap record failed: database error, biz_id={}, car_no={}.", swap_entity->info.biz_id, swap_entity->info.car_no);
    }
    return swap_entity->info.biz_id;
}

int DaoSwap::update_swap_record(std::string biz_id, DataFields& fields)
{
    auto& appdata = Global::data();
    if (biz_id.empty())
    {
        Spdlogger::error("[SWAP] update swap data record error：bizid is NULL");
        return 0;
    }
    if (fields.size() > 0)
    {
        fields.remove(DMSwapRecord::ID);
        string sql_c = " where " + DMSwapRecord::ID + "='" + biz_id + "'";
        DaoEntity dao(DMSwapRecord::TABLENAME);
        dao.update_fields(fields, sql_c);
        Global::request_stat = true;
        return 1;
    }
    return 0;
}