#include "platformobject.h"
#include "qjsonobject.h"
#include "qjsondocument.h"
#include <time.h>
#include "qnetworkaccessmanager.h"
#include "qnetworkrequest.h"
#include "qnetworkreply.h"

PlatformObject::PlatformObject(QObject *parent)
	: QObject(parent)
{
	m_bOrderDirection = false;
	m_isPositionOpen = false;
	m_deviationPercentage = 0;
	m_deviationCompensation = 0;
	m_pNetworkManager = nullptr;
	m_nLever = 100;
	m_bCon = false;
}

PlatformObject::~PlatformObject()
{

}

const int nTimeStand = 5 * 60 * 1000;
void PlatformObject::MinData(const DataPlatform &item )
{

	//QMutexLocker lock(&m_QMutex);
	m_QMutex.lock();
	m_vDataVec.push_back(item);
	auto it = m_vDataVec.begin();
	DataPlatform &temp = *it;
	m_price = item.fPrice;
	if (item.nData - temp.nData > nTimeStand)
	{
		m_vDataVec.erase(it);
		m_bCon = true;
	}
	m_QMutex.unlock();
}

float PlatformObject::CalcAverageSelf()
{
	m_QMutex.lock();
	double dAverage = 0.0;
	auto it = m_vDataVec.begin();
	for (;it != m_vDataVec.end();it++)
	{
		dAverage += it->fPrice;
	}
	if (m_vDataVec.size() > 0)
	{
		dAverage /= m_vDataVec.size();
	}
	m_dAverage = dAverage;
	m_QMutex.unlock();
	return dAverage;	
}

void PlatformObject::SetPlatformName( QString strName )
{
	m_strPlatName = strName;
}

double PlatformObject::GetAverage()
{
	return m_dAverage;
}

void PlatformObject::CalcdeviationCompensation( double dBinance )
{
	m_deviationCompensation = dBinance - m_dAverage;
}

double PlatformObject::GetDeviationCompensation()
{
	return m_deviationCompensation;
}

void PlatformObject::executeTradingLogic( double entryThreshold )
{
	if (m_bCon)
	{
		//if (m_bOrderDirection)
		{
			if (m_nLever * m_deviationPercentage > entryThreshold) //开多
			{
				if (!m_isPositionOpen)
				{
					m_isPositionOpen = true;
					m_isDealState = true;

					//tianjiadaima
					qDebug() << "OpenContractMore_XJ";
					OpenContractMore_XJ();
					//

				}

			}
			else if (m_nLever * m_deviationPercentage < entryThreshold)//平仓
			{
				m_isPositionOpen = false;
				//tianjiadaima
				CloseContractMore();
				qDebug() << "CloseContractMore";
			}
		}
		//else
		{
			if (m_nLever * m_deviationPercentage < entryThreshold*-1) //开多
			{
				if (!m_isPositionOpen)
				{
					m_isPositionOpen = true;
					m_isDealState = false;
					//tianjiadaima
					qDebug() << "OpenContractEmpty_XJ";
					OpenContractEmpty_XJ();
				}
			}
			else if (m_nLever * m_deviationPercentage > entryThreshold*-1)//平仓
			{
				m_isPositionOpen = false;
				//tianjiadaima
				qDebug() << "CloseContractEmpty";
				CloseContractEmpty();
			}
		}
	}	
}

void PlatformObject::CalcdeviationPercentage( double dBinancePrice )
{
	m_deviationPercentage = (dBinancePrice - (m_deviationCompensation + dBinancePrice)) / dBinancePrice;
}

double PlatformObject::GetRealPrice()
{
	return m_price;
}

void PlatformObject::OpenContractMore_XJ()
{
	OpenContractInfo item;

	item.delegatePrice = GetRealNewPrice();
	QByteArray dataArray = PackJson_Open(item);

	QString strUrl = "https://www.bitget.com/v1/mcp/order/openContract";
	SendPostRequst(strUrl,dataArray);
}

void PlatformObject::OpenContractEmpty_XJ()
{
	OpenContractInfo item;
	item.delegateType = 2;
	item.delegatePrice = GetRealNewPrice();

	QByteArray dataArray = PackJson_Open(item);

	QString strUrl = "https://www.bitget.com/v1/mcp/order/openContract";
	SendPostRequst(strUrl,dataArray);
}

