#include "InjuryDatabase.h"

InjuryDatabase *InjuryDatabase::getInstance()
{
    static InjuryDatabase db;
    return &db;
}

InjuryDatabase::~InjuryDatabase()
{
    close();
}

InjuryDatabase::InjuryDatabase()
{
    m_sqlDb = QSqlDatabase::addDatabase("QMYSQL");
}

//添加记录
bool InjuryDatabase::add(const Injury &data)
{
    qDebug() << "开始添加伤员记录: ID=" << data.id;
    
    if(open("fly_land_database","root","hzk200407140238"))
    {
        qDebug() << "数据库连接成功";
        
        try {
            beginAddFiled("injurydatabase");
            addFiled("id");
            addFiled("injuryrank");
            addFiled("lon");
            addFiled("lat");
            addFiled("flag");
            endAddFiled();

            beginAddRow();
            addValue(data.id);
            addValue(data.rank);
            addValue(data.lon);
            addValue(data.lat);
            addValue(data.flag);
            endAddRow();

            m_valueSql = m_valueSql.left(m_valueSql.length()-1);
            QString sql;
            sql = m_headerSql + m_valueSql;
            
            qDebug() << "执行SQL: " << sql;
            
            bool result = exec(sql);
            qDebug() << "SQL执行结果: " << (result ? "成功" : "失败");
            
            close();
            return result;
        } catch (const std::exception& e) {
            qDebug() << "添加记录异常: " << e.what();
            close();
            return false;
        }
    }
    
    qDebug() << "数据库连接失败";
    close();
    return false;
}


//查询所有记录
bool InjuryDatabase::select_all(QList<Injury> &result)
{
    if(open("fly_land_database","root","hzk200407140238"))
    {
    QSqlQuery query(m_sqlDb);

    QString strQuery;
    strQuery = "SELECT * FROM ";
    strQuery += "injurydatabase";

    query.prepare(strQuery);

    bool isSuccess = query.exec();
    if(isSuccess)
    {
        while(query.next())
        {
            QString id = query.value(0).toString();
            int rank = query.value(1).toInt();
            double lon = query.value(2).toDouble();
            double lat = query.value(3).toDouble();
            int flag = query.value(4).toInt();

            Injury data;
            data.id = id;
            data.rank = rank;
            data.lon = lon;
            data.lat = lat;
            data.flag = flag;
            result.append(data);
        }
    }

    return isSuccess;
    }
    close();
    return false;
}


//返回有效伤员的信息
void InjuryDatabase::ReturnInfo(QList<Injury> result)
{
    if(open("fly_land_database","root","hzk200407140238"))
    {
        select_valid("injurydatabase", result);
        for(int i = 0; i<result.length(); i++)
        {
            qDebug()<<result[i].id<<" "<<result[i].lon<< " "<<result[i].lat<<" "<<result[i].rank;
        }
    }
    close();
}

//——————————————————私有方法————————————
//建立连接
bool InjuryDatabase::open(const QString &dbName,const QString &userName,const QString &passwd)
{
    m_sqlDb.setHostName("localhost"); // 本地数据库 远程DB是：ipaddress
    m_sqlDb.setPort(3306); // 设置端口号
    m_sqlDb.setDatabaseName(dbName);
    m_sqlDb.setUserName(userName);
    m_sqlDb.setPassword(passwd);

    if(!m_sqlDb.open())
    {
        qDebug()<<"连接失败！";
        return false;
    }
    else
    {
        qDebug()<<"连接成功！";
        return true;
    }
}

//查询有效记录
bool InjuryDatabase::select_valid(const QString &tableName, QList<Injury> &result)
{
    QSqlQuery query(m_sqlDb);

    QString strQuery;
    strQuery = "SELECT id, injuryrank, lon, lat FROM ";
    strQuery += tableName;
    strQuery += "  WHERE flag = 1";

    //qDebug()<<strQuery;//打印SQL语句检查错误

    query.prepare(strQuery);

    bool isSuccess = query.exec();
    if(isSuccess)
    {
        while(query.next())
        {
            QString id = query.value(0).toString();
            int rank = query.value(1).toInt();
            double lon = query.value(2).toDouble();
            double lat = query.value(3).toDouble();

            Injury data;
            data.id = id;
            data.rank = rank;
            data.lon = lon;
            data.lat = lat;
            result.append(data);
        }
    }

    return isSuccess;
}

void InjuryDatabase::close()
{
    m_sqlDb.close();
}



void InjuryDatabase::beginAddFiled(const QString &tableName)
{
    m_tableName = tableName;
    m_fieldName.clear();
    m_headerSql.clear();
    m_valueSql.clear();
    m_fieldAdd = 0;
}

void InjuryDatabase::addFiled(const QString &filedName)
{
    m_fieldName.append(filedName);
}

void InjuryDatabase::endAddFiled()
{
    m_headerSql = QString("INSERT INTO %0 (%1) values").arg(m_tableName).arg(m_fieldName.join(","));
}

void InjuryDatabase::beginAddRow()
{
    m_valueSql += "(";
}

void InjuryDatabase::addValue(const QVariant &value)
{
    m_valueSql += QString("\'%0\',").arg(value.toString());
    m_fieldAdd++;
}

void InjuryDatabase::endAddRow()
{
    m_valueSql = m_valueSql.left(m_valueSql.length() - 1);
    m_valueSql += "),";
}


bool InjuryDatabase::exec(const QString &sql)
{
    QSqlQuery query(m_sqlDb);
    qDebug() << "执行SQL查询: " << sql;
    
    bool success = query.exec(sql);
    
    if (!success) {
        qDebug() << "SQL执行错误: " << query.lastError().text();
    }
    
    return success;
}

//删除伤员记录
bool InjuryDatabase::deleteById(const QString &id)
{
    qDebug() << "开始删除伤员记录: ID=" << id;
    
    if(open("fly_land_database","root","hzk200407140238"))
    {
        qDebug() << "数据库连接成功";
        
        try {
            QString sql = QString("DELETE FROM injurydatabase WHERE id='%1'").arg(id);
            qDebug() << "执行SQL: " << sql;
            
            bool result = exec(sql);
            qDebug() << "SQL执行结果: " << (result ? "成功" : "失败");
            
            close();
            return result;
        } catch (const std::exception& e) {
            qDebug() << "删除记录异常: " << e.what();
            close();
            return false;
        }
    }
    
    qDebug() << "数据库连接失败";
    close();
    return false;
}

