#include "clNoticeList.h"
#include "ui_clNoticeList.h"

#include <QLabel>
#include <QScrollBar>
#include <QHBoxLayout>

#include "CAppInfo.h"
#include "clOperation.h"
#include "CheckHeaderView.h"
#include "logproc.h"
#include "awMsgBox.h"

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

    setStyleSheet(g_appInfoPtr->m_sQssStr);

    qRegisterMetaType<CUpdateNoticeReadStatus>("CUpdateNoticeReadStatus");
    connect(g_httpBllPtr.get(), &CHttpBll::sgnUpdateNoticeReadStatus, this, &clNoticeList::onUpdateNoticeReadStatus);

}

clNoticeList::~clNoticeList()
{
    delete ui;
}

void clNoticeList::setUI(const int nWidth, const int nHeight)
{
    setGeometry(0, 0, nWidth, nHeight);
    ui->widget_noticelist->setGeometry(0, 0, width(), height());
    ui->widget_op_top->setGeometry(0, 0, width(), g_appInfoPtr->m_fRate*72);
    ui->btn_setRead->setGeometry(ui->widget_op_top->width() - g_appInfoPtr->m_fRate*30 - g_appInfoPtr->m_fRate*120,
                                             (ui->widget_op_top->height() - g_appInfoPtr->m_fRate*32)/2,
                                             g_appInfoPtr->m_fRate*120, g_appInfoPtr->m_fRate*32);
    ui->btn_setRead->setIconSize(QSize(g_appInfoPtr->m_fRate*16, g_appInfoPtr->m_fRate*14));
    ui->btn_setRead->setIcon(QIcon(":/images/btn-notice-set-read.png"));
    ui->tablewt_examList->setGeometry(g_appInfoPtr->m_fRate*30, ui->widget_op_top->height() + g_appInfoPtr->m_fRate*10,
                                      ui->widget_noticelist->width() - g_appInfoPtr->m_fRate*30*2,
                                      ui->widget_noticelist->height() - ui->widget_op_top->height() - g_appInfoPtr->m_fRate*(10 + 62));
    ui->tablewt_examList->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //整行选中的方式
    ui->tablewt_examList->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置为只能选中一行
    ui->tablewt_examList->setSelectionMode(QAbstractItemView::NoSelection);
    //隐藏列表头
    ui->tablewt_examList->verticalHeader()->setVisible(false);
    //隐藏边框
    ui->tablewt_examList->setShowGrid(false);
    //表头不高亮显示
    ui->tablewt_examList->horizontalHeader()->setHighlightSections(false);
    //设置行数
    ui->tablewt_examList->setRowCount(10);
    //设置列数
    ui->tablewt_examList->setColumnCount(3);

    ui->tablewt_examList->setHorizontalScrollMode(QTableWidget::ScrollPerPixel);
    ui->tablewt_examList->horizontalScrollBar()->setSingleStep(g_appInfoPtr->m_fRate*5);
    ui->tablewt_examList->setIconSize(QSize(g_appInfoPtr->m_fRate*36, g_appInfoPtr->m_fRate*36));
    QStringList sHeadStr;
    sHeadStr << QString::fromLocal8Bit("") <<
                QString::fromLocal8Bit("标题") <<
                QString::fromLocal8Bit("发送时间");

    //表头加入checkbox    
    CheckHeaderView *CheckHead = new CheckHeaderView(0, Qt::Horizontal, ui->tablewt_examList);
    connect(CheckHead, &CheckHeaderView::checkboxStateChanged, this, [&](int state){
        for(int i = 0; i < ui->tablewt_examList->rowCount(); i++)
        {
            QCheckBox* chk = dynamic_cast<QCheckBox*>(ui->tablewt_examList->cellWidget(i, 0));
            if(chk)
            {              
                chk->setCheckState((Qt::CheckState)state);
            }
        }
    });
    ui->tablewt_examList->setHorizontalHeader(CheckHead);
    ui->tablewt_examList->setHorizontalHeaderLabels(sHeadStr);

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

    ui->tablewt_examList->verticalHeader()->setDefaultSectionSize(g_appInfoPtr->m_fRate*48);
    ui->tablewt_examList->setColumnWidth(0, g_appInfoPtr->m_fRate*56);
    ui->tablewt_examList->setColumnWidth(1, g_appInfoPtr->m_fRate*940);
    ui->tablewt_examList->setColumnWidth(2, g_appInfoPtr->m_fRate*112);

    ui->tablewt_examList->horizontalHeader()->setStretchLastSection(true);

    
}

