#include "WebHandler.h"

#include <fstream>
#include <filesystem>
#include <iostream>
#include "common/Utils.h"
#include "common/Logger.h"
#include "Snowflake.h"
#include "app/Dao.h"
#include "app/Admin.h"
#include "app/Device.h"

static void VariantListRes(std::vector<Fields>& data, QVariantList& listRes)
{
    for (auto& fields: data)
    {
        QVariantMap row;
        for (auto& field: fields.fields())
        {
            row[field.first.c_str()] = field.second.c_str();
        }
        listRes << row;
    }
}

static void JSsetResPaginaion(QVariantMap& result, std::vector<Fields>& data, int page, int pageSize, int count, int code, string err)
{
    result["code"] = code;
    result["err"] = "操作成功";
    result["count"] = count;
    result["page"] = page;
    result["pageSize"] = pageSize;

    QVariantList listRow;
    for (auto& fields: data)
    {
        QVariantMap row;
        for (auto& field: fields.fields())
        {
            row[field.first.c_str()] = field.second.c_str();
        }
        listRow << row;
    }
    result["data"] = listRow;
}

static void JSgetReqParam(QString key, QVariantMap& params, Fields& fields)
{
    if (params.contains(key)) fields.set(key.toStdString(), params[key].toString().toStdString());
}

void MyWebHandler::setNativeText(const QString& text)
{
    nativeText_ = text;
    emit signalNativeTextChanged(text);
}

void MyWebHandler::log(const QString& text)
{
    XLOGD() << "[JS] " << text.toStdString();
}

QString MyWebHandler::readFile(const QString& filename)
{
    std::string fileName = filename.toStdString();
    XLOGD() << "[cppNative] readFile: " << fileName;
    std::filesystem::path filePath = std::filesystem::u8path(fileName);
    std::ifstream ifs(filePath);
    if (ifs.is_open())
    {
        // 获取文件大小
        ifs.seekg(0, std::ios::end);
        std::streamsize size = ifs.tellg();
        XLOGD() << "[cppNative] readFile [" << fileName << "] success, data size=" << size;

        // 定位回文件开始，读取文件内容到缓冲区
        ifs.seekg(0, std::ios::beg);
        std::string buf(size, '\0');
        ifs.read(&buf[0], size);
        ifs.close();
        return buf.c_str();
    }
    else
    {
        XLOGD() << "[cppNative] readFile [" << fileName << "] failed.";
    }
    return "";
}

void MyWebHandler::login(const QString& username, const QString& passwd)
{
    XLOGI() << "login request: " << username.toStdString();
    Errcode ecode = Admin::instance().longin(username.toStdString(), passwd.toStdString());

    //std::this_thread::sleep_for(std::chrono::milliseconds(10000));
    emit signalLongin(username, int(ecode));
}

void MyWebHandler::loginOut(const QString& username)
{
}

QVariantMap MyWebHandler::queryUserList(int page, int pageSize)
{
    XLOGD() << "[cppNative] queryUserList";
    std::vector<Fields> res;
    DAO::queryUser(res);

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}

int MyWebHandler::insertUser(QVariantMap params)
{
    Fields fields;
    JSgetReqParam("account", params, fields);
    fields.set("passwd", "123456");
    JSgetReqParam("name", params, fields);
    JSgetReqParam("gender", params, fields);
    JSgetReqParam("age", params, fields);
    JSgetReqParam("phone", params, fields);
    JSgetReqParam("email", params, fields);
    JSgetReqParam("is_open", params, fields);
    XLOGD() << "[cppNative] insertUser: params=" << fields.toStr();

    bool ret = DAO::insertUser(fields);



    // 设置用户角色
    std::string user_id = fields.getStr("user_id");
    if (params.contains("role_id")) {

        int role_id = params["role_id"].toInt();
        Fields fieldsUserRole;
        fieldsUserRole.set("user_id", user_id);
        fieldsUserRole.set("role_id", role_id);
        fieldsUserRole.set("create_time", Utils::timeNowStr());
        auto dao = DAO::get("user_role");
        ret = dao->insertFields(fieldsUserRole);
    }
    return ret;
}

