#include "audioPlay.h"
#include "ui_audioPlay.h"

#include <QFileInfo>


#include "awMsgBox.h"
#include "CCommonTools.h"
#include <QSettings>
#include "CAppInfo.h"
#include "logproc.h"
#include "CAudioPlayerProc.h"
#include "awMsgBox.h"

audioPlay::audioPlay(QString sAudioName,  QString sAudioUrl, int nlimitedPlayTimes, QWidget *parent) :
    CBaseWidget(parent),
    ui(new Ui::audioPlay), m_sAudioName(sAudioName), m_sAudioUrl(sAudioUrl)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose);

	setStyleSheet(g_appInfoPtr->m_sQssStr);

    m_sRecordDevice = "";
	m_nLeftPalyCount = 0;
	m_nPlayedCont = 0;
    if(g_appInfoPtr->m_jAudioPlayedCount != Json::Value::null &&
            g_appInfoPtr->m_jAudioPlayedCount.isMember(sAudioName.toStdString()))
    {
		m_nPlayedCont = g_appInfoPtr->m_jAudioPlayedCount[sAudioName.toStdString()].asInt();
        m_nLeftPalyCount = nlimitedPlayTimes - m_nPlayedCont;
    }
	else
	{
		m_nLeftPalyCount =  nlimitedPlayTimes;
	}


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

    m_nPlayVol = 100;//set.value("config/playVol", 100).toInt();

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


    m_pTimer = new QTimer;
    m_pTimer->setInterval(1000);
    connect(m_pTimer, &QTimer::timeout, this, &audioPlay::timeOut);

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


    QString sFileName = sAudioUrl.right(sAudioUrl.length() - sAudioUrl.lastIndexOf("/") - 1);
    QString sAudioFile = g_appInfoPtr->m_sCacheFileDir + "cache/" + sFileName;
    if(!QFile::exists(sAudioFile))
    {
        CHttpRequestPackage hrp;
        hrp.sUri = sAudioUrl;
        hrp.sCommonStr = sAudioFile;
        hrp.nRequestType = RequestType::rtDownLoadFile;
        hrp.nRetryCount = 3;
        g_httpBllPtr->downLoad(hrp);
    }

    this->installEventFilter(this);

}

audioPlay::~audioPlay()
{
	if (m_pTimer->isActive())
	{
		m_pTimer->stop();
		g_audioPalyerPtr->stopPlay();
	}
    delete ui;
}