void clNoticeList::setNotice(std::vector<CNoticeInfo> vNL)
{
    QString sCheckStyle = QString(R"(QCheckBox
                                  {
                                      outline: none;
                                      height:%1px;

                                      font-size:%2px;
                                      font-family:"Microsoft YaHei";
                                      font-weight:400;
                                      color:rgba(102,102,102,1);
                                  }

                                  QCheckBox::indicator
                                  {
                                      width:%3px;
                                      height:%4px;
                                  }

                                  QCheckBox::indicator:unchecked
                                  {
                                      border: %5px solid rgba(228,229,235,1);
                                      border-radius:%6px;
                                      background:rgba(239,240,245,1);
                                  }

                                  QCheckBox::indicator:checked
                                  {
                                      border-image: url(:/images/icon-checkbox-checked.png);
                                  })").arg((int)(g_appInfoPtr->m_fRate*26))
                                      .arg((int)(g_appInfoPtr->m_fRate*14))
                                      .arg((int)(g_appInfoPtr->m_fRate*14))
                                      .arg((int)(g_appInfoPtr->m_fRate*14))
                                      .arg((int)(g_appInfoPtr->m_fRate*1 < 1 ? 1 : g_appInfoPtr->m_fRate*1))
                                      .arg((int)(g_appInfoPtr->m_fRate*3));
	vNoticeList.clear();
	vNoticeList.assign(vNL.begin(), vNL.end());
	int nSize = vNoticeList.size();
	for (int i = 0; i < nSize; ++i)
	{
		CNoticeInfo ni = vNoticeList[i];
		QCheckBox *chkBox = new QCheckBox;
        chkBox->setStyleSheet(sCheckStyle);
		ui->tablewt_examList->setCellWidget(i, 0, chkBox);

		QWidget *widget = new QWidget;		
		QHBoxLayout *layout = new QHBoxLayout;
		widget->setLayout(layout);
		QLabel *icon = new QLabel;
		icon->setObjectName("icon");
		icon->setFixedSize(QSize(g_appInfoPtr->m_fRate * 16, g_appInfoPtr->m_fRate * 12));
		QString sIconFile = "";
		if (ni.bHasRead)
		{
			sIconFile = ":/images/icon-notice-read.png";
		}
		else
		{
			sIconFile = ":/images/icon-notice-unread.png";
		}
		icon->setPixmap(QPixmap(sIconFile).scaled(g_appInfoPtr->m_fRate * 16, g_appInfoPtr->m_fRate * 12));
		layout->addWidget(icon);
		QMyLabel *text = new QMyLabel(i);
		connect(text, &QMyLabel::sgnClick, this, &clNoticeList::on_tablewt_examList_cellClicked);
		if (ni.bHasRecalled)
		{
			text->setText(QString::fromLocal8Bit("发送者已撤回消息：%1").arg(ni.sTitle));
		}
		else
		{
			text->setText(ni.sTitle);
		}
		text->setFixedWidth(900);
		text->setStyleSheet(QString(R"(QLabel
                                    {
                                        font-size:%1px;
                                        font-family:"Microsoft YaHei";
                                        font-weight:400;
                                        color:rgba(51,51,51,1);
                                    })").arg((int)(g_appInfoPtr->m_fRate * 12)));
		layout->addWidget(text);
		layout->addStretch();

		ui->tablewt_examList->setCellWidget(i, 1, widget);
		ui->tablewt_examList->setItem(i, 2, new QTableWidgetItem(ni.sPublishTime));

	}
}

void clNoticeList::on_tablewt_examList_cellClicked(int row, int column)
{
    if ((int)(vNoticeList.size() - 1) < row ||
            column == 0)
	{
		return;
	}

    showNotice(vNoticeList[row]);
}


void clNoticeList::viewNotice(__int64 nId)
{
    for(CNoticeInfo ni : vNoticeList)
    {
        if(ni.nId == nId)
        {
            showNotice(ni);
        }
    }
}

void clNoticeList::showNotice(CNoticeInfo ni)
{
    if (m_pNoticeDetail == nullptr)
    {
        m_pNoticeDetail = std::make_shared<clNoticeDetail>(ni, this);
        m_pNoticeDetail->setUI(0, 0, width(), height());
        connect(m_pNoticeDetail.get(), &clNoticeDetail::gobackNoticeList, this, [&]() {
            if (m_pNoticeDetail != nullptr)
            {
                m_pNoticeDetail.reset();
            }
        });
    }
    m_pNoticeDetail->show();
    setNoticeRead(QString::number(ni.nId));
}

//noticeId  通知ID，多个以逗号分隔
void clNoticeList::setNoticeRead(QString sIds)
{
    CHttpRequestPackage hrp;
    hrp.sUri = "/api/ecs_exam_work/notice/updateNoticeReadStatus";
    hrp.sParamList.push_back(QString("noticeId,%1").arg(sIds));
    hrp.nRequestType = RequestType::rtUpdateNoticeReadStatus;
    hrp.sCommonStr = sIds;
    g_httpBllPtr->post(hrp);

}

void clNoticeList::on_btn_setRead_clicked()
{
    QStringList list;
    for(int i = 0; i < ui->tablewt_examList->rowCount(); i++)
    {
        QCheckBox* chk = dynamic_cast<QCheckBox*>(ui->tablewt_examList->cellWidget(i, 0));
        if(chk && chk->isChecked())
        {
            list<<QString::number(vNoticeList[i].nId);
        }
    }

    if(list.count() > 0)
    {
        QString sIds = list.join(",");
        setNoticeRead(sIds);
    }
}

void clNoticeList::onUpdateNoticeReadStatus(CUpdateNoticeReadStatus unrs)
{
    if(unrs.nCode == 200)
    {
        QStringList list = unrs.sIds.split(",");
        for(QString sId : list)
        {
            updateReadStatus(sId.toLongLong());
        }
		int unReadCount = 0;
		int nSize = vNoticeList.size();
		for (int i = 0; i < nSize; ++i)
		{
			CNoticeInfo &ni = vNoticeList[i];
			if(!ni.bHasRead)
			{
				++unReadCount;
			 }
		}
		emit unReadNoticeCount(unReadCount);
    }
    else
    {
        if(unrs.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("更新通知状态失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(unrs.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
    }
}

void clNoticeList::updateReadStatus(__int64 nId)
{
	int nSize = vNoticeList.size();
	for (int i = 0; i < nSize; ++i)
	{
		CNoticeInfo &ni = vNoticeList[i];
		if (ni.nId == nId)
		{
			ni.bHasRead = true;
			QString sIconFile = ":/images/icon-notice-read.png";
			QWidget *widget = ui->tablewt_examList->cellWidget(i, 1);
			if (widget)
			{
				QLabel *icon = widget->findChild<QLabel*>("icon");
				if (icon)
				{
					icon->setPixmap(QPixmap(sIconFile).scaled(g_appInfoPtr->m_fRate * 16, g_appInfoPtr->m_fRate * 12));
				}
			}
		}
	}

	emit readNotice(nId);
}
