#include "webservercontrol.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

#include <QtWebSockets>
#include <QtCore>

#include <cstdio>
#include <time.h>
#include "platformobject.h"
using namespace std;


WebServerControl *WebServerControl::m_pWebServerControl = nullptr;

WebServerControl::WebServerControl(QObject *parent)
	: QObject(parent)
{
	/*m_pWebSocketServer = new QWebSocketServer(QStringLiteral("WebServerControl Server"),
	QWebSocketServer::NonSecureMode,this);
	if (m_pWebSocketServer->listen(QHostAddress::Any, port))
	{
	QTextStream(stdout) << "Chat Server listening on port " << port << '\n';
	connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
	this, &WebServerControl::onNewConnection);
	}*/

	m_pBinancePlatformObject = nullptr;
}

WebServerControl::WebServerControl( quint16 port, QObject *parent /*= nullptr*/ )
{
	
}


WebServerControl::~WebServerControl()
{
	if (m_pWebSocketServer)
	{
		m_pWebSocketServer->close();
	}	
}

void WebServerControl::InitQWebSocketServer( quint16 port )
{
	m_pWebSocketServer = new QWebSocketServer(QStringLiteral("WebServerControl Server"),
		QWebSocketServer::NonSecureMode,this);
	if (m_pWebSocketServer->listen(QHostAddress::Any, port))
	{
		QTextStream(stdout) << "Chat Server listening on port " << port << '\n';
		connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
			this, &WebServerControl::onNewConnection);
	}
}

WebServerControl* WebServerControl::GetInstance()
{
	if (m_pWebServerControl == nullptr)
	{
		m_pWebServerControl = new WebServerControl();
	}
	return m_pWebServerControl;
}

void WebServerControl::FreeInstance()
{
	if (m_pWebServerControl)
	{
		delete m_pWebServerControl;
		m_pWebServerControl = nullptr;
	}
}

void WebServerControl::onNewConnection()
{
	auto pSocket = m_pWebSocketServer->nextPendingConnection();
	//QTextStream(stdout) << getIdentifier(pSocket) << " connected!\n";
	pSocket->setParent(this);

	// 对连接进来的每一个进行信号槽连接绑定
	connect(pSocket, &QWebSocket::binaryMessageReceived,
		this, &WebServerControl::processMessage);
	connect(pSocket, &QWebSocket::textMessageReceived,
		this, &WebServerControl::processMessageText);
	connect(pSocket, &QWebSocket::disconnected,
		this, &WebServerControl::socketDisconnected);
	// 使用 list 进行管理，方便断开
	m_vClients.push_back(pSocket);
}

void WebServerControl::processMessage( const QByteArray &message )
{
	QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());

	QWebSocket *pClient = nullptr;
	for (int i = 0;i < m_vClients.size();i++) 
	{
		pClient = m_vClients.at(i);
		if (pClient == pSender) 
		{
			pClient->sendTextMessage(message + " @ host echo ");
			//qDebug() << "peer address = " << pClient->peerAddress();


			Parse_Now_Json(message);
		}
	}
}

void WebServerControl::socketDisconnected()
{
	QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());
	if (pSender)
	{
		auto it = m_vClients.begin();
		for (; it != m_vClients.end();it++) 
		{
			QWebSocket *pClient = *it;
			if (pClient == pSender) 
			{
				m_vClients.erase(it);
				pClient->deleteLater();
				break;
			}
		}
	}
}

void WebServerControl::InitHeadCooko()
{
	// 假设你已经有了一个QNetworkAccessManager实例
	QNetworkAccessManager *pManager = new QNetworkAccessManager(this);

	// 发起一个HTTP GET请求来获取cookie
	QNetworkRequest request(QUrl("http://example.com"));
	pManager->get(request);

	// 连接信号和槽，以处理获取的cookie
	connect(pManager, &QNetworkAccessManager::finished, [&](QNetworkReply *reply)
	{
		if(reply->error() == QNetworkReply::NoError) 
		{
			// 获取Set-Cookie头部
			//QList<QNetworkCookie> cookies = reply->header(QNetworkRequest::SetCookieHeader).cookies();
			//QString cookie;
			//for(const QNetworkCookie &ck : cookies) 
			//{
			//	cookie += ck.toRawForm(); // 将cookie转换为字符串
			//}

			//// 使用获取到的cookie来建立WebSocket连接
			//QWebSocket *pWebSocket = new QWebSocket(QUrl("ws://example.com"), this);
			//pWebSocket->setCookiesFromUrl(QList<QNetworkCookie>() << QNetworkCookie(cookie));
			//pWebSocket->open(QUrl("ws://example.com").toEncoded());

			//// 处理webSocket的连接和数据
			//// ...
		}

		reply->deleteLater(); // 请求完成后删除reply对象
	});
}

