#include "showimagewidget.h"
#include "kyview.h"
#include "sizedate.h"

ShowImageWidget::ShowImageWidget(QWidget *parent) : QWidget(parent)
{
    initInteraction();

    //中间展示图片部分
    m_showImage = new QLabel(this);
    m_showImage->resize(this->width(), this->height());
    m_showImage->move(int((this->width() - m_showImage->width()) / 2),
                      int((this->height() - m_showImage->height()) / 2));
    m_showImage->setMouseTracking(true);
    m_showImage->installEventFilter(this);
    m_showImage->setAlignment(Qt::AlignCenter);
    m_showImage->setContextMenuPolicy(Qt::ActionsContextMenu);
    m_showImage->setContextMenuPolicy(Qt::CustomContextMenu);

    //设置位置和大小
    m_showImageQml = new QQuickWidget(this);
    QQmlEngine *engine = m_showImageQml->engine();
    engine->addImageProvider(QLatin1String("thumb"), new ScreenImageProvider);

    m_showImageQml->setSource(QUrl(QStringLiteral("qrc:/showImageComponent.qml")));
    m_showImageQml->setClearColor(Qt::transparent);
    //设置置顶
    //    m_showImageQml->setAttribute(Qt::WA_AlwaysStackOnTop);
    QObject *qmlObj = m_showImageQml->rootObject();
    qmlObj->setProperty("width", this->width());
    qmlObj->setProperty("height", this->height());
    qmlObj->setProperty("x", 0);
    qmlObj->setProperty("y", 0);
    m_showImageQml->installEventFilter(this);
    m_showImageQml->setContextMenuPolicy(Qt::ActionsContextMenu);
    m_showImageQml->setContextMenuPolicy(Qt::CustomContextMenu);
    m_showImageQml->lower();

    //菜单栏给功能选项：复制，设置为桌面壁纸，设置为锁屏壁纸，打印，删除，在文件夹中显示
    m_copy = new QAction(tr("Copy"), this);
    m_reName = new QAction(tr("Rename"), this);
    m_setDeskPaper = new QAction(tr("Set Desktop Wallpaper"), this);
    m_setLockPaper = new QAction(tr("Set Lock Wallpaper"), this);
    m_print = new QAction(tr("Print"), this);
    m_deleteImage = new QAction(tr("Delete"), this);
    m_showInFile = new QAction(tr("Show in File"), this);
    m_saveAs = new QAction(tr("Save as"), this);
    m_signImage = new QAction(tr("Markup"), this);
    //右键菜单
    m_imageMenu = new QMenu();
    m_imageMenu->addAction(m_copy);
    //    m_imageMenu->addAction(m_reName);
    //    m_imageMenu->addAction(m_setDeskPaper);
    //    imageMenu->addAction(setLockPaper);
    m_imageMenu->addAction(m_print);
    m_imageMenu->addAction(m_deleteImage);
    m_imageMenu->addAction(m_signImage);
    m_imageMenu->addAction(m_saveAs);
    m_imageMenu->addAction(m_showInFile);
    //上一张，下一张按钮
    g_next = new QPushButton(this);
    g_next->resize(IMAGE_BUTTON);
    g_next->setToolTip(tr("Next"));

    g_back = new QPushButton(this);
    g_back->resize(IMAGE_BUTTON);
    g_back->setToolTip(tr("Previous"));

    g_back->move(LEFT_POS, int((this->height() - g_back->height()) / 2));
    g_next->move(this->width() - LEFT_POS - g_next->width(), int((this->height() - g_next->height()) / 2));

    g_back->setIconSize(IMAGE_ICON);
    g_next->setIconSize(IMAGE_ICON);

    g_back->setFocusPolicy(Qt::NoFocus);
    g_next->setFocusPolicy(Qt::NoFocus);
    g_back->setFlat(true);
    g_next->setFlat(true);
    g_back->setStyleSheet("QPushButton{border:none;background-color:transparent;border-radius:4px;}");
    g_next->setStyleSheet("QPushButton{border:none;background-color:transparent;border-radius:4px;}");
    //图片没处理完毕时，显示转圈圈图
    m_loadingMovie = new QMovie(":/res/res/loadgif.gif");
    m_loadingMovie->setParent(this);
    m_cutWid = new CutWIdget(this);
    m_cutWid->hide();

    //需要将这个widget移动到showimagewidget内
    m_btnWid = new QWidget(this);
    m_btnWid->hide();
    m_btnWid->setFixedSize(108, 40);

    m_cancel = new QPushButton(m_btnWid);
    m_save = new QPushButton(m_btnWid);
    m_cancel->setFixedSize(24, 24);
    m_save->setFixedSize(24, 24);
    m_cancel->move(20, 8);
    m_save->move(30 + m_cancel->width() + 8, 8);
    m_save->setToolTip(tr("Save"));
    m_cancel->setToolTip(tr("Cancel"));
    cutBtnWidStyle();
    m_btnWid->move((this->width() - m_btnWid->width()) / 2, this->height() - m_btnWid->height() - 8);

    m_ocrWid = new OCRResultWidget(this);
    m_ocrWid->hide();
    m_ocrBtnWid = new QWidget(this);
    m_ocrBtnWid->hide();
    m_ocrBtnWid->setFixedSize(148, 40);
    m_ocrCancel = new QPushButton(m_ocrBtnWid);
    m_ocrCancel->setIcon(QIcon::fromTheme("ukui-start-symbolic"));
    m_ocrCancel->move(20, 8);
    m_ocrCancel->setFocusPolicy(Qt::NoFocus); //设置焦点类型
    m_ocrCancel->setProperty("isWindowButton", 0x1);
    m_ocrCancel->setProperty("useIconHighlightEffect", 0x2);
    m_ocrCancel->setFlat(true);
    m_ocrCancel->setFixedSize(24, 24);
    m_ocrCancel->setToolTip(tr("Cancel"));
    m_ocrExportToTxt = new QPushButton(m_ocrBtnWid);
    m_ocrExportToTxt->setText(tr("Export"));
    m_ocrExportToTxt->setProperty("isWindowButton", 0x1);
    m_ocrExportToTxt->setProperty("useIconHighlightEffect", 0x2);
    m_ocrExportToTxt->setFlat(true);
    m_ocrExportToTxt->setFixedSize(60, 24);
    m_ocrExportToTxt->move(64, 8);
    m_ocrExportToTxt->setEnabled(false);
    ocrBtnWidStyle();

    //绘制阴影
    QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this);
    effect->setOffset(0, 0); //设置向哪个方向产生阴影效果(dx,dy)，特别地，(0,0)代表向四周发散
    effect->setColor(TOOL_COLOR);       //设置阴影颜色，也可以setColor(QColor(220,220,220))
    effect->setBlurRadius(BLUR_RADIUS); //设定阴影的模糊半径，数值越大越模糊
    m_btnWid->setGraphicsEffect(effect);
    m_ocrBtnWid->setGraphicsEffect(effect);
    m_widChangeHeight = makeSureHeightState();
    this->setMouseTracking(true);
    this->update();
    this->initConnect();
}

