#include "etNetworkTest.h"
#include "ui_etNetworkTest.h"

#include "CAppInfo.h"
#include "logproc.h"

#include <QScrollBar>
#include <QHBoxLayout>
#include <QLabel>
#include <QProcess>
#include <regex>

#include "winsock2.h"
#include "windows.h"
#include "winsock.h"
#include "iphlpapi.h"

etNetworkTest::etNetworkTest(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::etNetworkTest)
{
    ui->setupUi(this);

    setStyleSheet(g_appInfoPtr->m_sQssStr);
	bSpeedPass = false;
	bDelayPass = false;

	connect(this, &etNetworkTest::checkInfo, this, [&](QString speed, QString sTime) {
		if (!speed.isEmpty())
		{
			if (speed.toInt() > 5)
			{
				bSpeedPass = true;

				ui->tablewt_envTest->item(0, 0)->setText(QString::fromLocal8Bit("电脑当前下载速度"));
				ui->tablewt_envTest->item(0, 1)->setText(speed + "kb/s");
				QWidget *widget = new QWidget;
				QHBoxLayout *layout = new QHBoxLayout;
				widget->setLayout(layout);
				QLabel *icon = new QLabel;
				icon->setFixedSize(QSize(g_appInfoPtr->m_fRate * 12, g_appInfoPtr->m_fRate * 9));
				icon->setPixmap(QPixmap(":/images/icon-et-item-pass.png").scaled(g_appInfoPtr->m_fRate * 12, g_appInfoPtr->m_fRate * 9));
				layout->addWidget(icon);
				layout->addStretch();
				ui->tablewt_envTest->setCellWidget(0, 2, widget);
			}
		}

		if(!sTime.isEmpty())
		{
			if (sTime.toInt() < 500)
			{
				bDelayPass = true;
			}

			ui->tablewt_envTest->item(1, 0)->setText(QString::fromLocal8Bit("电脑当前网络延迟"));
			ui->tablewt_envTest->item(1, 1)->setText(sTime+"ms");
			QWidget *widget = new QWidget;
			QHBoxLayout *layout = new QHBoxLayout;
			widget->setLayout(layout);
			QLabel *icon = new QLabel;
			icon->setFixedSize(QSize(g_appInfoPtr->m_fRate * 12, g_appInfoPtr->m_fRate * 9));
			icon->setPixmap(QPixmap(":/images/icon-et-item-pass.png").scaled(g_appInfoPtr->m_fRate * 12, g_appInfoPtr->m_fRate * 9));
			layout->addWidget(icon);
			layout->addStretch();
			ui->tablewt_envTest->setCellWidget(1, 2, widget);
		}

		if (bSpeedPass && bDelayPass)
		{
			m_bIsRun = false;
		}
	});

    m_bIsRun = true;
    m_thread = std::thread(std::bind(&etNetworkTest::threadProc, this));
}

etNetworkTest::~etNetworkTest()
{
    m_bIsRun = false;

    m_thread.join();

    delete ui;
}

void etNetworkTest::threadProc()
{
    PMIB_IFTABLE	m_pTable = NULL;
    DWORD	 m_dwAdapters = 0;
    ULONG	 uRetCode = GetIfTable(m_pTable, &m_dwAdapters, TRUE);
    if (uRetCode == ERROR_NOT_SUPPORTED)
    {
        return;
    }

    if (uRetCode == ERROR_INSUFFICIENT_BUFFER)
    {
        m_pTable = (PMIB_IFTABLE)new BYTE[65535];										//假设端口数不超过65535个
    }

    DWORD	dwLastIn = 0;																			//上一秒钟的接收字节数
    DWORD	dwLastOut = 0;																			//上一秒钟的发送字节数
    DWORD	dwBandIn = 0;																			//下载速度
    DWORD	dwBandOut = 0;
    while(m_bIsRun)
    {
        QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
        sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
        CHttpRequestPackage hrp;
        hrp.sUri = sAudioUrl;
        hrp.sCommonStr = sFileName;
        hrp.nRequestType = RequestType::rtDownLoadFile;
        g_httpBllPtr->downLoad(hrp);

        GetIfTable(m_pTable, &m_dwAdapters, TRUE);
        DWORD	dwInOctets = 0;
        DWORD	dwOutOctets = 0;

        //将所有端口的流量进行统计
        for (UINT i = 0; i < m_pTable->dwNumEntries; i++)
        {
            MIB_IFROW	Row = m_pTable->table[i];
            dwInOctets += Row.dwInOctets;
            dwOutOctets += Row.dwOutOctets;
        }

        dwBandIn = dwInOctets - dwLastIn;	//下载速度
        dwBandOut = dwOutOctets - dwLastOut;	//上传速速
        if (dwLastIn <= 0)
        {
            dwBandIn = 0;
        }
        else
        {
            dwBandIn = dwBandIn / 1024;	//b转换成kb
        }

        if (dwLastOut <= 0)
        {
            dwBandOut = 0;
        }
        else
        {
            dwBandOut = dwBandOut / 1024;	//b转换成kb
        }
		dwLastIn = dwInOctets;
		dwLastOut = dwOutOctets;

        QProcess process;
        process.start("ping www.baidu.com -n 1");
        process.waitForFinished(-1); // will wait forever until finished
		QString sOutStr = QString::fromLocal8Bit(process.readAllStandardOutput().data());
	
		QString sFindStr = QString::fromLocal8Bit("平均 =");
		int nIndex = sOutStr.indexOf(sFindStr);
		if (nIndex < 0)
		{
			nIndex = sOutStr.indexOf(QString::fromLocal8Bit("Average ="));
		}

		QString sTimeNum = "";
		if (nIndex > 0)
		{
			QString sTime = sOutStr.mid(nIndex + sFindStr.length(), sOutStr.length() - nIndex);
			int nTimeIndex = sTime.indexOf("ms");
			sTimeNum = sTime.left(nTimeIndex);			
		}
		emit checkInfo(QString::number(dwBandIn), sTimeNum);
		Sleep(1000);
    }
}