void WebServerControl::Parse_Now_Json( const QByteArray &arrayjson )
{
	QJsonParseError err_rpt;
	QJsonDocument  root_Doc = QJsonDocument::fromJson(arrayjson, &err_rpt);//字符串格式化为JSON

	if(err_rpt.error != QJsonParseError::NoError)
	{
		qDebug() << "JSON格式错误";
		return;
	}
	else    //JSON格式正确
	{
		QJsonObject object = root_Doc.object();

		if (object.contains("platform") && object["platform"].isString())
		{
			QString strPaltform = 	object["platform"].toString(); // 数据类型

			DataPlatform item;
			item.strPlatformType = strPaltform;
			item.strSymbol = object["symbol"].toString();

			QJsonValue::Type tt =  object["date"].type();

			item.nData = object["date"].toDouble();
			item.fPrice = object["price"].toDouble();

			InsertMapPlatObject(strPaltform,item);
		}
	}
}

void WebServerControl::processMessageText( const QString &message )
{
	QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());

	QWebSocket *pClient = nullptr;
	for (int i = 0;i < m_vClients.size();i++) 
	{
		pClient = m_vClients.at(i);
		if (pClient == pSender) 
		{
			pClient->sendTextMessage(message + " @ host echo ");
			//qDebug() << "peer address = " << pClient->peerAddress();


			float fStime = clock();

			Parse_Now_Json(message.toUtf8());
			float fStime2 = clock();

			//qDebug() << "Parse_Now_Json Time = " << fStime2 - fStime;


		}
	}
}

void WebServerControl::InsertMapPlatObject( QString strType,const DataPlatform &item )
{
	PlatformObject* pObject = nullptr;
	auto it = m_mPlatformObjects.find(strType);
	if (it == m_mPlatformObjects.end())
	{
		pObject = new PlatformObject;
		pObject->SetPlatformName(strType);
		m_mPlatformObjects[strType] = pObject;
		if (strType == "Binance")
		{
			m_pBinancePlatformObject = pObject;
		}
	}
	else
	{
		pObject = it->second;
	}
	if (pObject)
	{
		pObject->MinData(item);
	}
}

//每隔两个小时计算一次
void WebServerControl::CalcAver()
{
	auto it = m_mPlatformObjects.begin();
	for (;it != m_mPlatformObjects.end();it++)
	{
		PlatformObject* pObject = it->second;
		if (pObject)
		{
			pObject->CalcAverageSelf();
		}
	}
}

void WebServerControl::CalcdeviationCompensation()
{
	double dBinance = 0;
	if (m_pBinancePlatformObject)
	{
		if (m_pBinancePlatformObject)
		{
			dBinance = m_pBinancePlatformObject->GetDeviationCompensation();
		}		
	}

	auto it = m_mPlatformObjects.begin();
	for (;it != m_mPlatformObjects.end();it++)
	{
		PlatformObject* pObject = it->second;
		if (pObject)
		{
			pObject->CalcdeviationCompensation(dBinance);
		}
	}
}

void WebServerControl::CalculateDeviationPercentage()
{
	if (m_pBinancePlatformObject)
	{
		double dBNPrice = m_pBinancePlatformObject->GetRealPrice();
		auto it = m_mPlatformObjects.begin();
		for (;it != m_mPlatformObjects.end();it++)
		{
			PlatformObject* pObject = it->second;
			if (pObject != m_pBinancePlatformObject)
			{
				pObject->CalcdeviationPercentage(dBNPrice);
				pObject->executeTradingLogic(0.003);
				pObject->SetPostionState();//300ms判断是否要执行平仓
			}
		}
	}
}

void WebServerControl::ParseJson( const QByteArray &arrayjson )
{

	QJsonParseError err_rpt;
	QJsonDocument  root_Doc = QJsonDocument::fromJson(arrayjson, &err_rpt);//字符串格式化为JSON

	if(err_rpt.error != QJsonParseError::NoError)
	{
		qDebug() << "JSON格式错误";
		return;
	}
	else    //JSON格式正确
	{
		QJsonObject object = root_Doc.object();

		if (object.contains("interfaceType"))
		{
			if (object["interfaceType"] == "trade_config")
			{
				m_ParameterSetting.ParseJson(arrayjson);
			}			
		}
	}	
}