ShowImageWidget::~ShowImageWidget()
{
    delete m_imageMenu;
}

void ShowImageWidget::initConnect()
{
    connect(g_next, &QPushButton::clicked, this, &ShowImageWidget::nextImage);
    connect(g_back, &QPushButton::clicked, this, &ShowImageWidget::backImage);
    //右键菜单
    connect(m_showImage, &QLabel::customContextMenuRequested, [=](const QPoint &pos) {
        Q_UNUSED(pos);
        abnormalJudgBeforeClick();
        m_imageMenu->exec(QCursor::pos());
    });
    connect(m_showImageQml, &QQuickWidget::customContextMenuRequested, [=](const QPoint &pos) {
        Q_UNUSED(pos);
        abnormalJudgBeforeClick();
        m_imageMenu->exec(QCursor::pos());
    });
    //点击菜单选项
    connect(m_copy, &QAction::triggered, this, &ShowImageWidget::copy);
    connect(m_reName, &QAction::triggered, this, &ShowImageWidget::reName);
    connect(m_setDeskPaper, &QAction::triggered, this, &ShowImageWidget::setDeskPaper);
    //    connect(m_setLockPaper, &QAction::triggered, this,&ShowImageWidget::setLockPaper);
    connect(m_print, &QAction::triggered, this, &ShowImageWidget::initPrint);
    connect(m_deleteImage, &QAction::triggered, this, &ShowImageWidget::deleteImage);
    connect(m_showInFile, &QAction::triggered, this, &ShowImageWidget::showInFile);
    connect(m_cutWid, &CutWIdget::showBtnWid, this, &ShowImageWidget::showBthWid);
    connect(m_cancel, &QPushButton::clicked, this, &ShowImageWidget::exitCut);
    connect(m_save, &QPushButton::clicked, this, &ShowImageWidget::needSave);
    connect(m_cancel, &QPushButton::clicked, this, &ShowImageWidget::cutFinishUi);
    connect(m_saveAs, &QAction::triggered, this, &ShowImageWidget::saveAsOther);
    connect(m_signImage, &QAction::triggered, this, &ShowImageWidget::signImage);
    // OCR
    connect(m_ocrCancel, &QPushButton::clicked, this, &ShowImageWidget::exitGetText);
    connect(m_ocrExportToTxt, &QPushButton::clicked, this, &ShowImageWidget::exportToTxt);
}