QByteArray PlatformObject::PackJson_Open( const OpenContractInfo &item )
{
	QJsonObject jsonobject;
	jsonobject.insert("tokenId", item.tokenId);
	jsonobject.insert("symbolId", item.symbolId);

	jsonobject.insert("businessLine", item.businessLine);
	jsonobject.insert("secondBusinessLine", item.secondBusinessLine);

	jsonobject.insert("businessSource", item.businessSource);
	jsonobject.insert("enterPointSource", item.enterPointSource);

	jsonobject.insert("delegateCount", item.delegateCount);
	jsonobject.insert("orderType", item.orderType);

	jsonobject.insert("delegateType", item.delegateType);
	jsonobject.insert("pricedSymbol", item.pricedSymbol);

	jsonobject.insert("timeInForceValue",item.timeInForceValue);
	jsonobject.insert("delegatePrice", item.delegatePrice);

	jsonobject.insert("languageType",item.languageType);

	QJsonDocument doc(jsonobject);

	return doc.toJson(QJsonDocument::Compact);
}

void PlatformObject::OpenContractEmpty_SJ()
{
	OpenContractInfo item;
	item.orderType = 1;
	item.delegateType = 2;
	QByteArray dataArray = PackJson_Open(item);

	QString strUrl = "https://www.bitget.com/v1/mcp/order/openContract";
	SendPostRequst(strUrl,dataArray);
}

void PlatformObject::SetPostionState()
{
	if (m_isPositionOpen)
	{
		static float fTime  = clock();

		float fTimeReal  = clock();
		if (fTimeReal - fTime > 300)
		{
			//平仓
			fTime = clock();
			if (m_isDealState )
			{
				//tianjaidaima
				CloseContractMore();
				qDebug() << "CloseContractMore";
			}
			else 
			{
				CloseContractEmpty();

				qDebug() << "CloseContractEmpty";
			}			
		}
	}
}

void PlatformObject::SendPostRequst(QString strUrl,QByteArray &dataArray)
{
	if (m_pNetworkManager == nullptr)
	{
		m_pNetworkManager = new QNetworkAccessManager(this);
	}
	if (m_pNetworkManager)
	{
		QNetworkRequest _quest;
		_quest.setUrl((QUrl(strUrl)));
		// _quest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
		_quest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
		QNetworkReply *mReply = m_pNetworkManager->post(_quest,dataArray);
		QByteArray _data = mReply->readAll();//读出数据
		connect(mReply,&QNetworkReply::finished,this,&PlatformObject::ReplyFinshed);//方式一	
	}
}

void PlatformObject::ReplyFinshed()
{

}

void PlatformObject::CloseContractMore()
{
	CloseContractInfo item;
	QByteArray dataArray = PackJson_Close(item);

	QString strUrl = "https://www.bitget.com/v1/mcp/order/closeContract";
	SendPostRequst(strUrl,dataArray);
}

void PlatformObject::CloseContractEmpty()
{
	CloseContractInfo item;
	item.delegateType = 4;
	QByteArray dataArray = PackJson_Close(item);

	QString strUrl = "https://www.bitget.com/v1/mcp/order/closeContract";
	SendPostRequst(strUrl,dataArray);
}

QByteArray PlatformObject::PackJson_Close( const CloseContractInfo &item )
{
	QJsonObject jsonobject;
	jsonobject.insert("tokenId", item.tokenId);
	jsonobject.insert("symbolId", item.symbolId);

	jsonobject.insert("businessLine", item.businessLine);	

	jsonobject.insert("businessSource", item.businessSource);
	jsonobject.insert("enterPointSource", item.enterPointSource);
	jsonobject.insert("secondBusinessLine", item.secondBusinessLine);


	jsonobject.insert("timeInForceValue", item.timeInForceValue);
	jsonobject.insert("cancelOrder", item.cancelOrder);

	jsonobject.insert("delegateCount", item.delegateCount);
	jsonobject.insert("orderType", item.orderType);

	jsonobject.insert("delegateType", item.delegateType);

	jsonobject.insert("languageType",item.languageType);

	QJsonDocument doc(jsonobject);

	return doc.toJson(QJsonDocument::Compact);
}

QByteArray PlatformObject::PackJson_Cancle( const CancleContractInfo &item )
{
	QJsonObject jsonobject;

	jsonobject.insert("businessLine", item.businessLine);
	jsonobject.insert("orderId", item.orderId);
	jsonobject.insert("tokenId", item.tokenId);
	jsonobject.insert("symbolId", item.symbolId);

	jsonobject.insert("secondBusinessLine",item.secondBusinessLine);
	

	jsonobject.insert("languageType",item.languageType);

	QJsonDocument doc(jsonobject);

	return doc.toJson(QJsonDocument::Compact);
}

double PlatformObject::GetRealNewPrice()
{
	vector<DataPlatform>::iterator it =  m_vDataVec.end() - 1;
	return it->fPrice;
}