#include "mainwindow.h"
#include "src/view/ui_mainwindow.h"
#include "src/view/burndata.h"
#include "src/view/burnimage.h"
#include "src/view/copyimage.h"
#include "src/view/modaldialog.h"
#include "src/view/execdialog.h"
#include "src/view/viewfilterfiles.h"
#include "src/view/filefilterrules.h"
#include "src/view/kybaboutdialog.h"
#include "src/view/tip_burnresult.h"
#include "src/frame/xatom-helper.h"
#include "src/frame/logger.h"
#include "src/frame/signals.h"
#include "src/frame/configuration.h"
#include "src/po/translation.h"
#include "src/model/logicmain.h"
#include "src/model/monitorcdrom.h"
#include "src/model/menufactory.h"
#include "src/data/datacdrom.h"

#include <pwd.h>
#include <unistd.h>

#include <fstream>
#include <QPair>
#include <QtDBus>
#include <QDBusInterface>
#include <QDebug>
#include <QPainter>
#include <QPainterPath>
#include <QFileInfo>
#include <QMoveEvent>
#include <QFileSystemWatcher>
#include <QSharedMemory>
#include <QDBusReply>
#include <KF5/KWindowSystem/kwindowsystem.h>
#include <ukuistylehelper.h>
#include <kysdk/diagnosetest/libkydatacollect.h>
using namespace kdk;

#define ICON_SIZE QSize(26, 26)