void ShowImageWidget::sideState(int num)
{
    Q_EMIT changeSideSize(num);
}
//根据number决定界面显示:相册，左右按钮，删除时相册显示
bool ShowImageWidget::imageNum(int number)
{
    //侧栏上方新增加号，故number加1
    //判断有几张图片，分别进行处理：删除到0，显示打开界面；只有一张：不显示左右按钮。
    if (number == 1) {
        Q_EMIT clearImage();
        //点击删除按钮删除全部文件时，此标志位应该重设为默认状态，防止之后继续打开图片造成相册大小有误差
        m_isDelete = false;
        return true;
    }
    if (number == 2) {
        g_buttonState = false;
    } else {
        //删除时逻辑导致item总是比实际多一张，暂时先在前端进行判断来解决相关问题
        if (number == 3 && m_isDelete == true) {
            g_buttonState = false;
        } else {
            g_buttonState = true;
        }
    }
    return false;
}
//根据图片是否为空决定是否显示转圈圈
bool ShowImageWidget::imageNUll(QPixmap pixmap)
{
    if (pixmap.isNull()) {
        this->m_showImage->setMovie(m_loadingMovie);
        m_loadingMovie->start();
        m_showImage->show();
        m_showImageQml->hide();
        return true;
    }
    if (m_loadingMovie->state() != QMovie::NotRunning) {
        m_loadingMovie->stop();
    }
    if (m_isCutting || m_movieImage) {
        m_showImage->setPixmap(pixmap);
        m_showImage->show();
        m_showImageQml->hide();
        Q_EMIT perRate(QString::number(m_proportion) + "%", m_imagePath);
        return false;
    }

    if (!m_isOpenSuccess) {
        m_showImage->setPixmap(pixmap);
        m_showImage->show();
        m_showImageQml->hide();
        Q_EMIT perRate(QString::number(m_proportion) + "%", m_imagePath);
        return false;
    }

    m_showImage->hide();
    m_showImageQml->show();
    QObject *qmlObj = m_showImageQml->rootObject();
    QObject *qmlImageRect = qmlObj->findChild<QObject *>("imageRect");

    QObject *targatImage = qmlImageRect->findChild<QObject *>("targatImage");
    //更换图片：切换图片，旋转翻转
    if (targatImage->property("source").toString() != "image://thumb/" + m_imagePath) {
        //启动动画设置，切换或者更新图片的时候不启动动画效果
        qmlObj->setProperty("startAnimation", false);
        targatImage->setProperty("source", "image://thumb/" + m_imagePath);
    } else if (m_imageNeedUpdate) {
        //路径一样的要先清空source或者设置cache为false
        qmlObj->setProperty("startAnimation", false);
        targatImage->setProperty("source", "");
        targatImage->setProperty("source", "image://thumb/" + m_imagePath);
    } else {
        qmlObj->setProperty("startAnimation", true);
    }
    qmlImageRect->setProperty("width", m_displaySizeOfPicture.width());
    qmlImageRect->setProperty("height", m_displaySizeOfPicture.height());


    if (m_leftUpPos.x() == 0 && m_leftUpPos.y() == 0) {
        int leftPosX;
        if (displayMode == DisplayMode::OCRMode) {
            leftPosX = positionCorrection(this->width() / 2, m_displaySizeOfPicture.width());
        } else {
            leftPosX = positionCorrection(this->width(), m_displaySizeOfPicture.width());
        }
        int leftPosY = positionCorrection(this->height(), m_displaySizeOfPicture.height());
        qmlImageRect->setProperty("x", leftPosX + (m_displaySizeOfPicture.width() - tempImage.width()) / 2);
        qmlImageRect->setProperty("y", leftPosY + (m_displaySizeOfPicture.height() - tempImage.height()) / 2);
    } else {
        double xPos = m_leftUpPos.x() + (m_displaySizeOfPicture.width() - tempImage.width()) / 2;
        double yPos = m_leftUpPos.y() + (m_displaySizeOfPicture.height() - tempImage.height()) / 2;

        if (m_displaySizeOfPicture.width() <= this->width()) {
            xPos = this->width() / 2 - (m_displaySizeOfPicture.width() / 2)
                   + (m_displaySizeOfPicture.width() - tempImage.width()) / 2;
        }
        if (m_displaySizeOfPicture.height() <= this->height()) {
            yPos = this->height() / 2 - (m_displaySizeOfPicture.height() / 2)
                   + (m_displaySizeOfPicture.height() - tempImage.height()) / 2;
        }
        qmlImageRect->setProperty("x", xPos);
        qmlImageRect->setProperty("y", yPos);
    }

    targatImage->setProperty("scale", (m_proportion)*0.01);
    targatImage->setProperty("source", "image://thumb/" + m_imagePath);
    recordCurrentProportion = m_proportion;
    Q_EMIT perRate(QString::number(m_proportion) + "%", m_imagePath);
    return false;
}
//根据图片类型刷新右键菜单内容
void ShowImageWidget::imageMenu(QFileInfo info, QString imageSize, QString colorSpace)
{
    QString filename = info.fileName();
    //区分动图和静态图
    if (m_movieImage) {
        //设置壁纸--动图在传来时是一帧一帧，只判断并添加一次右键菜单选项
        if (m_canSet) {
            m_canSet = false;
            Q_EMIT titleName(filename, m_imagePath);         //给顶栏图片的名字
            Q_EMIT changeInfor(info, imageSize, colorSpace); //给信息栏需要的信息
            //设置右键菜单
            setMenuAction();
            //判断图片是否打开失败或者为无权限修改的图片
            stateUpdate();
            //给工具栏确定裁剪按钮的状态--必须在stateUpdate后
            Q_EMIT sendImageType(false);
        }

    } else {
        Q_EMIT titleName(filename, m_imagePath);         //给顶栏图片的名字
        Q_EMIT changeInfor(info, imageSize, colorSpace); //给信息栏需要的信息
        setMenuAction();
        //判断图片是否打开失败或者为无权限修改的图片
        stateUpdate();
        //给工具栏确定裁剪按钮的状态--必须在stateUpdate后
        if (!Variable::SUPPORT_FORMATS_NOT.contains("." + m_paperFormat.toLower()) && (m_isOpenSuccess && m_delOrNot)) {
            Q_EMIT sendImageType(true);
        } else {
            Q_EMIT sendImageType(false);
        }
    }
}

