#include "etVoiceTest.h"
#include "ui_etVoiceTest.h"

#include "CAppInfo.h"
#include "CAudioPlayerProc.h"
#include "awMsgBox.h"
#include <QScrollBar>
#include <QHBoxLayout>
#include <QLabel>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QFileDialog>


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

    setStyleSheet(g_appInfoPtr->m_sQssStr);

    m_nVoiceStatus = 2;
	m_nAudioSecord = 0;

	qRegisterMetaType<CDownLoadFileInfo>("CDownLoadFileInfo");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnDownLoadFile, this, &etVoiceTest::onDownLoadFile);

	QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
	sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
	m_sDownLoadAudioFile = sFileName;
	CHttpRequestPackage hrp;
	hrp.sUri = sAudioUrl;
	hrp.sCommonStr = sFileName;
	hrp.nRequestType = RequestType::rtDownLoadFile;
    hrp.nRetryCount = 3;
	g_httpBllPtr->downLoad(hrp);

	QFileInfo file("coe.cfgi");
	QString sFilePath = file.absoluteFilePath();
	QSettings set(sFilePath, QSettings::IniFormat);

	m_nPlayVol = set.value("config/playVol", 100).toInt();
	
	ui->hslider_etvt_volume->setValue(m_nPlayVol);

	if (g_audioPalyerPtr == nullptr)
	{
		g_audioPalyerPtr = std::make_shared<CAudioPlayerProc>();
	}

	m_pTimer = std::make_shared<QTimer>();
	m_pTimer->setInterval(1000);
	connect(m_pTimer.get(), &QTimer::timeout, this, [&]() {
		ui->hslider_etvt_voice->setValue(ui->hslider_etvt_voice->value() + 1);
		ui->label_etvt_time->setText(QString("%1:%2 / %3:%4").arg((int)(ui->hslider_etvt_voice->value() / 60), 2, 10, QChar('0'))
			.arg((int)(ui->hslider_etvt_voice->value() % 60), 2, 10, QChar('0'))
			.arg((int)(m_nAudioSecord / 60), 2, 10, QChar('0'))
			.arg((int)(m_nAudioSecord % 60), 2, 10, QChar('0')));
			
		if (ui->hslider_etvt_voice->value() >= m_nAudioSecord)
		{
            ui->btn_etvt_play->setStyleSheet("border-image:url(:/images/btn-etvt-play.png);");
			m_pTimer->stop();
			g_audioPalyerPtr->stopPlay();
		}
		else
		{
			std::string sDeciceName = "";
			if (!g_audioPalyerPtr->getDeviceinfo(sDeciceName))
			{
				m_pTimer->stop();
				QString sErrorStr = g_audioPalyerPtr->getErrMsg();
                ShowMsg(sErrorStr, this, MSG_ICON_TYPE::mit_error);
			}

			if (sDeciceName != m_sRecordDevice)
			{
                ShowMsg(QString::fromLocal8Bit("播放设备拔出，请检查设备！"), this, MSG_ICON_TYPE::mit_error);
				//            myDebug()<<QString::fromLocal8Bit("播放设备拔出，请检查设备！");
			}
		}
		
	});

}

etVoiceTest::~etVoiceTest()
{
    awMsgBox::clear(this);
    delete ui;
}

