#include "TaskListWidget.h"
#include "ui_TaskListWidget.h"

#include "calibration/CalibrationMainForm.h"

TaskListWidget::TaskListWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TaskListWidget)
{
    ui->setupUi(this);
    parentForm = (CalibrationMainForm *)parent;

    initForm();
    initFormTable();

    // 绑定信号与槽
    connect(ui->tableTaskTBDList, &QPagedTable::reloadTablePagedData, this, &TaskListWidget::getTaskToBeDoneList);
}

TaskListWidget::~TaskListWidget()
{
    qDebug() << "~TaskListWidget";
    delete ui;
}

void TaskListWidget::showEvent(QShowEvent * event)
{
    ui->tableTaskTBDList->adjustTableWidth();
    getTaskToBeDoneList(0);
}

void TaskListWidget::resizeEvent(QResizeEvent * event)
{
    ui->tableTaskTBDList->adjustTableWidth();
}

void TaskListWidget::initForm()
{
    // 加载样式表
    QString qssStyle = QssFileUtils::loadQssFileContent(":/qss/infoTable.css");
    if (qssStyle.isEmpty() == false) {
        this->setStyleSheet(qssStyle); // 仅本窗口生效
    }

    // 查询条件的样式
    QList<QWidget *> children = ui->wdgtQueryBox->findChildren<QWidget *>();
    for (QWidget * wdgt : children) {
        wdgt->setProperty("class", "queryBox");

        if (QString(wdgt->metaObject()->className()).contains("QLineEdit")) {
            // 绑定输入框回车事件 只在密码输入框执行
            connect((QLineEdit *)wdgt, &QLineEdit::returnPressed, this, [=](){
                emit ui->btnQuery->clicked();
            });
        }
    }

    // 查询和重置按钮
    ui->btnQuery->setProperty("class", "btnDefault");
    ui->btnResetQuery->setProperty("class", "btnResetQuery");

    ui->tableTaskTBDList->setTableProperty("class", "defaultTable");

    // 分页组件
    QStringList btnPageGroupUrls;
    btnPageGroupUrls << ":/image/infomation/btnPageFirst.png" << ":/image/infomation/btnPagePre.png"
                     << ":/image/infomation/btnPageNext.png" << ":/image/infomation/btnPageLast.png";
    ui->tableTaskTBDList->setPageButtonIcons(btnPageGroupUrls);
    ui->tableTaskTBDList->setPageButtonProperty("class", "pageBtnGroup");
}

void TaskListWidget::initFormTable()
{
    // 初始化查询条件
    SysLocalService localServ;
    QList<QMap<QString, QVariant>> deptTaskColumns = localServ.getInfomationTableColumns("deptTask");
    ui->tableTaskTBDList->setColumns(deptTaskColumns);

    ui->tableTaskTBDList->setMultiCheckType(QPagedTable::MultiCheckType::MULTI);
    ui->tableTaskTBDList->setCheckBoxClass("defaultSolid");

    ui->tableTaskTBDList->setDataRowHeight(45);

    connect(ui->tableTaskTBDList, &QPagedTable::tableRowSelected, this, &TaskListWidget::rowSelectedHandler);

    initUrgentSelect();

    ui->tableTaskTBDList->initTableWidget();
    ui->tableTaskTBDList->initTableHeader();
}

void TaskListWidget::initUrgentSelect()
{
    ui->selectUrgent->addItem("全部", "");
    ui->selectUrgent->addItem("不加急", "0");
    ui->selectUrgent->addItem("加急", "1");

    ui->selectUrgent->setView(new QListView()); // 使ComboBox下拉选项 的QSS生效的关键代码
}

void TaskListWidget::getTaskToBeDoneList(int currPage)
{
    TaskService taskServ;
    taskList.clear(); // 清除之前的结果

    // 获取所有查询条件
    TaskRequest request;
    request.userId = ProMemory::getInstance().getLoginUser().value("id").toString();
    request.sampleName = ui->inputDevName->text();
    request.sampleModel = ui->inputDevModel->text();
    request.customerName = ui->inputCustomer->text();
    request.measureStatusList << "3" << "2";
    request.isUrgent = ui->selectUrgent->currentData().toString();

    // 查询页
    page.currentPage = currPage;

    // 查询数据库
    taskList = taskServ.getDeptTaskListPage(request, page);
    QList<QMap<QString, QVariant>> pageData;
    for (TaskDTO task : taskList) {
        QMap<QString, QVariant> item;

        item.insert("id", task.id);
        item.insert("name", task.sampleName);
        item.insert("model", task.sampleModel);
        item.insert("serialNo", task.manufactureNo);
        item.insert("maker", task.manufacturer);
        item.insert("custom", task.customerName);
        item.insert("requireTime", task.requireOverTime);
        item.insert("isUrgent", task.isUrgentName);
        item.insert("orderNo", task.orderNo);
        item.insert("measureStatus", task.measureStatusName);

        pageData.append(item);
    }

    // 设置分页表格数据
    ui->tableTaskTBDList->setTotalCount(page.totalCount);
    ui->tableTaskTBDList->setDatas(pageData);

    // 筛选 加急=是 的单元格标红提示
    QList<int> matchedRows = ui->tableTaskTBDList->filterCells("isUrgent", "是");
    if (!matchedRows.isEmpty()) {
        for (int row : matchedRows) {
            ui->tableTaskTBDList->getTableInstance()->item(row, 10)->setForeground(QBrush("#FF0000")); // 多加了一列复选框
        }
    }

    // 勾选上已经选中的记录
    for (int i = 0; i < taskList.size(); i++) {
        ui->tableTaskTBDList->setRowSelected(i, parentForm->getSelectedTask().contains(taskList.at(i).sampleId));
    }
}

void TaskListWidget::rowSelectedHandler(int rowIdx, bool selected)
{
    QString rowId = taskList.at(rowIdx).sampleId;
    if (selected) {
        parentForm->getSelectedTask().insert(rowId, taskList.at(rowIdx));
    } else {
        parentForm->getSelectedTask().remove(rowId);
    }
}

void TaskListWidget::on_btnQuery_clicked()
{
    getTaskToBeDoneList(0);
}

void TaskListWidget::on_btnResetQuery_clicked()
{
    ui->inputDevName->setText("");
    ui->inputDevModel->setText("");
    ui->inputCustomer->setText("");

    ui->selectUrgent->setCurrentIndex(0);

    getTaskToBeDoneList(0);
}


void TaskListWidget::on_btnNextToConf_clicked()
{
    if (parentForm->getSelectedTask().size() == 0) {
        CustomMessageBox::warning(this, "提示", "请选择被检设备！");
    } else {
        // 判断多个被检设备 分类和量程是否都相同
        TaskService taskServ;
        QStringList itemCats = taskServ.getVerificationItemCatsBySelectedTask(parentForm->getSelectedTask().keys());

        if (itemCats.size() == 1) {
            parentForm->setVerificationItemCatIds(itemCats);
            emit taskEquipmentSelected();
        } else if (itemCats.isEmpty()) {
            CustomMessageBox::warning(this, "提示", "没找到所选待检设备的检定项分类，请检查相关配置");
        } else {
            qDebug() << itemCats;
            CustomMessageBox::warning(this, "提示", "所选的多个待检设备检定项目不同，请重新选择");
        }
    }
}