void ShowImageWidget::albumChangeImage(bool isChange)
{
    m_canSet = isChange;
}
//下一张
void ShowImageWidget::nextImage()
{
    m_canSet = true;
    Interaction::getInstance()->nextImage();
}
//上一张
void ShowImageWidget::backImage()
{
    m_canSet = true;
    Interaction::getInstance()->backImage();
}
//备用，图片加载过慢时，ui的处理--暂缓
void ShowImageWidget::delayShow(bool isLoading)
{
    if (isLoading == false) {
        if (m_loadingMovie->state() != QMovie::NotRunning) {
            m_loadingMovie->stop();
        }
        return;
    } else {
        this->m_showImage->setMovie(m_loadingMovie);
        m_loadingMovie->start();
        Q_EMIT toShowImage(); //给主界面--展示图片
    }
}

void ShowImageWidget::albumSlot(bool isOpen)
{
    m_isOpen = isOpen;
}

void ShowImageWidget::isDelete(bool isDel)
{
    if (!m_delOrNot) {
        m_isDelete = m_delOrNot;
        return;
    }
    m_isDelete = isDel;
    //    Q_EMIT toSelectHigh(isDel);
}

//复制
void ShowImageWidget::copy()
{
    //复制到剪切板
    //    QClipboard *clipBoard=QApplication::clipboard();
    //    clipBoard->setPixmap(m_pic);
    //    复制为文件
    QList<QUrl> copyfile;

    QUrl url = QUrl::fromLocalFile(m_imagePath); //待复制的文件
    if (url.isValid()) {
        copyfile.push_back(url);
    } else {
        return;
    }
    QMimeData *data = new QMimeData;
    data->setUrls(copyfile);

    QClipboard *clipBoard = QApplication::clipboard();
    clipBoard->setMimeData(data);
    //复制-埋点
    kdk::kabase::BuriedPoint buriedPointCopy;
    if (buriedPointCopy.functionBuriedPoint(kdk::kabase::AppName::KylinPhotoViewer,
                                            kdk::kabase::BuriedPoint::PT::KylinPhotoViewerCoyp)) {
        qCritical() << "buried point fail Copy!";
    }
}

void ShowImageWidget::updateImagePath(QString newImagePath)
{
    m_imagePath = newImagePath;
}
//设置为桌面壁纸
void ShowImageWidget::setDeskPaper()
{
    Interaction::getInstance()->setAsBackground();
}
//设置为锁屏壁纸
void ShowImageWidget::setLockPaper()
{
    qDebug() << "设置为锁屏壁纸";
}
//初始化打印
void ShowImageWidget::initPrint()
{
    m_printDialog = new QPrintDialog(this);
    connect(m_printDialog, SIGNAL(accepted(QPrinter *)), this, SLOT(acceptPrint(QPrinter *)));
    connect(m_printDialog, &QPrintDialog::finished, this, &ShowImageWidget::finishPrint);
    m_printDialog->setModal(true);
    m_printDialog->show();
}
//打印开始
void ShowImageWidget::acceptPrint(QPrinter *printer)
{
    Interaction::getInstance()->printImage(printer);
}
//开始裁剪
void ShowImageWidget::startCutColor()
{

    m_cutWid->show();
    m_cutWid->sizeChange(m_pic.toImage().size());
    m_cutWid->move((this->width() - m_cutWid->width()) / 2, (this->height() - m_cutWid->height()) / 2);
    m_isCutting = true;
    displayMode = DisplayMode::CuttingMode;
}
//退出裁剪
void ShowImageWidget::exitCutColor()
{
    m_cutWid->hide();
}
//开始OCR
void ShowImageWidget::startGetText()
{
    ocrMode();
    m_ocrWid->show();
    m_ocrBtnWid->show();
    QVector<QString> result;
    result.append(tr("OCR recognition..."));
    m_ocrWid->setFormatedText(result);
}

void ShowImageWidget::setGetTextResult(QVector<QString> result)
{
    m_ocrWid->setFormatedText(result);
    if (result.isEmpty()) {
        m_ocrExportToTxt->setEnabled(false);
    } else {
        m_ocrExportToTxt->setEnabled(true);
    }
}
//结束OCR
void ShowImageWidget::exitGetText()
{
    m_ocrWid->clear();
    m_ocrWid->hide();
    m_ocrBtnWid->hide();
    QObject *qmlObj = m_showImageQml->rootObject();
    qmlObj->setProperty("width", this->width());
    qmlObj->setProperty("height", this->height());
    qmlObj->setProperty("x", 0);
    qmlObj->setProperty("y", 0);
    m_showImage->resize(this->width(), this->height());
    m_showImage->move((this->width() - m_showImage->width()) / 2, (this->height() - m_showImage->height()) / 2);
    Interaction::getInstance()->changeWidgetSize(this->m_showImage->size());
    Q_EMIT viewExitOCRMode();
}