int etVoiceTest::setUI(const int nLeft, const int nTop, const int nWidth)
{
    setGeometry(nLeft, nTop, nWidth, g_appInfoPtr->m_fRate*247);
    ui->widget_etvt_voice->setGeometry(g_appInfoPtr->m_fRate*30, g_appInfoPtr->m_fRate*30,
                                  g_appInfoPtr->m_fRate*423, g_appInfoPtr->m_fRate*40);
    ui->btn_etvt_play->setGeometry(g_appInfoPtr->m_fRate*8, (ui->widget_etvt_voice->height() - g_appInfoPtr->m_fRate*24)/2,
                                   g_appInfoPtr->m_fRate*24, g_appInfoPtr->m_fRate*24);
	ui->label_etvt_time->adjustSize();
	ui->label_etvt_time->setGeometry(ui->btn_etvt_play->x() + ui->btn_etvt_play->width() + g_appInfoPtr->m_fRate * 10,
		(ui->widget_etvt_voice->height() - ui->label_etvt_time->height()) / 2,
		ui->label_etvt_time->width(), ui->label_etvt_time->height());
    ui->hslider_etvt_voice->setGeometry(ui->label_etvt_time->x() + ui->label_etvt_time->width() + g_appInfoPtr->m_fRate*10,
                                        (ui->widget_etvt_voice->height() - g_appInfoPtr->m_fRate*12)/2,
                                        g_appInfoPtr->m_fRate*150, g_appInfoPtr->m_fRate*16);
    ui->btn_etvt_volume->setGeometry(ui->hslider_etvt_voice->x() + ui->hslider_etvt_voice->width() + g_appInfoPtr->m_fRate*20,
                                     ui->btn_etvt_play->y(), ui->btn_etvt_play->width(), ui->btn_etvt_play->height());
	ui->hslider_etvt_volume->setGeometry(ui->btn_etvt_volume->x() + ui->btn_etvt_volume->width() + g_appInfoPtr->m_fRate * 10, ui->hslider_etvt_voice->y(),
		g_appInfoPtr->m_fRate*50, ui->hslider_etvt_voice->height());
    ui->btn_etvt_download->setGeometry(ui->hslider_etvt_volume->x() + ui->hslider_etvt_volume->width() + g_appInfoPtr->m_fRate*10,
                                       ui->btn_etvt_play->y(), ui->btn_etvt_play->width(), ui->btn_etvt_play->height());
    ui->btn_etvt_canotPlay->setGeometry(ui->widget_etvt_voice->x() + ui->widget_etvt_voice->width() + g_appInfoPtr->m_fRate*20,
                                        ui->widget_etvt_voice->y(), g_appInfoPtr->m_fRate*141, g_appInfoPtr->m_fRate*40);
    ui->btn_etvt_canotPlay->setIconSize(QSize(g_appInfoPtr->m_fRate*13, g_appInfoPtr->m_fRate*13));
    ui->btn_etvt_canotPlay->setIcon(QIcon(":/images/btn-can-not-play"));
    ui->btn_etvt_canPlay->setGeometry(ui->btn_etvt_canotPlay->x() + ui->btn_etvt_canotPlay->width() + g_appInfoPtr->m_fRate*10,
                                      ui->btn_etvt_canotPlay->y(), g_appInfoPtr->m_fRate*146, ui->btn_etvt_canotPlay->height());
    ui->btn_etvt_canPlay->setIconSize(QSize(g_appInfoPtr->m_fRate*18, g_appInfoPtr->m_fRate*12));
    ui->btn_etvt_canPlay->setIcon(QIcon(":/images/btn_can-play.png"));
    ui->label_HLine->setGeometry(ui->widget_etvt_voice->x(), ui->widget_etvt_voice->y() + ui->widget_etvt_voice->height() + g_appInfoPtr->m_fRate*30,
                                 width() - g_appInfoPtr->m_fRate*30*2, g_appInfoPtr->m_fRate*1 < 1 ? 1 : g_appInfoPtr->m_fRate*1);

    ui->tablewt_envTest->setGeometry(ui->widget_etvt_voice->x(), ui->label_HLine->y() + ui->label_HLine->height(),
                                     width() - g_appInfoPtr->m_fRate*30*2, height() - ui->label_HLine->y() - ui->label_HLine->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);
		*/
    }

    return height();
}

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

void etVoiceTest::onDownLoadFile(CDownLoadFileInfo downLoadFileInfo)
{
	//QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
	//sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
	if (downLoadFileInfo.sFileName == m_sDownLoadAudioFile)
	{
		if (downLoadFileInfo.nCode == 200)
		{
			initAudioDuration();
			ui->tablewt_envTest->setItem(0, 0, new QTableWidgetItem(QString::fromLocal8Bit("文件下载")));
			ui->tablewt_envTest->setItem(0, 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(0, 2, widget);
		}
		else
		{
			ui->tablewt_envTest->setItem(0, 0, new QTableWidgetItem(QString::fromLocal8Bit("文件下载")));
			ui->tablewt_envTest->setItem(0, 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 * 8, g_appInfoPtr->m_fRate * 8));
			icon->setPixmap(QPixmap(":/images/icon-et-iten-unpass.png").scaled(g_appInfoPtr->m_fRate * 8, g_appInfoPtr->m_fRate * 8));			
			layout->addWidget(icon);
			layout->addStretch();
			ui->tablewt_envTest->setCellWidget(0, 2, widget);
		}
	}
}
void etVoiceTest::on_btn_etvt_canotPlay_clicked()
{
	ui->tablewt_envTest->setItem(1, 0, new QTableWidgetItem(QString::fromLocal8Bit("声音播放")));
	ui->tablewt_envTest->setItem(1, 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 * 8, g_appInfoPtr->m_fRate * 8));
	icon->setPixmap(QPixmap(":/images/icon-et-iten-unpass.png").scaled(g_appInfoPtr->m_fRate * 8, g_appInfoPtr->m_fRate * 8));
	layout->addWidget(icon);
	layout->addStretch();
	ui->tablewt_envTest->setCellWidget(1, 2, widget);
    m_nVoiceStatus = 0;
}