int MyWebHandler::deleteUser(const QString& userId) { return 1; }

int MyWebHandler::updateUser(const QString& userId, QVariantMap params) 
{
    XLOGD() << "[cppNative] updateUser";

    int ret = 1;
    Fields fields;
    
    JSgetReqParam("account", params, fields);
    JSgetReqParam("name", params, fields);
    JSgetReqParam("gender", params, fields);
    JSgetReqParam("age", params, fields);
    JSgetReqParam("phone", params, fields);
    JSgetReqParam("email", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (params.size() > 0)
    {
        ret = DAO::updateUserById(userId.toStdString(), fields);
        XLOGD() << "updateUser: ret=" << ret;
    }

    if (params.contains("role_id")) {
        int role_id = params["role_id"].toInt();
        fields.clear();
        fields.set("user_id", userId.toStdString());
        fields.set("role_id", role_id);
        fields.set("create_time", Utils::timeNowStr());
        fields.set("update_time", Utils::timeNowStr());
        //fields.set("update_by", "");

        auto dao = DAO::get("user_role");
        std::vector<std::string> keysUpdate = {"role_id", "update_time"};
        bool res = dao->duplicateUpdate(fields, keysUpdate);
        ret = ret ? 0 : 1;
        XLOGD() << "updateUser, update role, ret=" << ret;
    }
    return ret;
}


// ================================================================================================================
// 角色管理接口
QVariantMap MyWebHandler::queryRoleList(int page, int pageSize)
{
    QVariantMap result;

    std::vector<Fields> res;
    auto dao = DAO::get("role");
    bool ret = dao->exec("SELECT * FROM role;", res);
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    XLOGD() << "[cppNative] queryRoleList " << (ret ? "success." : "failed.");

    //QtConcurrent::run([this]() 
    //    {
    //        XLOGD() << "[cppNative] lxy ========== queryRoleList 1111111111111111111111 ";
    //        QThread::msleep(2000);
    //        XLOGD() << "[cppNative] lxy ========== queryRoleList 2222222222222222222222 ";
    //    });

    return result;
}

int MyWebHandler::insertRole(QVariantMap params) 
{
    Fields fields;
    if (params.contains("name")) fields.set("name", params["name"].toString().toStdString());
    if (fields.size() == 0)
    {
        return 1;
    }
    if (params.contains("describe")) fields.set("describe", params["describe"].toString().toStdString());
    
    // 数据表 role_id 是自增id
    fields.set("create_time", Utils::timeNowStr());
    fields.set("update_time", Utils::timeNowStr());
    auto dao = DAO::get("role");
    bool ret = dao->insertFields(fields);
    return ret ? 0: 1;
}
int MyWebHandler::deleteRole(const QString& roleId) { return 1; }
int MyWebHandler::updateRole(const QString& roleId, QVariantMap params) 
{
    Fields fields;
    JSgetReqParam("name", params, fields);
    JSgetReqParam("describe", params, fields);
    if (fields.size() <= 0)
    {
        return 0;
    }
    fields.set("update_time", Utils::timeNowStr());

    std::string sqlC = " WHERE role_id='" + roleId.toStdString() + "'";
    auto dao = DAO::get("role");
    bool ret = dao->updateFields(fields, sqlC);
    return ret ? 0 : 1;
}

QVariantList MyWebHandler::queryRolePermissionList(int roleId)
{
    std::vector<Fields> result;
    std::string sql = "SELECT p.permission_id, p.name, rp.role_id, rp.is_open FROM permission p "
        "LEFT JOIN role_permission rp ON(rp.permission_id = p.permission_id AND rp.role_id = '" + std::to_string(roleId) +"') WHERE p.is_open='1';";

    auto dao = DAO::get("role_permission");
    bool ret = dao->exec(sql, result);

    QVariantList listRow;
    for (auto& fields: result)
    {
        QVariantMap row;
        for (auto& field: fields.fields())
        {
            row[field.first.c_str()] = field.second.c_str();
        }
        listRow << row;
    }
    return listRow;
};
int MyWebHandler::updateRolePermission(int roleId, QVariantList params)
{
    auto dao = DAO::get("role_permission");

    std::string sql = "DELETE FROM role_permission WHERE role_id='" + std::to_string(roleId) + "';";
    bool ret = dao->exec(sql);

    std::vector<Fields> vecFields;
    for (QVariant& item: params)
    {
        if (item.canConvert<QVariantMap>())
        {
            QVariantMap itemMap = item.toMap();
            Fields fields;
            fields.set("role_id", roleId);
            JSgetReqParam("permission_id", itemMap, fields);
            JSgetReqParam("is_open", itemMap, fields);
            vecFields.push_back(fields);
        }
    }
    ret = dao->insertFields(vecFields);
    return ret ? 0 : 1;
};

// ================================================================================================================
// 权限管理接口
QVariantMap MyWebHandler::queryPermissionList(int page, int pageSize)
{
    std::vector<Fields> res;
    auto dao = DAO::get("permission");
    bool ret = dao->exec("SELECT * FROM permission;", res);

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}

int MyWebHandler::insertPermission(QVariantMap params) 
{
    Fields fields; 
    JSgetReqParam("name", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("is_open", params, fields);
    fields.set("create_time", Utils::timeNowStr());
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("permission");
    bool ret = dao->insertFields(fields);
    return ret ? 0 : 1;
}

int MyWebHandler::deletePermission(const QString& permissionId) { return 1; }
int MyWebHandler::updatePermission(const QString& permissionId, QVariantMap params) 
{
    Fields fields;
    JSgetReqParam("name", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() <= 0)
    {
        return 0;
    }
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("permission");
    std::string sqlC = " WHERE permission_id='" + permissionId.toStdString() + "'";
    bool ret = dao->updateFields(fields, sqlC);
    return ret ? 0 : 1;
}

// ================================================================================================================
// 设备管理接口
QVariantMap MyWebHandler::queryDeviceList(int page, int pageSize)
{
    XLOGD() << "queryDeviceList:";

    std::vector<Fields> res;
    auto dao = DAO::get("device");
    bool ret = dao->exec("SELECT * FROM device;", res);
    XLOGD() << "queryDeviceList: size=" << res.size();

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}

static void JSgetReqParamSql(QString key, QVariantMap& params, std::string& sql)
{
    if (params.contains(key)) 
    {
        auto& v = params[key];
        std::string typeName = v.typeName();


        XLOGD() << key.toStdString() << " : " << typeName;
        if (!sql.empty()) sql += ",";
        
        if ("QVariantList" == typeName)
        {
            std::string str = "";
            for (auto& item : v.toList()) 
            {
                if (!str.empty()) str += ",";
                str += ("'" + item.toString().toStdString() + "'");
            }
            sql += ("`" + key.toStdString() + "` IN (" + str + ")");
            XLOGD() << "QVariantList";
        }
        else if ("QString" == typeName)
        {
            // 如果是数组, 需要处理数组格式： ["","",""]
            sql += ("`" + key.toStdString() + "`='" + v.toString().toStdString() + "'");
            XLOGD() << "QString";
        }
        else {
            XLOGD() << "???";
        }
    }
}

QVariantList MyWebHandler::queryDevice(QVariantMap params)
{
    XLOGD() << "MyWebHandler::queryDevice -- params.size=" << params.size();

    QVariantList result;

    std::string sqlc = "";
    JSgetReqParamSql("type", params, sqlc);

    if (sqlc.empty()) {
        return result;
    }

    std::string sql = "SELECT * FROM device WHERE " + sqlc + ";";
    auto dao = DAO::get("device");
    std::vector<Fields> res;
    bool ret = dao->exec(sql, res);
    XLOGD() << "sql=" << sql;
    XLOGD() << "queryDevice: size=" << res.size();

    VariantListRes(res, result);

    XLOGD() << "queryDevice: result size=" << result.size();
    return result;
}

int MyWebHandler::insertDevice(QVariantMap params) 
{ 
    Fields fields;
    JSgetReqParam("type", params, fields);
    JSgetReqParam("name", params, fields);
    JSgetReqParam("code", params, fields);
    JSgetReqParam("model", params, fields);
    JSgetReqParam("factory", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("create_time", Utils::timeNowStr());
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("device");
    bool ret = dao->insertFields(fields);
    return ret ? 0 : 1;
}
int MyWebHandler::deleteDevice(const QString& deviceId) { return 1; }
int MyWebHandler::updateDevice(const QString& deviceId, QVariantMap params) 
{
    Fields fields;
    JSgetReqParam("type", params, fields);
    JSgetReqParam("name", params, fields);
    JSgetReqParam("code", params, fields);
    JSgetReqParam("model", params, fields);
    JSgetReqParam("factory", params, fields);
    JSgetReqParam("is_open", params, fields);
    JSgetReqParam("attrs", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("device");
    std::string sqlC = "WHERE device_id='" + deviceId.toStdString() + "'";
    auto ret = dao->updateFields(fields, sqlC);
    return ret ? 0 : 1;
}
QVariantList MyWebHandler::queryDeviceTypeList()
{
    const std::vector<std::pair<int, std::string>> vecTypeDef =
    {
        {1, "光伏设备"},
        {2, "储能设备"},
        {3, "充电设备"},
        {4, "逆变器"},
        {5, "汇流箱"},
        {6, "电表"},
    };

    QVariantList result;
    for (auto& item: vecTypeDef)
    {
        QVariantMap row;
        row["id"] = item.first;
        row["name"] = item.second.c_str();
        result << row;
    }
    return result;
}

// ================================================================================================================
// 计费管理接口
QVariantMap MyWebHandler::queryPriceList(int page, int pageSize)
{
    std::vector<Fields> res;
    auto dao = DAO::get("price");
    bool ret = dao->exec("SELECT * FROM price;", res);
    XLOGD() << "queryPriceList: size=" << res.size();

    QVariantMap result; 
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}
int MyWebHandler::insertPrice(QVariantMap params) 
{
    Fields fields;
    JSgetReqParam("type", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("create_time", Utils::timeNowStr());
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("price");
    bool ret = dao->insertFields(fields);
    return ret ? 0 : 1;
}
int MyWebHandler::deletePrice(const QString& priceId) { return 1; }
int MyWebHandler::updatePrice(const QString& priceId, QVariantMap params) 
{ 
    Fields fields;
    JSgetReqParam("name", params, fields);
    JSgetReqParam("type", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("update_time", Utils::timeNowStr());

    std::string sqlC = "WHERE price_id='" + priceId.toStdString() + "'";
    auto dao = DAO::get("price");
    auto ret = dao->updateFields(fields, sqlC);
    return ret ? 0 : 1;
}

QVariantList MyWebHandler::queryPriceTypeList()
{
    const std::vector<std::pair<int, std::string>> vecTypeDef =
    {
        {1, "充电计费"},
    };

    QVariantList result;
    for (auto& item: vecTypeDef)
    {
        QVariantMap row;
        row["id"] = item.first;
        row["name"] = item.second.c_str();
        result << row;
    }
    return result;
}

QVariantMap MyWebHandler::queryPolicyList(int page, int pageSize)
{
    std::vector<Fields> res;
    auto dao = DAO::get("policy");
    bool ret = dao->exec("SELECT * FROM policy;", res);
    XLOGD() << "queryPolicyList: size=" << res.size();

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}

int MyWebHandler::insertPolicy(QVariantMap params) 
{ 
    Fields fields;
    JSgetReqParam("type", params, fields);
    JSgetReqParam("name", params, fields);
    JSgetReqParam("value", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("create_time", Utils::timeNowStr());
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("policy");
    bool ret = dao->insertFields(fields);
    return ret ? 0 : 1;
}

int MyWebHandler::deletePolicy(const QString& policyId) { return 1; }

int MyWebHandler::updatePolicy(const QString& policyId, QVariantMap params) 
{
    Fields fields;
    JSgetReqParam("type", params, fields);
    JSgetReqParam("name", params, fields);
    JSgetReqParam("value", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("update_time", Utils::timeNowStr());

    std::string sqlC = "WHERE policy_id='" + policyId.toStdString() + "'";
    auto dao = DAO::get("policy");
    auto ret = dao->updateFields(fields, sqlC);
    return ret ? 0 : 1;
}

QVariantList MyWebHandler::queryPolicyTypeList()
{
    const std::vector<std::pair<int, std::string>> vecTypeDef =
    {
        {1, "发电策略"},
        {2, "储能策略"},
        {3, "充电策略"},
    };

    QVariantList result;
    for (auto& item: vecTypeDef)
    {
        QVariantMap row;
        row["id"] = item.first;
        row["name"] = item.second.c_str();
        result << row;
    }
    return result;
}


QVariantMap MyWebHandler::querySyslogList(int page, int pageSize)
{
    std::vector<Fields> res;
    auto dao = DAO::get("system_log");
    bool ret = dao->exec("SELECT * FROM system_log;", res);
    XLOGD() << "querySyslogList: size=" << res.size();

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}

QVariantMap MyWebHandler::querySecPolicyList(int page, int pageSize)
{
    std::vector<Fields> res;
    auto dao = DAO::get("sec_policy");
    bool ret = dao->exec("SELECT * FROM sec_policy;", res);
    XLOGD() << "querySecPolicyList: size=" << res.size();

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
}

int MyWebHandler::insertSecPolicy(QVariantMap params)
{
    Fields fields;
    JSgetReqParam("name", params, fields);
    JSgetReqParam("type", params, fields);
    JSgetReqParam("code", params, fields);
    JSgetReqParam("level", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("action", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("create_time", Utils::timeNowStr());
    fields.set("update_time", Utils::timeNowStr());

    auto dao = DAO::get("sec_policy");
    bool ret = dao->insertFields(fields);
    return ret ? 0 : 1;
}

int MyWebHandler::updateSecPolicy(const QString& policyId, QVariantMap params)
{
    Fields fields;
    JSgetReqParam("name", params, fields);
    JSgetReqParam("type", params, fields);
    JSgetReqParam("code", params, fields);
    JSgetReqParam("level", params, fields);
    JSgetReqParam("describe", params, fields);
    JSgetReqParam("action", params, fields);
    JSgetReqParam("is_open", params, fields);
    if (fields.size() == 0)
    {
        return 0;
    }
    fields.set("update_time", Utils::timeNowStr());

    std::string sqlC = "WHERE sec_policy_id='" + policyId.toStdString() + "'";
    auto dao = DAO::get("sec_policy");
    auto ret = dao->updateFields(fields, sqlC);
    return ret ? 0 : 1;
}

QVariantMap MyWebHandler::querySecRecordList(int page, int pageSize) 
{
    std::vector<Fields> res;
    auto dao = DAO::get("sec_record");
    bool ret = dao->exec("SELECT * FROM sec_record;", res);
    XLOGD() << "querySecRecordList: size=" << res.size();

    QVariantMap result;
    JSsetResPaginaion(result, res, page, pageSize, res.size(), 0, "操作成功");
    return result;
};

int MyWebHandler::insertSecRecord(QVariantMap params) { return 0; };
int MyWebHandler::updateSecRecord(const QString& policyId, QVariantMap params) { return 0; };


QVariantList MyWebHandler::getDeviceInfo(const QVariantList& types)
{
    std::vector<std::shared_ptr<DeviceEntity>> vecDevice;
    for (auto item: types) 
    {
        int deviceType = item.toInt();
        auto vecRes = Device::getDeviceByType(deviceType);
        vecDevice.insert(vecDevice.end(), vecRes.begin(), vecRes.end());
    }

    QVariantList result;
    for (auto& device: vecDevice)
    {
        QVariantMap row;
        row["device_id"] = device->deviceId;
        row["name"] = device->name.c_str();
        row["type"] = device->type;
        row["status"] = device->status;
        row["online"] = device->online;
        row["err"] = device->err;
        result << row;
    }
    return result;
}

QVariantMap MyWebHandler::getEnvironmentInfo()
{
    QVariantMap result;
    result["illumination"] = 30.2;
    result["windspeed"] = 2.6;
    result["temperature"] = 27.8;
    result["humidity"] = 36.9;
    return result;
}

QVariantMap MyWebHandler::getFireInfo()
{
    QVariantMap result;

    // 多个消防点位的信息
    //感烟探测器	Smoke detector
    //感温探测器	Heat detector
    //火焰探测器	Flame detector

    QVariantList list;
    for (int i = 0; i<7; i++)
    {
        QVariantMap item;
        item["pos"] = 1;
        item["status"] = 0;
        list << item;
    }
    result["data"] = list;

    return result;
}

// 获取累计统计数据
QVariantMap MyWebHandler::getStatisticTotal()
{
    QVariantMap result;

    // 查询数据库获取累计统计数据
    
    result["elect_gen"] = 153.8;    // 累计发电量
    result["elect_in"] = 130.2;     // 累计入网电量
    result["elect_charge"] = 0.0;   // 累计充电电量
    result["income_elect"] = 100.0;   // 累计发电收益
    result["income_charge"] = 100.0;  // 累计充电收益
    result["ccers"] = 82.3;          // 累计碳减排量

    return result;
}

// 获取按天统计数据
QVariantList MyWebHandler::getStatisticDay(const QString& startDate, int nday)
{
    static QVariantList result;
    static std::once_flag flagOnce;
    std::call_once(flagOnce, []() {
        // 查询数据库获取累计统计数据
        for (int i = 1; i<=7; i++)
        {
            QVariantMap row;
            row["dt"] = "";

            // 光伏：发电量、入网电量、发电时长、故障次数
            row["elect_gen"] = 136.2 + Utils::random(0, 50);
            row["elect_in"] = 36.9 + Utils::random(0, 50);
            row["elect_gen_t"] = float(i);
            row["income_elect"] = float(i);  // 发电收益
            row["num_fault_solar"] = Utils::random(1, 6);

            // 储能：储能电量、放电电量、储能时长、放电时长、故障次数
            row["elect_store"] = 37.5 + Utils::random(0, 20);
            row["elect_discharge"] = 16.3+ Utils::random(0, 20);
            row["elect_store_t"] = float(i);
            row["elect_discharge_t"] = float(i);
            row["num_fault_store"] = Utils::random(1, 6);

            // 充电：充电电量、充电收益、充电次数、充电时长、故障次数
            row["elect_charge"] = 25.6+ Utils::random(0, 20);
            row["elect_charge_t"] = float(i);
            row["income_charge"] = 327;
            row["num_charge"] = 23;
            row["num_fault_charge"] = Utils::random(1, 6);


            // 负载：
            row["elect_load"] = 20.8 + Utils::random(0, 10);
            row["power_max_load"] = 10.3 + Utils::random(0, 10);
            row["num_fault_load"] = Utils::random(1, 6);

            result << row;
        }
    });

    return result;
}

static QVariantList RandCurveDataDay(int a, int b)
{
    QVariantList d;
    int64_t t0 = Utils::timeNowDate();
    int step = 600;
    int N = 86400 / step;
    int y = a;
    for (int i = 0; i <= N; ++i) {
        int t = t0 + i * step * 1000;
        y = std::floor((y + Utils::random(0, 20) - 10) * 100) / 100;
        QVariantMap item;
        item["name"] = t;
        item["value"] = QVariantList {t, y};
        d << item;
    }
    return d;
}

// 获取一天的发电功率
QVariantList MyWebHandler::getStatisticPowerDay()
{
    static auto tempData = RandCurveDataDay(500, 600);
    return tempData;
}

// 获取一天的辐照度
QVariantList MyWebHandler::getStatisticIrradianceDay()
{
    static auto tempData = RandCurveDataDay(500, 600);
    return tempData;
}

QVariantList MyWebHandler::getCurveDataDay(int a, int b)
{
    return RandCurveDataDay(a, b);
}