void ShowImageWidget::ocrMode()
{

    QObject *qmlObj = m_showImageQml->rootObject();
    if (displayMode == DisplayMode::OCRMode) {
        m_showImage->resize(this->width() / 2, this->height() - m_widChangeHeight);
        qmlObj->setProperty("width", this->width() / 2);
        qmlObj->setProperty("height", this->height() - m_widChangeHeight);
        qmlObj->setProperty("x", 0);
        qmlObj->setProperty("y", m_widChangeHeight);
        m_showImage->move(0, m_widChangeHeight);
        m_ocrWid->resize(this->width() / 2, this->height() - m_widChangeHeight);
        m_ocrWid->move(this->width() / 2, m_widChangeHeight);
        m_ocrBtnWid->move((this->width() - m_ocrBtnWid->width()) / 2, this->height() - m_ocrBtnWid->height() - 8);
    } else {
        qmlObj->setProperty("width", this->width());
        qmlObj->setProperty("height", this->height());
        qmlObj->setProperty("x", 0);
        qmlObj->setProperty("y", 0);
        m_showImage->resize(this->width(), this->height());
        m_showImage->move((this->width() - m_showImage->width()) / 2, (this->height() - m_showImage->height()) / 2);
    }
    m_ocrWid->resize(this->width() / 2, this->height());
    m_ocrWid->move(this->width() / 2, m_widChangeHeight);
    m_ocrBtnWid->move((this->width() - m_ocrBtnWid->width()) / 2, this->height() - m_ocrBtnWid->height() - 8);
    Interaction::getInstance()->changeWidgetSize(this->m_showImage->size());
}

void ShowImageWidget::exportToTxt()
{
    QString content = m_ocrWid->toPlainText();
    QFileDialog fileDialog(this, Qt::CustomizeWindowHint);
    QFileInfo filename(m_imagePath);
    QString savePath =
        fileDialog.getSaveFileName(this, QString(), m_path + "/" + filename.completeBaseName() + ".txt", ("*.txt"));
    QFileInfo info(savePath);
    if (savePath.isNull()) {
        return;
    }
    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        m_msg->warning(this, tr("Warning"), tr("save file failed!"));
    } else {
        QTextStream stream(&file);
        stream << content;
        stream.flush();
        file.close();
    }
}

void ShowImageWidget::saveAsOther()
{
    QString format;
    //构造另存为文件类型
    format = Variable::SUPPORT_FORMATS_SAVEAS;

    QFileDialog fileDialog(this, Qt::CustomizeWindowHint); //设置窗口标题属性自定义

    QFileInfo filename(m_imagePath);

    QString savePath =
        fileDialog.getSaveFileName(nullptr, QString(), m_path + "/" + filename.completeBaseName() + ".png", format);
    QFileInfo file(savePath);
    if (savePath.isNull()) {
        return;
    }
    if (file.fileName().indexOf(".") == 0) {
        //        qDebug()<<"不能以.命名";
        m_msg->warning(this, tr("Warning"), tr("save fail.name cannot begin with \".\" "));
        return;
    }
    for (int i = 0; i < SPECIALCHAR.length(); i++) {
        if (file.fileName().contains(SPECIALCHAR.at(i))) {
            //            qDebug()<<"命名非法";
            //含非法文件名
            m_msg->warning(this, tr("Warning"), tr("the file name is illegal"));
            return;
        }
    }
    if (file.fileName() == "") {
        //        qDebug()<<"命名非法";
        //含非法文件名
        m_msg->warning(this, tr("Warning"), tr("the file name is illegal"));
        return;
    }
    //如果没有后缀，或者后缀不在list里，就用原格式为后缀
    if (!Variable::SUPPORT_FORMATS_END.contains("." + file.suffix().toLower())) {
        if (Variable::SUPPORT_FORMATS_NOT.contains("." + file.suffix().toLower())) {
            savePath += +".png";
        } else {
            savePath += +"." + m_paperFormat.toLower();
        }
    }
    Interaction::getInstance()->needSaveAs(savePath);
}
//打印结束
void ShowImageWidget::finishPrint(int result)
{
    //失败才打印
    if (1 != result) {
        qDebug() << "========" << result;
    }
}
//删除
void ShowImageWidget::deleteImage()
{
    //    Interaction::getInstance()->deleteImage();
    Q_EMIT needDelete();
}
//在文件夹中显示
void ShowImageWidget::showInFile()
{
    Interaction::getInstance()->openImageInfile();
}
//重命名
void ShowImageWidget::reName()
{
    Q_EMIT toRename(1);
    Q_EMIT isRename();
}

void ShowImageWidget::signImage()
{
    Interaction::getInstance()->startSignImageApp();
}

