//
// Created by Mr.V on 2024/2/19.
//

#include "UpResult.h"

UpResult::UpResult(const ai_matrix::InterfaceConfig &config)
{
    this->httpIp = config.httpIp;
    this->httpPort = config.httpPort;
    this->username = config.username;
    this->password = config.password;
    this->tokenPath = config.tokenPath;
    this->upResultPath = config.upResultPath;
}

UpResult::~UpResult() {}

/**
 * 获取token授权码
 * @param errMsg 错误信息，一般正常时，返回“”
 * @param token 授权码
 * @return
 */
bool UpResult::getToken(QString errMsg, QString &token)
{
    try {
        httplib::Client cli(this->httpIp.toStdString(), this->httpPort);
        cli.set_connection_timeout(2);
        httplib::Headers header;
        httplib::Params params;

        header.emplace("Authorization", "Basic Y2xpZW50X2VudGVycHJpc2U6Y2xpZW50X2VudGVycHJpc2Vfc2VjcmV0");

        params.emplace("username", username.toStdString());
        params.emplace("password", password.toStdString());
        params.emplace("tenantId", "000000");
        params.emplace("grant_type", "password");
        auto res = cli.Post(this->tokenPath.toStdString(), header, params);
        if (res)
        {
            if (res->status == 200)
            {
                Json::CharReaderBuilder readerBuilder;
                std::istringstream iss(res->body);
                Json::Value root;
                std::string errs;

                if (Json::parseFromStream(readerBuilder, iss, &root, &errs))
                {
                    if (root["success"].asString().compare("true"))
                    {
                        token = QString::fromStdString(root["token_type"].asString());
                        token.append(" ");
                        token.append(QString::fromStdString(root["access_token"].asString()));
                    }
                }
                else {
                    errMsg = "获取Token的返回结果，在转化为json时失败！";
                    return false;
                }
            }
            else
            {
                errMsg = "获取Token失败，返回状态码：" + QString::number(res->status) + ", 提示信息：" + QString::fromStdString(res->body);
                return false;
            }
        }
        else
        {
            errMsg = "获取Token请求失败，请检查网络！";
            return false;
        }
    } catch (const std::exception &e) {
        errMsg += "获取Token失败，原因：";
        errMsg += e.what();
        return false;
    }
    return true;
}

/**
 * 上传识别结果
 * @param json 上传的json信息
 * @param token 授权码
 * @param errMsg 错误信息，无错误时一般为“”
 * @return
 */
bool UpResult::upInfo(const QString &json, QString &token, QString errMsg)
{
    try {
        httplib::Client cli(this->httpIp.toStdString(), this->httpPort);
        cli.set_connection_timeout(2);
        httplib::Headers header;
//        httplib::Params params;

        header.emplace("blade-auth", token.toStdString());
        header.emplace("Accept", "application/json");
        header.emplace("Content-Type", "application/json");
        header.emplace("charset", "utf-8");

        auto res = cli.Post(this->upResultPath.toStdString(), header,
                            json.toStdString(), "application/json");
        if (res)
        {
            if (res->status == 200)
            {
                Json::CharReaderBuilder readerBuilder;
                std::istringstream iss(res->body);
                Json::Value root;
                std::string errs;
                if (Json::parseFromStream(readerBuilder, iss, &root, &errs))
                {
                    if (!root["success"].asString().compare("true"))
                    {
                        errMsg = "识别结果上传失败，失败原因：";
                        errMsg += QString::fromStdString(root["msg"].asString());
                        return false;
                    }
                    else
                    {
                        if (!root["msg"].asString().compare("请求未授权"))
                        {
                            this->getToken(errMsg, token);
                            return this->upInfo(json, token, errMsg);
                        }
                    }
                }
                else
                {
                    errMsg = "上传识别结果的返回信息，在转化为json时失败！";
                    return false;
                }
            }
            else
            {
                errMsg = "上传识别结果失败，返回状态码：" + QString::number(res->status) + ", 提示信息：" + QString::fromStdString(res->body);
                return false;
            }
        }
        else
        {
            errMsg = "上传识别结果请求失败，请检查网络！";
            return false;
        }
    }
    catch (const std::exception &e)
    {
        errMsg += "上传识别结果失败，原因：";
        errMsg += e.what();
        errMsg += "识别结果：" + json;
        return false;
    }
    return true;
}