#include "custom_message_box.h"
#include <QEvent>
#include <QMouseEvent>

#include "find_and_match_ppds.h"
#include "ukui_apt.h"
#include "base_notify_dialog.h"

#include "theme_util.h"
#include "ukui_printer.h"

#include "network_device_monitor.h"
#include "global_variable.h"
#include "common.h"

#include "custom_message_box.h"
#include "choose_ppd_combo_box.h"
#include "add_printer_window.h"
#include "ui_add_printer_window.h"

AddPrinterWindow::AddPrinterWindow(QPoint pos, QWidget *parent)
    : kdk::KDialog(parent)
    , ui(new Ui::AddPrinterWindow)
    , m_parentCenterPos(pos)
{
    initUi();
    //初始化结束后，调用刷新USB按钮
    // TODO:
    //刷新功能使用异步方案
    // connect(DeviceMonitor::getInstance(), &DeviceMonitor::findUsbConnect, this, &AddPrinterWindow::onUsbDeviceAdd);
    // DeviceMonitor::getInstance()->start();
    //启动网络搜索
    connect(NetworkDeviceMonitor::getInstance(), &NetworkDeviceMonitor::findNetworkConnect, this, &AddPrinterWindow::onAutoDeviceAdd);
    NetworkDeviceMonitor::getInstance()->m_sendTestinfo = true;
    NetworkDeviceMonitor::getInstance()->start();
    connect(this, &AddPrinterWindow::showThis, this, &AddPrinterWindow::onShow);
}

AddPrinterWindow::~AddPrinterWindow()
{
    delete bar;
    delete ui;
}

void AddPrinterWindow::initUi()
{
    ui->setupUi(this->mainWidget());

    m_centralWidget = ui->centralWidget;
    m_manualLabel = ui->manualLabel;
    m_manualWidget = ui->manualWidget;
    m_addrEdit = ui->addrEdit;
    m_searchBtn = ui->searchBtn;
    m_protocolLabel = ui->protocolLabel;
    m_protocolComboBox = ui->protocolComboBox;
    m_printerStatus = ui->printerStatus;

    m_devList = ui->devList;
    m_loadingPic = ui->loadingPic;
    m_refreshBtn = ui->refreshBtn;
    m_autoWidget = ui->autoWidget;
    m_autoTableView = ui->autoTableView;

    m_nameLabel = ui->nameLabel;
    m_netLabel = ui->netLabel;
    m_locationLabel = ui->locationLabel;
    m_drvLabel = ui->drvLabel;

    m_nameEdit = ui->nameEdit;
    m_locationEdit = ui->locationEdit;
    m_drvComboBox = ui->drvComboBox;

    m_forwardBtn = ui->forwardBtn;

    setFixedSize(560,616);
    setWindowModality(Qt::ApplicationModal);
    setWindowTitle(tr("Add Printer"));
    setWindowIcon(QIcon::fromTheme("kylin-printer"));
    
    initSwitchArea();
    initCentralWidget();
    initDeviceComponents();
    initBottomArea();

    // setStyleSheet(QString::fromUtf8("border:3px solid blue"));
}

void AddPrinterWindow::initSwitchArea()
{
    bar = new kdk::KTabBar(kdk::KTabBarStyle::SegmentDark, nullptr);
    bar->setFixedSize(240,36);
    bar->addTab(tr("Auto"));
    bar->addTab(tr("Manual"));
    ui->switchLayout->addWidget(bar, Qt::AlignCenter);
    connect(bar, &kdk::KTabBar::currentChanged, [=](int index) {
        switch (index) {
        case 0:
            onAutoClicked();
            break;
        case 1:
            onManualClicked();
            break;
        default:
            break;
        }
    });
}

void AddPrinterWindow::initCentralWidget()
{
    initAutoWidget();
    initManualWidget();
}