void ShowImageWidget::abnormalJudgBeforeClick()
{
    setMenuEnable();
    QFile fileImage(m_imagePath);
    QFile fileSignApp(QStandardPaths::findExecutable(SIGN_APP_NAME));
    if (!fileSignApp.exists()) {
        m_signImage->setEnabled(false);
    } else if (!fileImage.exists()) {
        m_signImage->setEnabled(false);
        m_copy->setEnabled(false);
        m_setDeskPaper->setEnabled(false);
        m_print->setEnabled(false);
        //        m_deleteImage->setEnabled(false);
        m_showInFile->setEnabled(false);
        m_reName->setEnabled(false);
        m_saveAs->setEnabled(false);
    }
}
//显示右键菜单栏
void ShowImageWidget::setMenuAction()
{
    //拿到可设置为壁纸的图片格式
    QStringList formatList;
    QString format;
    format = "";
    for (const QString &str : Variable::BACKGROUND_SUPPORT_FORMATS) {
        format = str;
        formatList.append(format);
    }
    //判断是否为可设置为壁纸的类型
    if (formatList.contains(m_paperFormat)) {
        m_imageMenu->insertAction(m_showInFile, m_setDeskPaper);
        m_imageMenu->insertAction(m_setDeskPaper, m_reName);
    } else {
        m_imageMenu->removeAction(m_setDeskPaper);
        m_imageMenu->insertAction(m_showInFile, m_reName);
    }
    setMenuEnable();
}
//设置右键菜单是否选项可点击
void ShowImageWidget::setMenuEnable()
{

    m_copy->setEnabled(m_isOpenSuccess);
    m_setDeskPaper->setEnabled(m_isOpenSuccess);
    m_setLockPaper->setEnabled(m_isOpenSuccess);
    m_print->setEnabled(m_isOpenSuccess);
    if (m_movieImage || m_paperFormat == "svg") {
        m_saveAs->setEnabled(false);
    } else {
        m_saveAs->setEnabled(m_isOpenSuccess);
    }

    if (m_delOrNot == false) {
        m_reName->setEnabled(m_delOrNot);
        m_deleteImage->setEnabled(m_delOrNot);
    } else {
        m_reName->setEnabled(m_isOpenSuccess);
        m_deleteImage->setEnabled(m_isOpenSuccess);
    }
    if (SIGN_APP_NOT_SUPPORT.contains(m_paperFormat.toLower())) {
        m_signImage->setEnabled(false);
    } else {
        m_signImage->setEnabled(true);
    }
}

void ShowImageWidget::initInteraction()
{
    connect(Interaction::getInstance(), &Interaction::startWithOpenImage, this,
            &ShowImageWidget::startWithOpenImage); //启动时打开图片
    connect(Interaction::getInstance(), &Interaction::openFinish, this,
            &ShowImageWidget::openFinish); //图片打开完成，获取数据
    connect(Interaction::getInstance(), &Interaction::delayShow, this, &ShowImageWidget::delayShow);
    connect(Interaction::getInstance(), &Interaction::changeDelState, this, &ShowImageWidget::canDelete);
    connect(Interaction::getInstance(), &Interaction::isCutNotSave, this,
            &ShowImageWidget::cutQueryWid); //弹出关闭询问弹窗
    //    connect(Interaction::getInstance(), &Interaction::exitOcrModeSign, this,
    //            &ShowImageWidget::viewExitOCRMode); //弹出关闭询问弹窗
}
//双击或带参数打开
void ShowImageWidget::startWithOpenImage(QString path)
{
    if (path != Variable::API_TYPE) {
        KyView::mutual->show();
    }
    Q_EMIT startWayToSetTitleStyle();
    if (path == "") {
        return;
    }
    //双击和右键打开图片，将路径写入
    QFileInfo info(path);
    Variable::setSettings("imagePath", info.absolutePath());
    openImage(path);
}
//从权限判断是否可删除
void ShowImageWidget::canDelete(bool delOrNot)
{
    m_delOrNot = delOrNot;
}
//展示工具栏
void ShowImageWidget::showBthWid(bool isShow)
{
    if (isShow) {
        m_btnWid->show();
        m_btnWid->move((this->width() - m_btnWid->width()) / 2, this->height() - m_btnWid->height() - 8);
        return;
    }
    m_btnWid->hide();
}

int ShowImageWidget::positionCorrection(int windowSize, int pictureSize)
{
    int actualPos = windowSize / 2 - pictureSize / 2;
    if (actualPos < 0) {
        actualPos = 0;
    }
    return actualPos;
}
//退出裁剪
void ShowImageWidget::exitCut()
{
    m_cutWid->hide();
    m_btnWid->hide();
    Interaction::getInstance()->exitCut();
    //发信号给主界面，告知退出裁剪状态
    m_isCutting = false; //可进行放大缩小
    Q_EMIT needExitCut();
}
//保存裁剪图片并退出
void ShowImageWidget::needSave()
{
    m_cutWid->hide();
    m_btnWid->hide();
    //备份保存
    Interaction::getInstance()->needSaveCutImage(m_proportion);
    //弹出保存询问
    //    exitCut();
    m_isCutting = false; //可进行放大缩小
    Q_EMIT needExitCut();
}