int audioPlay::setUI(const int nWidth)
{ 
    ui->label_ap_playTimes->setText(QString::fromLocal8Bit(R"(<html>
                                            <style>
                                            .span
                                            {
                                                font-size:%1px;
                                                font-family:"Microsoft YaHei";
                                                font-weight:600;
                                            }
                                            #nText
                                            {
                                                color:rgba(102,102,102,1);
                                            }
                                            #gText
                                            {
                                                color:rgba(19,187,138,1);
                                            }
                                            #rText
                                            {
                                                color:rgba(254,119,100,1);
                                            }
                                            </style>
                                            <body>
                                            <span id="nText">（请<span id="gText">点击播放</span>按钮听音作答。已播次数：<span id="rText">%2</span> ，剩余播放次数：<span id="rText">%3</span> ）</span>
                                            </body>
                                            </html>)").arg((int)(g_appInfoPtr->m_fRate*14)).arg(m_nPlayedCont).arg(m_nLeftPalyCount));

    QString sFileName = m_sAudioUrl.right(m_sAudioUrl.length() - m_sAudioUrl.lastIndexOf("/") - 1);
    QString sAudioFile = g_appInfoPtr->m_sCacheFileDir + "cache/" + sFileName;

    int nSecord = g_audioPalyerPtr->GetMediaDuration(sAudioFile);
    m_nMaxTestSecord = nSecord;
    QString sText = QString("00:00 / %1:%2")
            .arg((int)(nSecord/60), 2, 10, QChar('0'))
            .arg((int)(nSecord%60), 2, 10, QChar('0'));
    ui->label_ap_time->setText(sText);

    setGeometry(0, 0, nWidth, g_appInfoPtr->m_fRate*60);
    ui->widget_audioPlay->setGeometry(0, g_appInfoPtr->m_fRate * 10, g_appInfoPtr->m_fRate*555, g_appInfoPtr->m_fRate*40);
    ui->btn_ap_play->setGeometry(g_appInfoPtr->m_fRate*8, (ui->widget_audioPlay->height() - g_appInfoPtr->m_fRate*24)/2, g_appInfoPtr->m_fRate*24, g_appInfoPtr->m_fRate*24);
    ui->label_ap_time->adjustSize();
    ui->label_ap_time->setGeometry(ui->btn_ap_play->x() + ui->btn_ap_play->width() + g_appInfoPtr->m_fRate*7,
                                   (ui->widget_audioPlay->height() - ui->label_ap_time->height())/2, ui->label_ap_time->width(), ui->label_ap_time->height());
	if (!QFile::exists(sAudioFile))
	{
		ui->btn_ap_play->setVisible(false);
		ui->label_ap_time->setText(QString::fromLocal8Bit("正在下载音频"));
	}
    ui->label_ap_playTimes->adjustSize();
    ui->label_ap_playTimes->setGeometry(ui->label_ap_time->x() + ui->label_ap_time->width() + g_appInfoPtr->m_fRate*10,
                                        (ui->widget_audioPlay->height() - ui->label_ap_playTimes->height())/2, ui->label_ap_playTimes->width(), ui->label_ap_playTimes->height());
	ui->widget_audioPlay->setGeometry(0, g_appInfoPtr->m_fRate * 10, ui->label_ap_playTimes->x() + ui->label_ap_playTimes->width() + g_appInfoPtr->m_fRate * 8, g_appInfoPtr->m_fRate*40);
	if (m_nLeftPalyCount == 0)
	{		
		ui->btn_ap_play->setStyleSheet("border-image:url(:/images/btn-play_disable.png);");
	}
    return g_appInfoPtr->m_fRate*60;
}

void audioPlay::onDownLoadFile(CDownLoadFileInfo downLoadFileInfo)
{
    QString sFileName = m_sAudioUrl.right(m_sAudioUrl.length() - m_sAudioUrl.lastIndexOf("/") - 1);
    QString sAudioFile = g_appInfoPtr->m_sCacheFileDir + "cache/" + sFileName;
    if (downLoadFileInfo.sFileName == sAudioFile)
    {
        if (downLoadFileInfo.nCode == 200)
        {
            int nSecord = g_audioPalyerPtr->GetMediaDuration(sAudioFile);
            m_nMaxTestSecord = nSecord;
            QString sText = QString("00:00 / %1:%2")
                    .arg((int)(nSecord/60), 2, 10, QChar('0'))
                    .arg((int)(nSecord%60), 2, 10, QChar('0'));
            ui->label_ap_time->setText(sText);
			ui->btn_ap_play->setVisible(true);
        }
        else
        {
            if(downLoadFileInfo.sMessage.isEmpty())
            {
                ShowMsg(QString::fromLocal8Bit("音频下载失败，请检查网络连接"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
            }
            else
            {
                ShowMsg(downLoadFileInfo.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
            }
        }
    }
}


bool audioPlay::eventFilter(QObject *obj, QEvent *ev)
{
    if(obj == this)
    {
      //判断事件
        if(ev->type() == QEvent::Hide)
        {
            if(m_pTimer->isActive())
            {
                m_pTimer->stop();
                g_audioPalyerPtr->stopPlay();
            }
        }
    }
    return QWidget::eventFilter(obj, ev);
}

void audioPlay::on_btn_ap_play_clicked()
{
	if (m_pTimer->isActive())
	{
		m_pTimer->stop();
		g_audioPalyerPtr->pausePlay();
		ui->btn_ap_play->setStyleSheet("border-image:url(:/images/btn-audio-play.png);");
	}
	else
	{
        if (m_nTestSecord == 0 || m_nMaxTestSecord == 0 || m_nTestSecord >= m_nMaxTestSecord)
		{
			//播放
			if (m_nLeftPalyCount < 1)
			{
				return;
			}

			m_nTestSecord = 0;
			//    m_nMaxTestSecord = 0;
			m_sRecordDevice = "";
			if (!g_audioPalyerPtr->getDeviceinfo(m_sRecordDevice))
			{
				m_pTimer->stop();
				QString sErrorStr = g_audioPalyerPtr->getErrMsg();
				//        ShowMsg(sErrorStr, g_appInfoPtr->m_answerWidget);
				return;
			}
			g_audioPalyerPtr->setVol(m_nPlayVol);
			QString sFileName = m_sAudioUrl.right(m_sAudioUrl.length() - m_sAudioUrl.lastIndexOf("/") - 1);
			QString sAudioFile = g_appInfoPtr->m_sCacheFileDir + "cache/" + sFileName;



			/* m_nMaxTestSecord =*/ g_audioPalyerPtr->playAudio(sAudioFile);
			m_pTimer->start();

			m_nPlayedCont++;
			m_nLeftPalyCount--;

			ui->label_ap_playTimes->setText(QString::fromLocal8Bit(R"(<html>
													<style>
													.span
													{
														font-size:%1px;
														font-family:"Microsoft YaHei";
														font-weight:400;
													}
													#nText
													{
														color:rgba(102,102,102,1);
													}
													#gText
													{
														color:rgba(19,187,138,1);
													}
													#rText
													{
														color:rgba(254,119,100,1);
													}
													</style>
													<body>
													<span id="nText">（请<span id="gText">点击播放</span>按钮听音作答。已播次数：<span id="rText">%2</span> ，剩余播放次数：<span id="rText">%3</span> ）</span>
													</body>
													</html>)").arg((int)(g_appInfoPtr->m_fRate * 14)).arg(m_nPlayedCont).arg(m_nLeftPalyCount));


			g_appInfoPtr->m_jAudioPlayedCount[m_sAudioName.toStdString()] = m_nPlayedCont;

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

void audioPlay::getPalyedCount(QString &name, int &nCount)
{
	name = m_sAudioName;
	nCount = m_nPlayedCont;
}

void audioPlay::timeOut()
{
    m_nTestSecord++;
	int nSecord = m_nMaxTestSecord;
	QString sText = QString("%1:%2 / %3:%4").arg((int)(m_nTestSecord / 60), 2, 10, QChar('0'))
		.arg((int)(m_nTestSecord % 60), 2, 10, QChar('0'))
		.arg((int)(nSecord / 60), 2, 10, QChar('0'))
		.arg((int)(nSecord % 60), 2, 10, QChar('0'));
	ui->label_ap_time->setText(sText);

    if(m_nTestSecord == m_nMaxTestSecord)
    {		
        m_pTimer->stop();
        g_audioPalyerPtr->stopPlay();     
		ui->btn_ap_play->setStyleSheet("border-image:url(:/images/btn-audio-play.png);");
		if (m_nLeftPalyCount == 0)
		{
			ui->btn_ap_play->setStyleSheet("border-image:url(:/images/btn-play_disable.png);");
		}
    }
    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("播放设备拔出，请检查设备！"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
//            myDebug()<<QString::fromLocal8Bit("播放设备拔出，请检查设备！");
        }
    }
}

int audioPlay::widgetType()
{
    return wt_aduioPlay;
}