void AddPrinterWindow::initAutoWidget()
{
    m_devList->setText(tr("Device List"));
    m_refreshBtn->setIcon(QIcon::fromTheme("view-refresh-symbolic"));
    connect(m_refreshBtn, &QPushButton::clicked, this, &AddPrinterWindow::onRefreshClicked);

    // 设置表头隐藏
    m_autoTableView->horizontalHeader()->setHidden(true);
    m_autoTableView->verticalHeader()->setHidden(true);
    // 隔行变色
    m_autoTableView->setAlternatingRowColors(true);
    // 不显示网格线
    m_autoTableView->setShowGrid(false);
    // 禁用双击编辑
    m_autoTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_autoTableView->setColumnWidth(0, 494);
    m_autoTableView->horizontalHeader()->setDefaultSectionSize(494);
    m_autoTableView->verticalHeader()->setDefaultSectionSize(36);
    // 设置右键触发customContextMenuRequested信号
    m_autoTableView->setContextMenuPolicy(Qt::CustomContextMenu);

    m_autoSearchResultModel = new AutoSearchResultModel();
    m_autoTableView->setModel(m_autoSearchResultModel);
    connect(m_autoTableView, &QTableView::clicked, [=](const QModelIndex &index) {
        DeviceInformation info = m_autoSearchResultModel->getInfo(index);
        onDeviceUpdated(info);
    });
    connect(m_autoTableView, &QTableView::customContextMenuRequested, [=](const QPoint& pos) {
        int row = m_autoTableView->indexAt(pos).row();
        qDebug() << row;
        if (row < 0 && m_autoSearchResultModel->rowCount() < row) {
            clearDeviceArea();
        }
    });
}