bool ShowImageWidget::btnWidState()
{
    if (m_btnWid != nullptr) {
        if (m_btnWid->isHidden()) {
            return false;
        } else {
            return true;
        }
    }
}
//打开图片
void ShowImageWidget::openImage(QString path)
{
    if (displayMode == DisplayMode::OCRMode) {
        exitGetText();
    }
    Interaction::getInstance()->openImage(path);
}
//拿到图片信息，进行处理
void ShowImageWidget::openFinish(QVariant var)
{
    ImageAndInfo package = var.value<ImageAndInfo>();
    m_isOpenSuccess = package.openSuccess;
    QPixmap pixmap = package.image; //图片
    m_pic = pixmap;
    tempImage = package.originImage.toImage();
    m_displaySizeOfPicture = package.displaySizeOfPicture;
    m_actualClickPos = package.actualClickPos;
    //拿到返回信息
    QFileInfo info = package.info;       //详情信息
    int proportion = package.proportion; //比例
    m_proportion = proportion;
    QString imageSize = package.imageSize;
    QString colorSpace = package.colorSpace;
    QString num;
    int number = package.imageNumber; //在队列中的标签
    m_movieImage = package.movieImage;
    if (MOVIE_IMAGE_FORMAT.contains(m_paperFormat)) {
        m_movieImage = true;
    }
    m_imageNeedUpdate = package.imageNeedUpdate;
    m_imageShowWay = package.imageShowWay;
    m_zoomFocus = package.zoomFocus;
    m_leftUpPos = package.leftUpPos;

    num = QString("%1").arg(proportion) + "%";
    m_path = info.absolutePath(); //图片的路径
    m_imagePath = info.absoluteFilePath();
    m_paperFormat = info.suffix().toLower();
    m_typeNum = number;
    Q_EMIT sendSuffixToToolbar(m_paperFormat);
    //根据number决定界面显示
    if (imageNum(number)) {
        return;
    }

    //重置ocr导出文本按钮的状态
    if (m_ocrExportToTxt->isEnabled()) {
        m_ocrExportToTxt->setEnabled(false);
    }
    //使用返回的信息进行设置界面
    Q_EMIT toShowImage(); //给主界面--展示图片
    //根据图片是否为空决定是否显示转圈圈
    if (imageNUll(pixmap)) {
        return;
    }

    //根据图片类型刷新右键菜单内容
    imageMenu(info, imageSize, colorSpace);

    sideState(m_typeNum);
    m_isDelete = false;
    //    Q_EMIT toSelectHigh(false);
}
//拉伸主界面时重新安排界面显示
void ShowImageWidget::reMove(int W, int H)
{
    //拉伸主界面时重新安排界面显示
    this->resize(W, H);
    QObject *qmlObj = m_showImageQml->rootObject();

    if (displayMode == DisplayMode::OCRMode) {
        this->m_showImage->resize(this->width() / 2, this->height() - m_widChangeHeight);
        qmlObj->setProperty("width", this->width() / 2);
        qmlObj->setProperty("height", this->height() - m_widChangeHeight);
        qmlObj->setProperty("x", 0);
        qmlObj->setProperty("y", m_widChangeHeight);
        this->m_showImage->move(0, m_widChangeHeight);
        this->m_ocrWid->resize(this->width() / 2, this->height() - m_widChangeHeight);
        this->m_ocrWid->move(this->width() / 2, m_widChangeHeight);
        this->m_ocrBtnWid->move((this->width() - m_ocrBtnWid->width()) / 2, this->height() - m_ocrBtnWid->height() - 8);
    } else {
        qmlObj->setProperty("width", this->width());
        qmlObj->setProperty("height", this->height());
    }
    g_back->move(LEFT_POS, int((this->height() - g_back->height()) / 2));
    g_next->move(W - LEFT_POS - g_next->width(), int((H - g_next->height()) / 2));
}

