#include "DaoBattery.h"

#include "database/DaoEntity.h"

void DaoBattery::insert_battery(DataFields& fields)
{
    // ID为自增
    fields.remove(DMBattery::ID);
    fields.check(DMBattery::BATTERY_NUM, "", "0");
    DaoEntity dao(DMBattery::TABLENAME);
    dao.insert_fields(fields);
}

void DaoBattery::query_battery(PageInfo& pageinfo, vector<DataFields>& result, string sql_c)
{
    DaoEntity dao(DMBattery::TABLENAME);
    dao.query_fields("*", sql_c, pageinfo, result);
}

void DaoBattery::query_battery(vector<DataFields>& result)
{
    PageInfo pageinfo;
    pageinfo.page_id = 0;
    pageinfo.page_size = 100;
    DaoEntity dao(DMBattery::TABLENAME);
    dao.query_fields("*", "", pageinfo, result);
}

void DaoBattery::query_battery_by_code(string code, vector<DataFields>& result)
{
    DaoEntity dao(DMBattery::TABLENAME);
    string sql_c = "where code='" + code + "'";
    dao.query_fields("*", sql_c, result);
}

bool DaoBattery::query_battery_by_pos(string storage_id, vector<DataFields>& result)
{
    string sql = "select * from " + DMBattery::TABLENAME + " where " + DMBattery::ID + "='" + storage_id + "'";
    return DaoEntity::exec_once(sql, result);
}

int DaoBattery::update_battery(DataFields& fields, string condition)
{
    DaoEntity dao(DMBattery::TABLENAME);
    fields.check("business_time", "", "NULL");
    fields.check("cool_type", "", "NULL");
    fields.check("status", "", "NULL");
    return dao.update_fields(fields, condition);
}

bool DaoBattery::insert_battery_data(DataFields& fields)
{
    DaoEntity dao(DMBatteryData::TABLENAME);
    return dao.insert_fields(fields);
}

bool DaoBattery::update_battery_bms(std::string batt_code, DataFields& fields)
{
    string sql_c = " WHERE " + DMBatteryData::FID_BATTERY_CODE + "='" + batt_code + "'";

    vector<DataFields> result;
    DaoEntity dao(DMBatteryData::TABLENAME);
    string sql = "select count(1) count from " + DMBatteryData::TABLENAME + sql_c;
    bool ret = dao.exec(sql, result);
    if (!ret)
    {
        return false;
    }
    if (result.size() > 0)
    {
        if (result[0].get_int("count") > 0)
        {
            // UPDATE
            return dao.update_fields(fields, sql_c);
        }
    }

    // INSERT
    fields.set(DMBatteryData::FID_BATTERY_CODE, batt_code);
    return dao.insert_fields(fields);
}