void AddPrinterWindow::initManualWidget()
{
    m_manualLabel->setText(tr("Manual"));
    m_protocolLabel->setText(tr("Protocol"));
    m_netLabel->setText(tr("Address"));
    QRegExp rx_ip("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|"
                  "2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
    m_addrEdit->setValidator(new QRegExpValidator(rx_ip, this));
    m_addrEdit->setClearButtonEnabled(true);
    connect(m_addrEdit, &QLineEdit::textChanged, this, &AddPrinterWindow::onAddrChanged);
    connect(m_addrEdit, &QLineEdit::returnPressed, this, &AddPrinterWindow::onSearchClicked);

    m_searchBtn->setText(tr("Search"));
    connect(m_searchBtn, &QPushButton::clicked, this, &AddPrinterWindow::onSearchClicked);
    m_searchBtn->setEnabled(false);
    m_printerStatus->setStyleSheet("color:red");

    m_protocolComboBox->addItem(tr("socket"));
    m_protocolComboBox->addItem(tr("ipp"));
    m_protocolComboBox->addItem(tr("http"));
    m_protocolComboBox->setCurrentIndex(0);
}

void AddPrinterWindow::initDeviceComponents()
{
    m_nameLabel->setText(tr("name"));
    m_locationLabel->setText(tr("location"));
    m_drvLabel->setText(tr("driver"));
}

void AddPrinterWindow::initBottomArea()
{
    m_forwardBtn->setText(tr("forward"));
    connect(m_forwardBtn, &QPushButton::clicked, this, &AddPrinterWindow::onForwardClicked);
}

void AddPrinterWindow::clearDeviceArea()
{
    clearDeviceComponent();
    m_autoSearchResultModel->clearUsbPrinter();
}

void AddPrinterWindow::clearDeviceComponent()
{
    m_nameEdit->setEnabled(false);
    m_locationEdit->setEnabled(false);
    m_drvComboBox->setEnabled(false);
    m_locationEdit->clear();
    m_nameEdit->clear();
    m_drvComboBox->clear();
    m_deviceInfo = DeviceInformation();
    m_forwardBtn->setEnabled(false);
    m_autoTableView->clearSelection();
}

void AddPrinterWindow::onForwardClicked()
{
    qDebug() << __FUNCTION__;
    if (m_drvComboBox->isEmpty()) {
        //弹出一个提示窗口，然后返回(安装失败，请重试)
        CustomMessageBox Msg(CustomMessageBox::Critical, tr("Error"), tr("Add printer failed: no PPD selected!"),
                        CustomMessageBox::NoButton);
        Msg.exec();
        return ;
    }
    bool ret = false;
    ret = UkuiPrinterManager::getInstance().addPrinter(m_deviceInfo.uri, m_nameEdit->text(), m_drvComboBox->currentText(), m_locationEdit->text());
    if (ret == false) {
        //弹出一个提示窗口，然后返回(安装失败，请重试)
        CustomMessageBox Msg(CustomMessageBox::Critical, tr("Error"), tr("Add printer failed，please retry after a while."),
                        CustomMessageBox::NoButton);
        Msg.setParent(this);
        QPushButton *btnYes = Msg.addButton(tr("Confirm"), CustomMessageBox::YesRole);
        return;
    }
    CustomMessageBox msg1(CustomMessageBox::Question,tr("Hint"), tr("Add printer successfully，printer a test page？"), CustomMessageBox::NoButton);
    msg1.setParent(this);
    QPushButton *btnYes = msg1.addButton(tr("Print test page"), CustomMessageBox::YesRole);
    QPushButton *btnNo  = msg1.addButton(tr("Check Printer"), CustomMessageBox::NoRole);
    msg1.exec();
    if ((QPushButton*)msg1.clickedButton() == btnYes) {
        // TODO:打开打印测试页窗口
        UkuiPrinterManager::getInstance().printTestPage(m_nameEdit->text());
        CustomMessageBox msg2(CustomMessageBox::Question,tr("Hint"), tr("Is the test page printed successfully?"), CustomMessageBox::NoButton);
        msg2.setParent(this);
        QPushButton *btnYes = msg2.addButton(tr("Yes"), CustomMessageBox::YesRole);
        QPushButton *btnNo  = msg2.addButton(tr("No"), CustomMessageBox::NoRole);
        msg2.exec();
        if ((QPushButton*)msg2.clickedButton() == btnYes) {
            // TODO 通知主窗体显示这台打印机？
            emit needUpdateDests(m_nameEdit->text());
            close();
        } else if ((QPushButton*)msg2.clickedButton() == btnNo) {
            CustomMessageBox msg3(CustomMessageBox::Question,tr("Hint"), tr("Test print failed.Do you want to change a printer driver?"), CustomMessageBox::NoButton);
            msg3.setParent(this);
            QPushButton *btnYes = msg3.addButton(tr("Change Driver"), CustomMessageBox::YesRole);
            QPushButton *btnNo  = msg3.addButton(tr("Cancel"), CustomMessageBox::NoRole);
            msg3.exec();
            if ((QPushButton*)msg3.clickedButton() == btnNo) {
                // TODO:删除当前打印机
                // UkuiPrinterManager::getInstance().removePrinter(m_nameEdit->text());
                close();
            } else if ((QPushButton*)msg3.clickedButton() == btnYes) {
                // TODO:确定显示到哪个页面？
                return;
            }
        }

    } else if ((QPushButton*)msg1.clickedButton() == btnNo) {
        // TODO:发送信号，通知主窗体显示这次添加的打印机
        emit needUpdateDests(m_nameEdit->text());
        close();
    }
}

void AddPrinterWindow::onSearchClicked()
{
    qDebug() << __FUNCTION__ << m_addrEdit->text();
    QString ipAddr = m_addrEdit->text();
    m_printerStatus->setText(tr("Searching..."));
    // TODO:Call add network printer interface,like snmp interface to get printer info
    // DeviceInformation info = NetworkDeviceMonitor::getInstance()->getDeviceFromIP(ipAddr);

    QPoint windowCenter = QPoint(this->mapToGlobal(QPoint(0,0)).x() + this->width()/2,this->mapToGlobal(QPoint(0,0)).y() + this->height()/2);

    BaseNotifyDialog dialog(this);
    dialog.hide();
    dialog.dialogSetType(BaseNotifyDialogType::WAITTING);
    dialog.labelSetText(tr("Searching printers..."));
    dialog.show();

    dialog.move(windowCenter - dialog.rect().center());

    DeviceInformation info;
    connect(NetworkDeviceMonitor::getInstance(), &NetworkDeviceMonitor::getDeviceFromIP_cb, &dialog, &QDialog::close);
    connect(NetworkDeviceMonitor::getInstance(), &NetworkDeviceMonitor::getDeviceFromIP_cb, this, &AddPrinterWindow::handleDeviceFromIP,Qt::UniqueConnection);
    //connect(NetworkDeviceMonitor::getInstance(), &NetworkDeviceMonitor::getDeviceFromIP_cb, this, &addPrinterWindow::handleDeviceFromIP);

    ProtocolType type;
    switch (m_protocolComboBox->currentIndex())
    {
    case 0:
        type = ProtocolType::SOCKET;
        break;
    case 1:
        type = ProtocolType::IPP;
        break;
    case 2:
        type = ProtocolType::HTTP;
        break;
    default:
        break;
    }
    emit NetworkDeviceMonitor::getInstance()->getDeviceFromIP_async(ipAddr, 9100, type);
    dialog.showThis();
}

void AddPrinterWindow::handleDeviceFromIP(DeviceInformation &info)
{
    if (info.connectType == ConnectType::InfoFrom_Invalid) {
        m_printerStatus->setText(tr("Can not find this Printer!"));
        return;
    } else {
        m_printerStatus->setText("");
    }

    onDeviceUpdated(info);
    return;
}

void AddPrinterWindow::onRefreshClicked()
{
    qDebug() << __FUNCTION__;
    m_refreshBtn->setEnabled(false);
    clearDeviceArea();
    QPoint windowCenter = QPoint(this->mapToGlobal(QPoint(0,0)).x() + this->width()/2,this->mapToGlobal(QPoint(0,0)).y() + this->height()/2);

    BaseNotifyDialog dialog(this);
    dialog.hide();
    dialog.dialogSetType(BaseNotifyDialogType::WAITTING);
    dialog.labelSetText(tr("Searching printers..."));
    dialog.show();
    dialog.move(windowCenter - dialog.rect().center());

    connect(this, SIGNAL(installEnd()), &dialog, SLOT(close()));
    getUsbPrinterThread* usbThread = new getUsbPrinterThread();
    connect(usbThread, &getUsbPrinterThread::recvUsbPrinter, this, &AddPrinterWindow::onAutoDeviceAdd);
    connect(usbThread, &getUsbPrinterThread::finished, [=]() {
        m_refreshBtn->setEnabled(true);
        emit installEnd();
    });
    usbThread->startWorker();
    dialog.exec();
}

void AddPrinterWindow::onAutoClicked()
{
    m_centralWidget->setCurrentWidget(m_autoWidget);
    clearDeviceArea();
    onRefreshClicked();
}

void AddPrinterWindow::onManualClicked()
{
    m_centralWidget->setCurrentWidget(m_manualWidget);
}

void AddPrinterWindow::onAutoDeviceAdd(DeviceInformation& device)
{
    qDebug() << device;
    qDebug() << "IN";
    if (device.connectType == ConnectType::InfoFrom_USB || 
        device.connectType == ConnectType::InfoFrom_NETWORK_DETECT && device.protocolType == ProtocolType::IPP) {

        m_autoSearchResultModel->addPrinter(device);
    }
}

void AddPrinterWindow::onDeviceUpdated(DeviceInformation& info)
{
    qDebug() << "IN";
    // Update device area values.
    // TODO table update

    QString desc = info.vendor + "-" + info.model;
    desc.replace(QRegExp("\\ "), "-");
    if (desc.compare("") == 0) {
        return;
    }
    m_nameEdit->setEnabled(true);
    m_locationEdit->setEnabled(true);
    m_drvComboBox->setEnabled(true);
    m_nameEdit->setText(desc);

    m_locationEdit->setText("");
    m_drvComboBox->clear();
    m_deviceInfo = info;

    //自己画一个窗口，
    m_installOk = 1;
    QPoint windowCenter = QPoint(this->mapToGlobal(QPoint(0,0)).x() + this->width()/2,this->mapToGlobal(QPoint(0,0)).y() + this->height()/2);

    BaseNotifyDialog dialog(this);
    dialog.hide();
    dialog.dialogSetType(BaseNotifyDialogType::WAITTING);
    dialog.labelSetText(tr("Searching printer driver..."));
    dialog.show();
    dialog.move(windowCenter - dialog.rect().center());
    connect(g_findAndMatchWorkThread, &FindAndMatchPPDs::updateFinished, &dialog, &QDialog::close);
    connect(g_findAndMatchWorkThread, &FindAndMatchPPDs::updateFailed, &dialog, &QDialog::close);
    connect(this, SIGNAL(installEnd()), &dialog, SLOT(close()));

    AptUtilHelper* aptHelper = new AptUtilHelper(m_deviceInfo);
    connect(aptHelper, &AptUtilHelper::succeed, [=]() {
        qDebug() << "Install succeed";
        m_installOk = 0;
        g_findAndMatchWorkThread->updatePPDsMap();
    });
    connect(aptHelper, &AptUtilHelper::failed, [=]() {
        qDebug() << "Install failed";
        m_installOk = 1;
        emit installEnd();
    });
    aptHelper->startWorker();
    dialog.exec();
    if (m_installOk == 1) {
        CustomMessageBox Msg(
            CustomMessageBox::Warning, tr("Warning"), tr("Install driver package automatically failed,continue?"), CustomMessageBox::NoButton);
        Msg.setParent(this);
        QPushButton *btnYes = Msg.addButton(tr("Confirm"), CustomMessageBox::YesRole);
        QPushButton *btnNo  = Msg.addButton(tr("Cancel"), CustomMessageBox::NoRole);
        Msg.exec();
        if ((QPushButton*)Msg.clickedButton() == btnNo) {
            m_autoTableView->clearSelection();
            clearDeviceComponent();
            return;
        }
    }

    QString ppd;
    QStringList ppdList;
    int ret = g_findAndMatchWorkThread->matchPPDToPrinter(m_deviceInfo.vendor, m_deviceInfo.model, ppd, ppdList);
    if (ret != 0) {
        qDebug() << ret;
    }

    if (ppd.compare("") != 0) {
        qDebug("完全匹配");
        m_drvComboBox->addItem(ppd);
    } else {
        QStringList ppds = ppdList;
        qDebug() << ppds.size();
        if (ppds.size() == 0) {
            return;
        }
        m_drvComboBox->addItems(ppds);
    }
    if (!checkPrinterNameIsLegal(false)) {
        m_forwardBtn->setEnabled(false);
    } else {
        m_forwardBtn->setEnabled(true);
    }
}

void AddPrinterWindow::onAddrChanged(const QString& ipAddr)
{
    qDebug() << ipAddr;
    m_searchBtn->setEnabled(ipIsValid(ipAddr));
}

void AddPrinterWindow::onNameEditChanged() {
    checkPrinterNameIsLegal(true);
}

bool AddPrinterWindow::checkPrinterNameIsLegal(bool hasMessageBox)
{
    if (m_nameEdit->text() == "") {
        m_forwardBtn->setEnabled(false);
        return false;
    }
    if (printerNameIsLegal(m_nameEdit->text()) == false) {
        m_forwardBtn->setEnabled(false);
        if (hasMessageBox) {
            QString warningMsg = tr("Printer Name Cannot Contains '/\\'\"?#', And More Than 0 Letter, Less Than 128 Letters !");
            CustomMessageBox Msg(CustomMessageBox::Warning, tr("Warning"), warningMsg, CustomMessageBox::NoButton);
            Msg.setParent(this);
            Msg.addButton(tr("Close"), CustomMessageBox::NoRole);
            Msg.exec();
        }
        m_forwardBtn->setEnabled(false);
        return false;
    } else {
        QList<UkuiUsbPrinter> allPrintersVector;
        UkuiPrinterManager::getInstance().enumPrinters(allPrintersVector);
        for (auto it : allPrintersVector) {
            qDebug() << m_nameEdit->text();
            qDebug() << it.name;
            if (!m_nameEdit->text().compare(it.name, Qt::CaseSensitive)) {
                if (hasMessageBox) {
                    QString warningMsg = tr("Exist Same Name Printer!");
                    CustomMessageBox Msg(CustomMessageBox::Warning, tr("Warning"), warningMsg, CustomMessageBox::NoButton);
                    Msg.setParent(this);
                    Msg.addButton(tr("Close"), CustomMessageBox::NoRole);
                    Msg.exec();
                }

                m_forwardBtn->setEnabled(false);
                return false;
            } else if (!m_nameEdit->text().compare(it.name, Qt::CaseInsensitive)) {
                if (hasMessageBox) {
                    QString warningMsg = tr("Printer Name Illegal!");
                    CustomMessageBox Msg(CustomMessageBox::Warning, tr("Warning"), warningMsg, CustomMessageBox::NoButton);
                    Msg.setParent(this);
                    Msg.addButton(tr("Close"), CustomMessageBox::NoRole);
                    Msg.exec();
                }

                m_forwardBtn->setEnabled(false);
                return false;
            } else {
                continue;
            }
        }
        m_forwardBtn->setEnabled(true);
    }
    return true;
}



void AddPrinterWindow::onShow(QPoint pos)
{
    m_nameEdit->setEnabled(false);
    m_locationEdit->setEnabled(false);
    m_drvComboBox->setEnabled(false);
    m_parentCenterPos = pos;

    qDebug() << "Set addPrinterWindow to toplevel.";
    move(pos - rect().center());
    if (!isActiveWindow()) {
        hide();
        show();
    }
    show();
    raise();
    activateWindow();
    // Clear all other area... and then refresh all
    m_addrEdit->clear();
    m_printerStatus->setText("");
    bar->tabBarClicked(0);
    onRefreshClicked();
}

void AddPrinterWindow::setQSSFontSize(QFont curFont)
{

}

void AddPrinterWindow::manualInstall(DeviceInformation& info)
{
    if (info.connectType == ConnectType::InfoFrom_USB) {
        // for (auto btn : m_listUsbDev) {
        //     if (btn->getInfo().uri == info.uri) {
        //         emit btn->click();
        //         return;
        //     }
        // }
    } else if (info.connectType == ConnectType::InfoFrom_NETWORK_DETECT) {
        // for (auto btn : m_listNetDev) {
        //     if (btn->getInfo().uri == info.uri) {
        //         emit btn->click();
        //         return;
        //     }
        // }
    } else {
        return;
    }
}

bool AddPrinterWindow::eventFilter(QObject* watched, QEvent* event)
{
    if (watched == m_autoTableView) {
        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            QPoint p = mouseEvent->pos();
            qDebug() << p;
            QModelIndex index = m_autoTableView->indexAt(p);
            if (!index.isValid()) {
                clearDeviceArea();
            } else {
                qDebug() << index.row();
            }
        }
    }
    return kdk::KDialog::eventFilter(watched, event);
}

