#include "service.h"

// 构造函数
MyService::MyService(unsigned short port) : port_(port) {
    // 初始化各个平台数据
    platforms_["BN"] = {0.0, 0.0, false, false, {}};
    platforms_["BG"] = {0.0, 0.0, false, false, {}};
    platforms_["HOT"] = {0.0, 0.0, false, false, {}};
}

void MyService::start() {
    net::io_context io_context;

    tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), port_));
    std::cout << "Server running on port " << port_ << std::endl;

    while (true) {
        tcp::socket socket(io_context);
        acceptor.accept(socket);

        std::thread(&MyService::doHttpSession, this, std::move(socket)).detach();
        // 在这里可以启动 WebSocket 会话
    }
}

void MyService::doHttpSession(tcp::socket socket) {
    try {
        beast::flat_buffer buffer;
        http::request<http::string_body> req;

        http::read(socket, buffer, req);

        onHttpRequest(req);

        http::response<http::string_body> res{http::status::ok, req.version()};
        res.set(http::field::content_type, "text/plain");
        res.body() = "Hello from MyService!";
        res.prepare_payload();
        http::write(socket, res);
    } catch (std::exception& e) {
        std::cerr << "HTTP Session error: " << e.what() << std::endl;
    }
}

void MyService::onHttpRequest(http::request<http::string_body> req) {
    // 解析前端传递的参数，例如价格更新或校正小数点位数
    // 假设消息格式为：{"platform": "BN", "price": 100.5}

    // 这里进行简单处理，只是演示
    std::string platformId = "BN"; // 这应从请求中读取
    double newPrice = 100.5; // 这应从请求中读取

    updatePrice(platformId, newPrice);
}

void MyService::updatePrice(const std::string &platform, double price) {
    std::lock_guard<std::mutex> lock(dataMutex_);

    if (platforms_.find(platform) != platforms_.end()) {
        auto &data = platforms_[platform];

        // 更新价格并记录历史
        data.price = price;
        data.pricesHistory.push_back(price);

        // 调整小数点位数（可根据实际需求调整）
        adjustDecimalPoints();

        // 检查偏差补偿
        checkDeviationCompensation();

        // 计算偏离度百分比
        calculateDeviationPercentage();

        // 判断开仓平仓
        determinePosition();
    }
}

void MyService::adjustDecimalPoints() {
    std::lock_guard<std::mutex> lock(dataMutex_);
    // 实现小数点位数的校正逻辑
    // 例如，可以根据前端给定的参数来统一各平台的小数点位数
}

void MyService::checkDeviationCompensation() {
    auto now = std::chrono::steady_clock::now();
    std::chrono::duration<double, std::ratio<60>> elapsed = now - lastCompensationTime_;

    if (elapsed.count() > compensationIntervalMinutes) {
        calculateAveragePrices();
        lastCompensationTime_ = now; // 更新最后偏差补偿时间
    }
}

void MyService::calculateAveragePrices() {
    std::lock_guard<std::mutex> lock(dataMutex_);

    double bnSum = 0.0;
    int bnCount = 0;

    for (const auto &price : platforms_["BN"].pricesHistory) {
        bnSum += price;
        bnCount++;
    }

    double bnAverage = (bnCount > 0) ? (bnSum / bnCount) : 0.0;

    // 对于其他平台（BG 和 HOT）进行类似的处理
    for (const auto &platformName : {"BG", "HOT"}) {
        double avg = bnAverage - platforms_[platformName].price; // 偏差补偿
        platforms_[platformName].deviationCompensation = avg;
    }
}

void MyService::calculateDeviationPercentage() {
    std::lock_guard<std::mutex> lock(dataMutex_);

    for (auto &entry : platforms_) {
        auto &data = entry.second;
        double deviationPercentage = (platforms_["BN"].price - (data.deviationCompensation + data.price)) / platforms_["BN"].price;
        std::cout << "Platform: " << entry.first << ", Deviation Percentage: " << deviationPercentage << std::endl;
    }
}

void MyService::determinePosition() {
    std::lock_guard<std::mutex> lock(dataMutex_);

    for (auto &entry : platforms_) {
        auto &data = entry.second;
        double deviationPercentage = (platforms_["BN"].price - (data.deviationCompensation + data.price)) / platforms_["BN"].price;

        // 开多
        if (!data.isOpenLong && deviationPercentage > entryThresholdPercentage) {
            data.isOpenLong = true;
            std::cout << entry.first << " opened long position." << std::endl;
        }
        // 平仓
        else if (data.isOpenLong && deviationPercentage < entryThresholdPercentage) {
            data.isOpenLong = false;
            std::cout << entry.first << " closed long position." << std::endl;
        }

        // 开空
        if (!data.isOpenShort && deviationPercentage < -entryThresholdPercentage) {
            data.isOpenShort = true;
            std::cout << entry.first << " opened short position." << std::endl;
        }
        // 平仓
        else if (data.isOpenShort && deviationPercentage > -entryThresholdPercentage) {
            data.isOpenShort = false;
            std::cout << entry.first << " closed short position." << std::endl;
        }
    }
}