void ShowImageWidget::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    this->m_showImage->resize(KyView::mutual->width(), KyView::mutual->height());
    QObject *qmlObj = m_showImageQml->rootObject();
    if (displayMode == DisplayMode::OCRMode) {
        this->m_showImage->resize(this->width() / 2, this->height() - m_widChangeHeight);
        qmlObj->setProperty("width", this->width() / 2);
        qmlObj->setProperty("height", this->height() - m_widChangeHeight);
        qmlObj->setProperty("x", 0);
        qmlObj->setProperty("y", m_widChangeHeight);
        this->m_showImage->move(0, m_widChangeHeight);
        this->m_ocrWid->resize(this->width() / 2, this->height() - m_widChangeHeight);
        this->m_ocrWid->move(this->width() / 2, m_widChangeHeight);
        this->m_ocrBtnWid->move((this->width() - m_ocrBtnWid->width()) / 2, this->height() - m_ocrBtnWid->height() - 8);
    } else {
        qmlObj->setProperty("width", this->width());
        qmlObj->setProperty("height", this->height());
        qmlObj->setProperty("x", 0);
        qmlObj->setProperty("y", 0);
    }
    Interaction::getInstance()->changeWidgetSize(this->m_showImage->size());
}
//滚轮放大缩小
bool ShowImageWidget::eventFilter(QObject *obj, QEvent *event)
{
    //滚轮进行放大缩小图片
    if (obj == m_showImage) {
        if (event->type() == QEvent::Wheel) {
            QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event);
            if (m_isOpenSuccess) {
                if (displayMode != DisplayMode::NormalMode) {
                    return QObject::eventFilter(obj, event);
                }
                QPoint zoomFocus = wheelEvent->pos();
                if (wheelEvent->angleDelta().y() > 0) {
                    m_addOrreduce = true;
                    Q_EMIT enlargeChange(zoomFocus);
                } else {
                    m_addOrreduce = false;
                    Q_EMIT reduceChange(zoomFocus);
                }
            }
        }
    }
    //滚轮进行放大缩小图片
    if (obj == m_showImageQml) {
        if (event->type() == QEvent::Wheel) {
            QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event);
            if (m_isOpenSuccess) {
                if (displayMode != DisplayMode::NormalMode) {
                    return QObject::eventFilter(obj, event);
                }
                QPoint zoomFocus = wheelEvent->pos();
                if (wheelEvent->angleDelta().y() > 0) {
                    m_addOrreduce = true;
                    Q_EMIT enlargeChange(zoomFocus);
                } else {
                    m_addOrreduce = false;
                    Q_EMIT reduceChange(zoomFocus);
                }
            }
        }
    }
    //裁剪后使qmenu隐藏
    if (displayMode != DisplayMode::NormalMode) {
        m_imageMenu->hide();
    }
    return QObject::eventFilter(obj, event);
}
//裁剪的工具栏按钮样式设置
void ShowImageWidget::cutBtnWidStyle()
{


    m_save->setStyleSheet(
        "QPushButton{border:0px;border-radius:4px;background:transparent;border-image: url(:/res/res/save.png);}"
        "QPushButton::hover{border:0px;border-radius:4px;background:transparent;border-image: "
        "url(:/res/res/save_hover.png);}"
        "QPushButton::pressed{border:0px;border-radius:4px;background:transparent;border-image: "
        "url(:/res/res/save_hover.png);}");
    m_cancel->setStyleSheet(
        "QPushButton{border:0px;border-radius:4px;background:transparent;border-image: url(:/res/res/cancel.png);}"
        "QPushButton::hover{border:0px;border-radius:4px;background:transparent;border-image: "
        "url(:/res/res/cancel_hover.png);}"
        "QPushButton::pressed{border:0px;border-radius:4px;background:transparent;border-image: "
        "url(:/res/res/cancel_hover.png);}");
}
// OCR的工具栏按钮样式设置
void ShowImageWidget::ocrBtnWidStyle()
{
    m_ocrCancel->setStyleSheet("QPushButton{border:0px;border-radius:4px;background:transparent;}"
                               "QPushButton::hover{border:0px;border-radius:4px;background:transparent;}"
                               "QPushButton::pressed{border:0px;border-radius:4px;background:transparent;}");
    m_ocrExportToTxt->setStyleSheet("QPushButton{border:0px;border-radius:4px;background:transparent;}"
                                    "QPushButton::hover{border:0px;border-radius:4px;background:transparent;}"
                                    "QPushButton::pressed{border:0px;border-radius:4px;background:transparent;}");
}

void ShowImageWidget::stateUpdate()
{
    //判断图片是否打开失败或者为无权限修改的图片

    Q_EMIT fileState(m_isOpenSuccess, m_delOrNot);
}

int ShowImageWidget::makeSureHeightState()
{
    int widHeight = BAR_HEIGHT;
    if (platForm.contains(Variable::platForm)) {
        widHeight = BAR_HEIGHT_INTEL;
    }
    return widHeight;
}

void ShowImageWidget::navigatorState(bool state)
{
    m_navigatorState = state;
}

void ShowImageWidget::navigatorMove(bool isDrageImage)
{
    m_isDragImage = isDrageImage;
}
void ShowImageWidget::changeQmlcomponentColor(QColor color, double opacity)
{
    QObject *qmlObj = m_showImageQml->rootObject();
    qmlObj->setProperty("color", color);
    //    QPalette pal(this->palette());
    //    pal.setColor(QPalette::Window, QColor(color));
    //    this->setPalette(pal);
    //        qmlObj->setProperty("opacity", opacity);
}
//裁剪的工具栏窗口样式设置
void ShowImageWidget::cutBtnWidChange(QString themeTyep)
{
    if ("ukui-dark" == themeTyep || "ukui-black" == themeTyep) {
        m_btnWid->setStyleSheet("QWidget{background-color:rgba(0,0,0,0.72);border-radius:6px;}");
        m_ocrBtnWid->setStyleSheet("QWidget{background-color:rgba(0,0,0,0.72);border-radius:6px;}");
    } else {
        m_btnWid->setStyleSheet("QWidget{background-color:rgba(255, 255, 255, 1);border-radius:6px;}");
        m_ocrBtnWid->setStyleSheet("QWidget{background-color:rgba(255, 255, 255, 1);border-radius:6px;}");
    }
}
//备用-目前不需要-以后可能会用到
void ShowImageWidget::cutQueryWid()
{
    m_queryMsg->warning(this, tr("Warning"), tr("是否保存对此图片的更改？"), QMessageBox::Ok);
}

void ShowImageWidget::cutFinishUi()
{
    if (m_cutWid != nullptr) {
        m_cutWid->cutFinish();
    }
}