getUsbPrinterThread::getUsbPrinterThread(QObject* parent)
    : QObject(parent)
{
    m_thread = new QThread;
    moveToThread(m_thread);
    connect(m_thread, &QThread::started, this, &getUsbPrinterThread::startSearch);
    connect(this, &getUsbPrinterThread::finished, m_thread, &QThread::quit);
    connect(this, &getUsbPrinterThread::finished, this, &getUsbPrinterThread::deleteLater);
    connect(m_thread, &QThread::finished, m_thread, &QThread::deleteLater);
}
void getUsbPrinterThread::startSearch()
{
    QList<DeviceInformation> devices = DeviceMonitor::getInstance()->getAllPrinterConnected();
    qDebug() << devices.size();
    for (DeviceInformation device : devices) {
        emit recvUsbPrinter(device);
    }
    emit finished();
}


AutoSearchResultModel::AutoSearchResultModel(QStandardItemModel *parent)
    : QStandardItemModel(parent)
{
    setColumnCount(1);
    m_devInfoList = new QMap<QString, DeviceInformation>;
}

AutoSearchResultModel::~AutoSearchResultModel()
{
    delete m_devInfoList;
}

void AutoSearchResultModel::addPrinter(const DeviceInformation &info)
{
    static QMutex mutex;
    qDebug() << info.makeAndModel;
    mutex.lock();
    insertRow(0);
    QString type = QString("");
    switch (info.connectType)
    {
    case ConnectType::InfoFrom_USB :
        type = "USB";
        break;
    case ConnectType::InfoFrom_NETWORK_DETECT :
        if (info.protocolType == ProtocolType::IPP)
        type = tr("network");
        break;
    default:
        break;
    }
    if (type == QString("")) {
        mutex.unlock();
        return;
    }
    QString displayName = QString("(%1)%2").arg(type).arg(info.vendor + "-" + info.model);
    displayName.replace(QRegExp("\\ "), "-");

    setData(index(0, 0), displayName);
    m_devInfoList->insert(displayName, info);
    mutex.unlock();
}

void AutoSearchResultModel::clearUsbPrinter()
{
    // 沿用之前的逻辑，如果是usb则清空；如果是网络打印机则不清空
    auto list = findItems("(usb)", Qt::MatchContains);
    for (auto item : list) {
        int row = item->row();
        QString displayName = index(row, 0).data().toString();
        qDebug() << displayName << " " << row;
        removeRow(row);
        m_devInfoList->remove(displayName);
    }
}

void AutoSearchResultModel::clearAllPrinter()
{
    // 沿用之前的逻辑，如果是usb则清空；如果是网络打印机则不清空
    clear();
    setColumnCount(1);
    m_devInfoList->clear();
}

DeviceInformation AutoSearchResultModel::getInfo(const QModelIndex &index)
{
    QString displayName = index.data().toString();
    auto it = m_devInfoList->find(displayName);
    return it.value();
}