MainWindow::MainWindow(QStringList args, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_oGroup(new QButtonGroup(this))
{
    //判断是否是平板
    QDBusConnection sessionBus1 = QDBusConnection::sessionBus();

    QDBusMessage m = QDBusMessage::createMethodCall(QString("com.kylin.statusmanager.interface"),
                                                    QString("/"),
                                                    QString("com.kylin.statusmanager.interface"),
                                                    QString("get_current_tabletmode"));

    QDBusMessage res = sessionBus1.call(m);
    if (res.type() == 1 || res.type() == 2){

        m_isTabletMode = res.arguments().first().toBool();
         qInfo()<<"m_isTabletMode"<<m_isTabletMode;
    }
    else{
        qInfo()<<"m_isTabletMode"<<m_isTabletMode;

        m_isTabletMode = false;
    }
    //切换模式
    QDBusConnection::sessionBus().connect(QString("com.kylin.statusmanager.interface"),
                                          QString("/"),
                                          QString("com.kylin.statusmanager.interface"),
                                          QString("mode_change_signal"), this,
                                          SLOT(uiModeChange(bool)));
    QFont f; // 调整导航栏字体
    QPoint p;
    QUrl url;
    QFileInfo file;

    ui->setupUi(this);
    uiAdjust();

    m_oCDROMS.clear();

    //判断是否是wayland环境
    if(QString(qgetenv("XDG_SESSION_TYPE")) == "wayland") {
        kdk::UkuiStyleHelper::self()->removeHeader(this);
    } else {
        MotifWmHints hints;
        hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
        hints.functions = MWM_FUNC_ALL;
        hints.decorations = MWM_DECOR_BORDER;
        XAtomHelper::getInstance()->setWindowMotifHint(winId(), hints);
    }

    // 日志记录打印
    connect(this, SIGNAL(info(QString)), LOGGER, SLOT(info(QString)));
    connect(this, SIGNAL(warn(QString)), LOGGER, SLOT(warn(QString)));
    connect(this, SIGNAL(error(QString)), LOGGER, SLOT(error(QString)));
    connect(this, SIGNAL(debug(QString)), LOGGER, SLOT(debug(QString)));
    LOGGER->registerName(this, _("MainWindow"));

    connect(g_user_signal, SIGNAL(changeBtnBusnessName()), this, SLOT(slotsChangeBtnBusnessName()));


    if (started())
    {
#if 0
        //刻录是单例，使用弹窗提醒应用已存在
        error(_("Burner has started..."));
        EXEC->information(_("Starting"), _("Burner has been started,"
                                           "do not start again."), true);
        exit(0);
#else
        //刻录是单例，再次点击图标将主界面放在最前面
        QDBusInterface interface( "com.kylin.burner.manager",
                                  "/com/kylin/burner/manager",
                                  "com.kylin.burner.manager",
                                  QDBusConnection::sessionBus());

        QDBusReply<int> reply = interface.call( "slotsReShowMainWindow");
        if ( reply.isValid() && reply.value() == 0)
        {
            //qDebug( "%d", reply.value());          // prints 4
            qDebug()<<"The kylin-burner process is running";
        }
        else
        {
            qDebug() << "fail";
        }
        qDebug()<<"The kylin-burner process is already running";
        exit(0);

#endif
    }

    QDBusConnection sessionBus = QDBusConnection::sessionBus();
    if(sessionBus.registerService("com.kylin.burner.manager"))
    {
        sessionBus.registerObject("/com/kylin/burner/manager",this,
                                  QDBusConnection::ExportAllContents);
        qDebug()<<"初始化DBUS成功";
    }
    else
    {
        info("init dbus error");
        qDebug() << sessionBus.lastError();
        qDebug()<<"初始化DBUS失败";
    }


    // 初始化业务界面
    connect(PAGE_BurnData, SIGNAL(busness(bool)), this, SLOT(slotsBusness(bool)));
    // connect(PAGE_BurnData, SIGNAL(busness(bool)), MENU, SIGNAL(setSetting(bool)));
    connect(PAGE_BurnData, SIGNAL(updateDisk(int,void*)), this, SLOT(slotsUpdateDisk(int,void*)));
    connect(PAGE_BurnImage, SIGNAL(busness(bool)), this, SLOT(slotsBusness(bool)));
    // connect(PAGE_BurnImage, SIGNAL(busness(bool)), MENU, SIGNAL(setSetting(bool)));
    connect(PAGE_CopyImage, SIGNAL(busness(bool)), this, SLOT(slotsBusness(bool)));
    // connect(PAGE_CopyImage, SIGNAL(busness(bool)), MENU, SIGNAL(setSetting(bool)));
    connect(PAGE_CopyImage, SIGNAL(busness(int)), this, SLOT(slotsChangeName(int)));
    ui->stackedWidget->addWidget(PAGE_BurnData);
    ui->stackedWidget->addWidget(PAGE_BurnImage);
    ui->stackedWidget->addWidget(PAGE_CopyImage);

    ui->navTitle->onlyShowLogo();
    ui->burnerTitle->onlyShowButton();
    // 自定义标题栏
    connect(this, SIGNAL(windowIconChanged(QIcon)), ui->navTitle, SLOT(onWindowIconChange(QIcon)));
    connect(this, SIGNAL(windowTitleChanged(QString)), ui->navTitle, SLOT(onWindowTitleChange(QString)));
    connect(this, SIGNAL(windowIconChanged(QIcon)), ui->burnerTitle, SLOT(onWindowIconChange(QIcon)));
    connect(this, SIGNAL(windowTitleChanged(QString)), ui->burnerTitle, SLOT(onWindowTitleChange(QString)));
    connect(ui->navTitle, SIGNAL(close()), this, SLOT(close()));
    connect(ui->navTitle, SIGNAL(min()), this, SLOT(showMinimized()));
    connect(ui->navTitle, &WindowTitle::max, [=](){
        if (Qt::WindowMaximized == windowState())
        {
            showNormal();
            ui->burnerTitle->onWindowShowMaxed(false);
        }
        else
        {
            showMaximized();
            ui->burnerTitle->onWindowShowMaxed(true);
        }
    });
    connect(ui->burnerTitle, SIGNAL(close()), this, SLOT(close()));
    connect(ui->burnerTitle, SIGNAL(min()), this, SLOT(showMinimized()));
    connect(ui->burnerTitle, &WindowTitle::max, [=](){
        if (Qt::WindowMaximized == windowState())
        {
            showNormal();
            ui->burnerTitle->onWindowShowMaxed(false);
        }
        else
        {
            showMaximized();
            ui->burnerTitle->onWindowShowMaxed(true);
        }
    });

    //图标库主题的刻录图片名换为burner
    setWindowIcon(QIcon::fromTheme("burner"));
    setWindowTitle(_("Burner"));
    ui->nav->setFocus();
    //setFocusPolicy(Qt::NoFocus);

    f = ui->btnBurnData->font();
    //f.setPointSize(15);
    f.setPixelSize(14);
   // ui->btnBurnData->setFont(f);
 //   ui->btnBurnData->setText(_("BurnData"));
   // ui->btnBurnData->setToolTip(_("BurnData"));
   // ui->btnBurnData->setIconSize(ICON_SIZE);
  //  ui->btnBurnData->setIcon(QIcon(":/burnData.png"));
  //  connect(ui->btnBurnData, SIGNAL(clicked(bool)), this, SLOT(slotsBurnData()));
    qInfo()<<"按钮高度"<<ui->btnBurnData->size();
    qInfo()<<"按钮高度"<<ui->btnBurnImage->size();
    qInfo()<<"按钮高度"<<ui->btnCopyImage->size();
    ui->btnBurnImage->setFont(f);
    ui->btnBurnImage->setText(_("BurnImage"));
    ui->btnBurnImage->setToolTip(_("BurnImage"));
    ui->btnBurnImage->setIconSize(ICON_SIZE);
    ui->btnBurnImage->setIcon(QIcon(":/burnImage.png"));
    connect(ui->btnBurnImage, SIGNAL(clicked(bool)), this, SLOT(slotsBurnImage()));

    ui->btnCopyImage->setFont(f);
    ui->btnCopyImage->setText(_("CopyImage"));
    ui->btnCopyImage->setToolTip(_("CopyImage"));
    ui->btnCopyImage->setIconSize(ICON_SIZE);
    ui->btnCopyImage->setIcon(QIcon(":/copyImage.png"));
    connect(ui->btnCopyImage, SIGNAL(clicked(bool)), this, SLOT(slotsCopyImage()));

    f = ui->btnSetting->font();
    f.setPixelSize(14);
    ui->btnBusness->setFont(f);
    ui->btnSetting->setFont(f);
    ui->comboBoxBurner->setFont(f);
    ui->comboBoxBurner->clear();
    ui->comboBoxDisk->setFont(f);
    ui->comboBoxDisk->clear();
    f = ui->labelBurner->font();
    f.setWeight(60);
    f.setPixelSize(14);
    ui->labelBurner->setFont(f);
    ui->labelDisk->setFont(f);
    ui->labelBurner->setText(_("BurnerName:"));
    ui->labelDisk->setText(_("DiskName:"));
    //f = ui->btnBusness->font();
    //f.setPixelSize(18);
    //ui->btnBusness->setFont(f);
    info(_("Loaded over"));

    connect(ui->comboBoxBurner, SIGNAL(currentIndexChanged(int)), ui->comboBoxDisk, SLOT(setCurrentIndex(int)));
    connect(ui->comboBoxDisk, SIGNAL(currentIndexChanged(int)), ui->comboBoxBurner, SLOT(setCurrentIndex(int)));
    connect(ui->comboBoxDisk, SIGNAL(currentIndexChanged(int)), PAGE_BurnData, SIGNAL(changeCurrentIndex(int)));
    connect(this, SIGNAL(delData(int)), PAGE_BurnData, SIGNAL(delData(int)));
    connect(this, SIGNAL(delData(int)), VIEWFILTERFILE, SIGNAL(delNode(int)));
    connect(ui->comboBoxDisk, SIGNAL(currentIndexChanged(int)), this, SLOT(slotsAdjustBurnData(int)));

    ui->btnSetting->setCheckable(true);
    connect(ui->btnSetting, SIGNAL(toggled(bool)), this, SLOT(slotsBrowseOrSetting(bool)));
    connect(this, SIGNAL(browse(QString)), MAIN, SIGNAL(storagePath(QString)));

    connect(this, SIGNAL(busness(int)), MAIN, SLOT(slotsSetBusness(int)));
    connect(ui->btnBusness, SIGNAL(clicked(bool)), MAIN, SLOT(slotsDoBusness()));


    //connect(this, SIGNAL(position(QPoint)), MAIN, SIGNAL(position(QPoint)));
    connect(MAIN, SIGNAL(createISO(void*)), this, SLOT(slotsInitCreateISO(void*)));
    connect(MAIN, SIGNAL(noMedium(void*)), this, SLOT(slotsNoMediun(void*)));
    connect(MAIN, SIGNAL(deleteCDROM(void*)), this, SLOT(slotsRemoveCDROM(void*)));
    connect(MAIN, SIGNAL(emptyMedium(void*)), this, SLOT(slotsInitCreateISO(void*)));
    connect(MAIN, SIGNAL(appendableMedium(void*)), this, SLOT(slotsInitCreateISO(void*)));
    connect(MAIN, SIGNAL(finishedMedium(void*)), this, SLOT(slotsInitCreateISO(void*)));

    connect(MAIN, SIGNAL(appendableMedium(void*)), MENU, SLOT(newEarse(void*)));
    connect(MAIN, SIGNAL(finishedMedium(void*)), MENU, SLOT(newEarse(void*)));
    //connect(MAIN, SIGNAL(noMedium(void*)), MENU, SLOT(newEarse(void*)));
    connect(MAIN, SIGNAL(noMedium(void*)), MENU, SLOT(removeEarse(void*)));
    connect(g_user_signal, SIGNAL(haveMedium(void*)), MENU , SLOT(newEarse(void*)));
    connect(g_user_signal, &GlobalUserSignal::iconChange, [=](QIcon icon){
        setWindowIcon(icon);
    });



    m_oGroup->addButton(ui->btnBurnData);
    m_oGroup->addButton(ui->btnBurnImage);
    m_oGroup->addButton(ui->btnCopyImage);

    uiModeChange(m_isTabletMode);

    if (args.size() == 1)
    {
        file.setFile(args.first());
        if (file.suffix() == "iso")
        {
            url.setUrl(args.first());
            PAGE_BurnImage->slotsNewISOPath(args.first());
            emit busness(LogicMain::BurnImage);
            ui->btnBurnImage->click();
            QListView* mViewOfNavBar = m_NavBar->listview();
            if(mViewOfNavBar){
                mViewOfNavBar->setCurrentIndex(mViewOfNavBar->model()->index(1,0,QModelIndex()));
            }
        }
    }
    else
    {
        emit busness(LogicMain::CreateISO);
        emit ui->btnBurnData->click();
    }

    p.setX(pos().x() + width() / 2);
    p.setY(pos().y() + height() / 2);

    move(p);
    m_mapStartTime[0] = QDateTime::currentMSecsSinceEpoch();
    ABOUT->close();
    //emit position(p);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    calculatorTime(m_current_page);
    emit MAIN->exit();
    if (VIEWFILTERFILE)
    {
        VIEWFILTERFILE->close();
        VIEWFILTERFILE->destroy();
    }
    if (FILTERRULES)
    {
        FILTERRULES->close();
        FILTERRULES->destroy();
    }
    qApp->exit();
    QMainWindow::closeEvent(event);
}

void MainWindow::moveEvent(QMoveEvent *event)
{
    QPoint p;
    QPoint sp;

    p.setX(event->pos().x() + width() / 2);
    p.setY(event->pos().y() + height() / 2);

  //  ABOUT->updatePosition(p);
    MODAL->updatePosition(p);
    FILTERRULES->updatePosition(p);
    VIEWFILTERFILE->updatePosition(p);
    PAGE_BurnData->updatePosition(p);
    TIP_BURNRESULT->updatePosition(p);

    sp.setX(p.x() - EXEC->width() / 2);
    sp.setY(p.y() - EXEC->height() / 2);
    EXEC->move(sp);

    //emit position(sp);

    QMainWindow::moveEvent(event);
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPalette pal = ui->burner->palette();
    if ("ukui-black" == MAIN->theme())
    {
        pal.setBrush(QPalette::Background, QColor("#484848"));
        ui->nav->setPalette(pal);
//        pal.setBrush(QPalette::Background, QColor("#242424"));
        pal.setBrush(QPalette::Background, QColor("#232426"));
        ui->burner->setPalette(pal);
    }
    else
    {
        pal.setBrush(QPalette::Background, QColor("#F0F0F0"));
        ui->nav->setPalette(pal);
        pal.setBrush(QPalette::Background, QColor("#FFFFFF"));
        ui->burner->setPalette(pal);
    }
    ui->comboBoxDisk->setToolTip(ui->comboBoxDisk->itemText(
                                     ui->comboBoxDisk->currentIndex()));

    QPainterPath path;
    QPainter painter(this);
    painter.setOpacity(m_transparentValue);
    painter.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    painter.setClipping(true);

    path.addRect(ui->nav->rect());
    path.setFillRule(Qt::WindingFill);
    painter.setBrush(this->palette().window());
    painter.setPen(Qt::transparent);
    painter.drawPath(path);

    QMainWindow::paintEvent(event);
}

//主界面窗口设置为最顶层窗口，显示在最前面
int MainWindow::slotsReShowMainWindow()
{
    //存在kylin-burner进程
    info(_("kylin-burner process already exists"));
    qDebug()<<"kylin-burner process already exists";
    qDebug()<<"New kylin-burner process exit";
    info(_("New kylin-burner process exit"));

    KWindowSystem::forceActiveWindow(this->winId());
    return 0;
}

bool MainWindow::isBusyDevice(QString device)
{
    return g_user_signal->getDeviceBusyStatus(device);
}

void MainWindow::slotsBurnData()
{
    ui->burnData->show();
    ui->stackedWidget->setCurrentIndex(0);
    // 根据comboBoxDisk 下表结合其对应的光驱信息确认业务类型
    slotsAdjustBurnData(ui->comboBoxDisk->currentIndex());
}

void MainWindow::slotsBurnImage()
{
    ui->burnData->hide();
    ui->btnBusness->setText(_("BurnImage"));
    ui->stackedWidget->setCurrentIndex(1);
    emit busness(LogicMain::BurnImage);
    PAGE_BurnImage->update();
}

void MainWindow::slotsCopyImage()
{
    ui->burnData->hide();
    ui->btnBusness->setText(_("CopyImage"));
    ui->stackedWidget->setCurrentIndex(2);
    busness(LogicMain::GetISO);
    PAGE_CopyImage->check();
}


void MainWindow::slotsAdjustBurnData(int idx)
{
    DataCDROM *cdrom;

    cdrom = nullptr;
    if (idx < 0) return;

    if ( 0 != ui->stackedWidget->currentIndex() ) return;
    // 根据comboBoxDisk 下表结合其对应的光驱信息确认业务类型
    if (idx > 0)
    {
        if (idx >= m_oCDROMS.size()) return;
        cdrom = static_cast<DataCDROM *>(m_oCDROMS.at(idx));
        ui->btnSetting->setText(_("Setting"));
        //判断是做UDF格式还是ISO9660格式
        if(cdrom->getBurnFormat() == "UDF")
        {
            //UDF
            //qDebug()<<"MainWindow::slotsAdjustBurnData  UDF Format";
            ui->btnBusness->setText(_("BurnUDFData"));
            emit busness(LogicMain::BurnUDFData);
        }
        else if(cdrom->getBurnFormat() == "ISO9660")
        {
            //ISO9660
            //qDebug()<<"MainWindow::slotsAdjustBurnData  ISSO9660 Format";
            switch (cdrom->mediumStatus())
            {
            case DataMedium::MEDIUM_EMPTY:
                ui->btnBusness->setText(_("BurnData"));
                emit busness(LogicMain::BurnData);
                break;
            case DataMedium::MEDIUM_INCOMPLETE:
                ui->btnBusness->setText(_("AppendBurn"));
                emit busness(LogicMain::AddBurn);
                break;
            default:
                ui->btnBusness->setText(_("DonotBurn"));
                emit busness(LogicMain::AddBurn);
                break;
            }
        }
        else
        {
            error(_("cdrom->getBurnFormat() == [NULL]"));
            //qDebug()<<"MainWindow::slotsAdjustBurnData  cdrom->getBurnFormat() == [NULL]";
        }
    }
    else
    {
        ui->btnSetting->setText(_("Browse"));
        ui->btnBusness->setText(_("CreateISO"));
        emit busness(LogicMain::CreateISO);
    }
    ui->comboBoxDisk->setToolTip(ui->comboBoxDisk->itemText(idx));
    PAGE_BurnData->refresh();
}

void MainWindow::slotsBusness(bool b)
{
    if (PAGE_BurnData == sender() && 0 == ui->stackedWidget->currentIndex())
    {
        ui->btnBusness->setEnabled(b);
        ui->btnSetting->setEnabled(b);
        MENU->setSetting(b);
    }
    else if (PAGE_BurnImage == sender() && 1 == ui->stackedWidget->currentIndex())
    {
        ui->btnBusness->setEnabled(b);
        MENU->setSetting(b);
    }
    else if (PAGE_CopyImage == sender() && 2 == ui->stackedWidget->currentIndex())
    {
        ui->btnBusness->setEnabled(b);
        MENU->setSetting(b);
    }
    else {}
}

void MainWindow::slotsInitCreateISO(void *d)
{
    int idx;
    DataCDROM *cdrom;

    cdrom = (DataCDROM *)d;
    if(cdrom->m_iUsing<=0) return;
    if (-1 != m_oCDROMS.indexOf(d)){//设备已存在且查询到属性更新时，需要刷新UI界面
        ui->comboBoxDisk->setItemText(m_oCDROMS.indexOf(d),cdrom->mDisplay());
        PAGE_BurnData->refresh();
        return;
    }
    m_oCDROMS << d;

    ui->comboBoxBurner->addItem(cdrom->icon(), cdrom->display());
    ui->comboBoxDisk->addItem(cdrom->mediumIcon(), cdrom->mDisplay());

    idx = ui->comboBoxDisk->count() - 1;
    if (idx >= 0) ui->comboBoxDisk->setCurrentIndex(idx);
    else ui->comboBoxDisk->setCurrentIndex(0);
    PAGE_BurnData->refresh();

    if (0 != ui->stackedWidget->currentIndex()) return;

    //判断是做UDF格式还是ISO9660格式
    if(cdrom->getBurnFormat() == "UDF")
    {
        //UDF
        //qDebug()<<"MainWindow::slotsInitCreateISO  UDF Format";
        ui->btnBusness->setText(_("BurnUDFData"));
        emit busness(LogicMain::BurnUDFData);
    }
    else if(cdrom->getBurnFormat() == "ISO9660")
    {
        //ISO9660
        //qDebug()<<"MainWindow::slotsInitCreateISO  ISSO9660 Format";
        switch (cdrom->mediumStatus())
        {
        case DataMedium::MEDIUM_EMPTY:
            ui->btnSetting->setText(_("Setting"));
            ui->btnBusness->setText(_("BurnData"));
            emit busness(LogicMain::BurnData);
            break;
        case DataMedium::MEDIUM_INCOMPLETE:
            ui->btnSetting->setText(_("Setting"));
            ui->btnBusness->setText(_("AppendBurn"));
            emit busness(LogicMain::AddBurn);
            break;
        default:
            if (cdrom->isCDROM())
            {
                ui->btnSetting->setText(_("Setting"));
                ui->btnBusness->setText(_("DonotBurn"));
                emit busness(LogicMain::AddBurn);
            }
            break;
        }
    }
    else
    {
        error(_("cdrom->getBurnFormat() == [NULL]"));
        //qDebug()<<"MainWindow::slotsInitCreateISO  cdrom->getBurnFormat() == [NULL]";
    }

}

void MainWindow::slotsNoMediun(void * d)
{
    int idx;

    idx = m_oCDROMS.indexOf(d);
    if (-1 == idx) return;
    m_oCDROMS.takeAt(idx);
    delData(idx); // 先删除数据，后移除展示

    ui->comboBoxDisk->removeItem(idx);
    ui->comboBoxBurner->removeItem(idx);
    if (idx < ui->comboBoxDisk->count())
        ui->comboBoxDisk->setCurrentIndex(idx);
    else
        ui->comboBoxDisk->setCurrentIndex(0);
    debug(_("Delete item %1 of total %2").arg(idx).arg(ui->comboBoxBurner->count()));
}

void MainWindow::slotsRemoveCDROM(void *d)
{
    int idx;

    idx = m_oCDROMS.indexOf(d);
    if (-1 != idx)
    {
        debug(_("Remove CDROM from burn data."));
        m_oCDROMS.takeAt(idx);
    }
}
//#include <QDir>
void MainWindow::slotsBrowseOrSetting(bool b)
{
    QString path;
    QString testPath;
    QFileDialog fd;
    QList<QUrl> list = fd.sidebarUrls();
    int sidebarNum = 8;//最大添加U盘数，可以自己定义
    QString home = QDir::homePath().section("/", -1, -1);
    QString mnt = "/media/" + home + "/";
    QDir mntDir(mnt);
    mntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
    QFileInfoList filist = mntDir.entryInfoList();
    QList<QUrl> mntUrlList;
    for (int i = 0; i < sidebarNum && i < filist.size(); ++i) {
        QFileInfo fi = filist.at(i);
        if (fi.fileName() == "2691-6AB8") /* 990 9a0 */
                 continue;
        mntUrlList << QUrl("file://" + fi.filePath());
    }

    QFileSystemWatcher fsw(&fd);
    fsw.addPath("/media/" + home + "/");
    connect(&fsw, &QFileSystemWatcher::directoryChanged, &fd,
            [=, &sidebarNum, &mntUrlList, &list, &fd](const QString path) {
        QDir wmntDir(path);
        wmntDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        QFileInfoList wfilist = wmntDir.entryInfoList();
        mntUrlList.clear();
        for (int i = 0; i < sidebarNum && i < wfilist.size(); ++i) {
            QFileInfo fi = wfilist.at(i);
            if (fi.fileName() == "2691-6AB8") /* 990 9a0 */
                     continue;
            mntUrlList << QUrl("file://" + fi.filePath());
        }
        fd.setSidebarUrls(list + mntUrlList);
        fd.update();
    });

    connect(&fd, &QFileDialog::finished, &fd, [=, &list, &fd]() {
        fd.setSidebarUrls(list);
    });
    if (b)
    {
        if (0 == ui->comboBoxDisk->currentIndex())
        {
            //path = QFileDialog::getExistingDirectory(this, _("Browse"), path);
            //path = fd.getExistingDirectory(this, _("Browse"), path);
            //fd.setNameFilter(_("Forlder"));
            fd.setFileMode(QFileDialog::DirectoryOnly);
            fd.setSidebarUrls(list + mntUrlList);

            if (/*!path.isEmpty()*/ fd.exec() == QDialog::Accepted)
            {
                path = fd.selectedFiles().at(0);
                testPath = path + "/.t/.k";
                QDir dir(testPath);
                if (dir.mkpath(testPath))
                {
                    dir.removeRecursively();
                    browse(path);
                }
                else
                {
#if 0
                    QMessageBox::critical(this, _("Invalid path"),
                                          _("Cannot choose a read "
                                            "only path %1 to "
                                            "storage path").arg(path));
#endif
                    ui->btnSetting->setChecked(false);
                    return;
                }
            }
        }
        else
        {
            MENU->burnSetting(b);
        }
        ui->btnSetting->setChecked(false);
    }
}

void MainWindow::slotsUpdateDisk(int idx, void *d)
{
    DataCDROM *cdrom;

    cdrom = (DataCDROM *)d;

    ui->comboBoxDisk->setItemText(idx, cdrom->mDisplay());
    ui->comboBoxDisk->setItemIcon(idx, cdrom->mediumIcon());
}

void MainWindow::slotsCloseAll()
{
    close();
}

void MainWindow::slotsChangeName(int bus)
{
    if (ui->stackedWidget->currentWidget() != PAGE_CopyImage) return;
    switch (bus)
    {
    case LogicMain::GetISO:
        ui->btnBusness->setText(_("Get ISO"));
        busness(LogicMain::GetISO);
        break;
    default:
        ui->btnBusness->setText(_("Copy Disk"));
        busness(LogicMain::CopyData);
        break;
    }
}

//改btnBusness按钮的名字
void MainWindow::slotsChangeBtnBusnessName()
{
    //qDebug()<<"MainWindow::slotsChangeBtnBusnessName111111";
    DataCDROM *cdrom;
    cdrom = nullptr;
    int idx = ui->comboBoxDisk->currentIndex();
    //qDebug()<<"idx==["<<idx<<"]";
    //qDebug()<<"ui->stackeWidget->currentIndex === ["<<ui->stackedWidget->currentIndex()<<"]";
    //判断在【刻录数据】界面
    if (ui->stackedWidget->currentIndex() != 0) return;
    if(idx < 0 ) return;
    //判断comboxDisk选择的是光盘
    if(idx>0)
    {
        if (idx >= m_oCDROMS.size()) return;
        cdrom = static_cast<DataCDROM *>(m_oCDROMS.at(idx));
        ui->btnSetting->setText(_("Setting"));
        //判断是做UDF盘还是ISO9660盘
        if(cdrom->getBurnFormat() == "UDF")
        {
            //UDF
            //qDebug()<<"MainWindow::slotsChangeBtnBusnessName  UDF Format";
            ui->btnBusness->setText(_("BurnUDFData"));
            emit busness(LogicMain::BurnUDFData);
        }
        else if(cdrom->getBurnFormat() == "ISO9660")
        {
            //ISO9660
            //qDebug()<<"MainWindow::slotsChangeBtnBusnessName  ISSO9660 Format";
            switch (cdrom->mediumStatus())
            {
            case DataMedium::MEDIUM_EMPTY:
                ui->btnBusness->setText(_("BurnData"));
                emit busness(LogicMain::BurnData);
                break;
            case DataMedium::MEDIUM_INCOMPLETE:
                ui->btnBusness->setText(_("AppendBurn"));
                emit busness(LogicMain::AddBurn);
                break;
            default:
                ui->btnBusness->setText(_("DonotBurn"));
                emit busness(LogicMain::AddBurn);
                break;
            }
        }
        else
        {
            error(_("cdrom->getBurnFormat() == [NULL]"));
            //qDebug()<<"MainWindow::slotsChangeBtnBusnessName  cdrom->getBurnFormat() == [NULL]";
        }
    }
}

bool MainWindow::started()
{
    QString comm;
    QDir dir("/proc/");
    QFileInfo file;
    ifstream in;
    std::string s;

    foreach (QFileInfo f, dir.entryInfoList())
    {
        if (f.baseName() == QString("%1").arg(getpid())
                || f.baseName() == "self" ||
                f.baseName() == "thread-self") continue;
        comm = QString("/proc/%1/comm").arg(f.baseName());
        file.setFile(comm);
        if (file.exists())
        {
            in.open(file.absoluteFilePath().toStdString());
            if (in.is_open())
            {
                getline(in, s);
                comm = QString::fromStdString(s);
                if (comm == "kylin-burner")
                    return true;
            }
            in.close();
        }
    }

    return false;
}


MainWindow::~MainWindow()
{
    //在程序退出前调用，不需要传入参数
    kdk_dia_upload_program_exit();

    if(m_burnDataItem){
        delete m_burnDataItem;
        m_burnDataItem = nullptr;
    }
    if(m_burnImageItem){
        delete m_burnImageItem;
        m_burnImageItem = nullptr;
    }
    if(m_copyImageItem){
        delete m_copyImageItem;
        m_copyImageItem = nullptr;
    }
    if(m_NavBar){
        delete m_NavBar;
        m_NavBar = nullptr;
    }
    if(m_transparentSettings){
        delete m_transparentSettings;
        m_transparentSettings = nullptr;
    }
    MONITOR->stop();
    MAIN->destroy();
    MENU->destroy();
    PAGE_BurnImage->destroy();
    TIP_BURNRESULT->destroy();
    LOGGER->destroy();
    CFG->destroy();
    delete ui;
}

/** 获取并监控透明度变化 */
void MainWindow::initTransparent(){
    m_transparentValue = 1.0;
    m_transparentSettings = nullptr;

    if(QGSettings::isSchemaInstalled(TRANSPARENT_SCHEMAS))
        m_transparentSettings = new QGSettings(TRANSPARENT_SCHEMAS);

    if(m_transparentSettings->keys().contains("transparency")){
        m_transparentValue = m_transparentSettings->get("transparency").toString().toDouble();
        connect(m_transparentSettings, &QGSettings::changed, this, [=](const QString& key){
            m_transparentValue = m_transparentSettings->get("transparency").toString().toDouble();
            repaint();
        });
    }
}
/** 计算刻录数据、刻录镜像、拷贝镜像不同页面停留时间
 * 1. current是当前页面索引值0,1,2
 * 2. show_time是切换页面之前页面的停留时间
*/
void MainWindow::calculatorTime(int current)
{
    KCustomProperty property[2];
    KTrackData *data_node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP,KEVENT_CLICK);
    KTrackData *image_node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP,KEVENT_CLICK);
    KTrackData *copy_node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP,KEVENT_CLICK);
    for(auto &pair : m_mapStartTime){
        if(pair.second != 0)
        {
            qint64 show_time = QDateTime::currentMSecsSinceEpoch() - pair.second;
            qDebug() << "页面" << pair.first << "停留时间" << show_time << "ms";
            QString s = QString::number(show_time) + "ms";
            switch(pair.first){
            case 0:
                // 刻录数据入口的停留时间
                property[0].key = "burnDataEntranceDwellTime";
                property[0].value = strdup(s.toStdString().c_str());
                kdk_dia_append_custom_property(data_node,property,1);
                kdk_dia_upload_default(data_node,"burn_data_entrance_dwell_time_event","entryPage ");
                kdk_dia_data_free(data_node);
                break;
            case 1:
                // 刻录镜像入口的停留时间
                property[0].key = "burnImageEntranceDwellTime";
                property[0].value = strdup(s.toStdString().c_str());              
                kdk_dia_append_custom_property(image_node,property,1);
                kdk_dia_upload_default(image_node,"burn_image_entrance_dwell_time_event","entryPage ");
                kdk_dia_data_free(image_node);
                break;
            case 2:
                // 拷贝镜像入口的停留时间
                property[0].key = "copyImageEntranceDwellTime";
                property[0].value = strdup(s.toStdString().c_str());             
                kdk_dia_append_custom_property(copy_node,property,1);
                kdk_dia_upload_default(copy_node,"copy_image_entrance_dwell_time_event","entryPage ");
                kdk_dia_data_free(copy_node);
                break;
            default:
                break;
            }
            qDebug() << property[0].key << s;
            qDebug() << property[0].key << property[0].value;
            m_mapStartTime[pair.first] = 0;
        }
    }
    m_mapStartTime[current] = QDateTime::currentMSecsSinceEpoch();
}