void etVoiceTest::on_btn_etvt_canPlay_clicked()
{
	ui->tablewt_envTest->setItem(1, 0, new QTableWidgetItem(QString::fromLocal8Bit("声音播放")));
	ui->tablewt_envTest->setItem(1, 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(1, 2, widget);
    m_nVoiceStatus = 1;
}

void etVoiceTest::initAudioDuration()
{
	QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
	sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
	m_nAudioSecord = g_audioPalyerPtr->GetMediaDuration(sFileName);
	ui->label_etvt_time->setText(QString("%1:%2 / %3:%4").arg(0, 2, 10, QChar('0'))
		.arg(0, 2, 10, QChar('0'))
		.arg((int)(m_nAudioSecord / 60), 2, 10, QChar('0'))
		.arg((int)(m_nAudioSecord % 60), 2, 10, QChar('0')));
	ui->hslider_etvt_voice->setMaximum(m_nAudioSecord);
	ui->hslider_etvt_voice->setValue(0);
}

void etVoiceTest::on_btn_etvt_play_clicked()
{
	if (m_pTimer->isActive())
	{			
		m_pTimer->stop();
		g_audioPalyerPtr->pausePlay();
		ui->btn_etvt_play->setStyleSheet("border-image:url(:/images/btn-etvt-play.png);");
	}
	else
	{ 
		if (m_nAudioSecord == 0 || ui->hslider_etvt_voice->value() == 0
			|| ui->hslider_etvt_voice->value() >= m_nAudioSecord)
		{
			QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
			sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
			if (QFile::exists(sFileName))
			{
				ui->btn_etvt_play->setStyleSheet("border-image:url(:/images/btn-etvt-stop.png);");
				initAudioDuration();
				g_audioPalyerPtr->setVol(m_nPlayVol);

				if (!g_audioPalyerPtr->getDeviceinfo(m_sRecordDevice))
				{
					m_pTimer->stop();
					QString sErrorStr = g_audioPalyerPtr->getErrMsg();
					ShowMsg(sErrorStr, this);
				}

				g_audioPalyerPtr->playAudio(sFileName);
				m_pTimer->start();

			}
		}
		else
		{
			ui->btn_etvt_play->setStyleSheet("border-image:url(:/images/btn-etvt-stop.png);");
			g_audioPalyerPtr->play();
			m_pTimer->start();
		}
	}
    


}

void etVoiceTest::on_btn_etvt_download_clicked()
{
	QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
	sFileName = QFileDialog::getSaveFileName(
		this, sAudioUrl, QFileInfo(sFileName).fileName(),
		"All Files(*.*)");
	m_sDownLoadAudioFile = sFileName;
	CHttpRequestPackage hrp;
	hrp.sUri = sAudioUrl;
	hrp.sCommonStr = sFileName;
	hrp.nRequestType = RequestType::rtDownLoadFile;
    hrp.nRetryCount = 3;
	g_httpBllPtr->downLoad(hrp);
}


int etVoiceTest::getCheckStatus()
{
    return m_nVoiceStatus;
}

void etVoiceTest::on_hslider_etvt_volume_valueChanged(int value)
{    
	QFileInfo file("coe.cfgi");
	QString sFilePath = file.absoluteFilePath();
	QSettings set(sFilePath, QSettings::IniFormat);

	m_nPlayVol = value;
	set.setValue("config/playVol", value);
	if (m_pTimer && m_pTimer->isActive())
	{
		g_audioPalyerPtr->setVol(m_nPlayVol);
	}
    
}

void etVoiceTest::on_btn_etvt_volume_clicked()
{
    if(m_bMute)
    {
        ui->btn_etvt_volume->setStyleSheet("border-image:url(:/images/btn-etvt-volume.png);");
        ui->hslider_etvt_volume->setValue(m_nLastVol);
    }
    else
    {
        ui->btn_etvt_volume->setStyleSheet("border-image:url(:/images/btn-etvt-mute.png);");
        m_nLastVol = ui->hslider_etvt_volume->value();
        ui->hslider_etvt_volume->setValue(0);
    }
    m_bMute = !m_bMute;
}