int etNetworkTest::setUI(const int nLeft, const int nTop, const int nWidth)
{
    setGeometry(nLeft, nTop, nWidth, g_appInfoPtr->m_fRate*146);
    ui->tablewt_envTest->setGeometry(g_appInfoPtr->m_fRate*30, 0, width() - g_appInfoPtr->m_fRate*30*2, height());

    ui->tablewt_envTest->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //整行选中的方式
    ui->tablewt_envTest->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置为只能选中一行
    ui->tablewt_envTest->setSelectionMode(QAbstractItemView::SingleSelection);
    //隐藏列表头
    ui->tablewt_envTest->verticalHeader()->setVisible(false);
    //隐藏边框
    ui->tablewt_envTest->setShowGrid(false);
    //表头不高亮显示
    ui->tablewt_envTest->horizontalHeader()->setHighlightSections(false);
    //设置行数
    ui->tablewt_envTest->setRowCount(2);
    //设置列数
    ui->tablewt_envTest->setColumnCount(3);

    ui->tablewt_envTest->setHorizontalScrollMode(QTableWidget::ScrollPerPixel);
    ui->tablewt_envTest->horizontalScrollBar()->setSingleStep(g_appInfoPtr->m_fRate*5);

    QStringList sHeadStr;
    sHeadStr << QString::fromLocal8Bit("检测项") <<
                QString::fromLocal8Bit("值") <<
                QString::fromLocal8Bit("状态");

    ui->tablewt_envTest->setHorizontalHeaderLabels(sHeadStr);
    ui->tablewt_envTest->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    ui->tablewt_envTest->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    ui->tablewt_envTest->verticalHeader()->setDefaultSectionSize(g_appInfoPtr->m_fRate*48);
    ui->tablewt_envTest->setColumnWidth(0, g_appInfoPtr->m_fRate*525);
    ui->tablewt_envTest->setColumnWidth(1, g_appInfoPtr->m_fRate*170);
    ui->tablewt_envTest->setColumnWidth(2, g_appInfoPtr->m_fRate*24);
    ui->tablewt_envTest->horizontalHeader()->setStretchLastSection(true);
	
    for(int i = 0; i < 2; i++)
    {
        ui->tablewt_envTest->setItem(i, 0, new QTableWidgetItem(QString::fromLocal8Bit("")));
        ui->tablewt_envTest->setItem(i, 1, new QTableWidgetItem(QString::fromLocal8Bit("")));
       /* QWidget *widget = new QWidget;
        QHBoxLayout *layout = new QHBoxLayout;
        widget->setLayout(layout);
        QLabel *icon = new QLabel;
        icon->setFixedSize(QSize(g_appInfoPtr->m_fRate*12, g_appInfoPtr->m_fRate*9));
        icon->setPixmap(QPixmap(":/images/icon-et-item-pass.png").scaled(g_appInfoPtr->m_fRate*12, g_appInfoPtr->m_fRate*9));
        layout->addWidget(icon);
        layout->addStretch();
        ui->tablewt_envTest->setCellWidget(i, 2, widget);*/
    }
	ui->tablewt_envTest->item(0, 0)->setText(QString::fromLocal8Bit("电脑当前下载速度"));
	ui->tablewt_envTest->item(1, 0)->setText(QString::fromLocal8Bit("电脑当前网络延迟"));
	
    return height();
}

int etNetworkTest::widgetHeight()
{
    return height();
}

int etNetworkTest::getCheckStatus()
{
    return (bSpeedPass && bDelayPass);
}