/** 调整左侧导航栏栏ui
 * 1. 开启左侧栏毛玻璃效果
 * 2. 左侧栏使用KNavigationBar类
*/
void MainWindow::uiAdjust(){
    m_NavBar = nullptr;
    m_burnDataItem = nullptr;
    m_burnImageItem = nullptr;
    m_copyImageItem = nullptr;

    setProperty("useSystemStyleBlur",true);     //毛玻璃属性
    setAttribute(Qt::WA_TranslucentBackground); //设置整个窗体透明
    initTransparent();                          //使用系统透明度

    ui->splitter->setHandleWidth(0);            //设置分隔符宽度为0
    ui->splitter->setCollapsible(0,false);      //设置分隔符不可拖动

    ui->nav->setFixedWidth(200);                //左侧栏宽度固定
    ui->nav->setContentsMargins(0,0,0,0);
    ui->nav->setAutoFillBackground(false);      //关闭左侧栏背景自动填充

    /** 左侧栏改用KNavigationBar实现
     *  FIXME: KNavigationBar+QStandardItem会存在失去焦点后按钮配色异常的问题，后期应该由sdk进行修复
    */
    ui->buttons->hide();
    qInfo()<<"ui->button"<<ui->buttons->size();
    //ui->widgetCopyRight->hide();

   // ui->verticalSpacer->invalidate();
    m_NavBar = new KNavigationBar(ui->nav);
    m_NavBar->setGeometry(ui->buttons->x()+10,48,180,300);
    QListView* mViewOfNavBar = m_NavBar->listview();
    mViewOfNavBar->setFocus();

    m_burnDataItem = new QStandardItem(QIcon::fromTheme("ukui-burn-data-symbolic"),_("BurnData"));
    m_burnImageItem = new QStandardItem(QIcon::fromTheme("ukui-burn-mirror-symbolic"),_("BurnImage"));
    m_copyImageItem = new QStandardItem(QIcon::fromTheme("ukui-burn-cd-symbolic"),_("CopyImage"));

    m_NavBar->addItem(m_burnDataItem);
    m_NavBar->addItem(m_burnImageItem);
    m_NavBar->addItem(m_copyImageItem);

    QModelIndex helloIndex = mViewOfNavBar->model()->index(0,0, QModelIndex());  //获取首元素的index
    mViewOfNavBar->setCurrentIndex(helloIndex);                                  //默认选中首元素
    connect(mViewOfNavBar, &QListView::pressed, this, [=](const QModelIndex& pressedIndex){//注意pressed()信号的参数为const类型
        switch(pressedIndex.row()){
        case 0:
            slotsBurnData();
            break;
        case 1:
            slotsBurnImage();
            break;
        case 2:
            slotsCopyImage();
            break;
        default:
            break;
        }
        m_current_page = pressedIndex.row();
        calculatorTime(m_current_page);
    });
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_F1)
    {
        struct passwd *pwd;
        QFileInfo f;

        pwd = getpwuid(getuid());

        msg = QDBusMessage::createMethodCall( QString("com.kylinUserGuide.hotel_%1")
                                              .arg(pwd->pw_gid),"/", "com.guide.hotel",
                                              "showGuide");
        f.setFile("/usr/share/kylin-user-guide/data/guide/kylin-burner");
        msg << "kylin-burner";
        msg.setDelayedReply(false);
        QDBusConnection::sessionBus().call(msg);
        return;
    }
    if(event->key() == Qt::Key_F10)
    {
        //关于界面
        ABOUT->show();
        return;
    }

    QMainWindow::keyPressEvent(event);
}

void MainWindow::uiModeChange(bool is_tabletmode)
{
    qInfo()<<"平板模式"<<is_tabletmode;
    // 是否平板模式，平板模式
    m_isTabletMode = is_tabletmode;

    ui->burnerTitle->setIsTabletMode(is_tabletmode);
}

void MainWindow::changeEvent(QEvent *event){
    if (QEvent::WindowStateChange == event->type()) {
        Qt::WindowStates state = this->windowState();
        switch (state) {
        case Qt::WindowMaximized:
        case Qt::WindowFullScreen:
            ui->burnerTitle->onWindowShowMaxed(true);
            break;
        case Qt::WindowNoState:
            ui->burnerTitle->onWindowShowMaxed(false);

            break;
        default:
            break;
        }
    }

    QMainWindow::changeEvent(event);
}
