#include "ephoto.h"
#include "ephotoattr.h"
#include "QThread"
ePhoto::ePhoto(QRectF rectInit,QSizeF DrawBoardSize,const QString &file, InteractiveType type, QGraphicsItem *parent) :
    eObject(rectInit,type, parent)
{
    m_rectInit=rectInit;
    m_DrawBoardSize=DrawBoardSize;
    m_iType=eObject::Photo;
    int iResult=onResChanged(file);
    if(iResult==2)
    {

    }
    else {
        setPlayArg(10, 1, 0, 0);
        int x=rectInit.left();
        int y=rectInit.top();
        qreal ihbiw=static_cast<qreal>(m_photo.height())/ static_cast<qreal>(m_photo.width());
        qreal iwbih=static_cast<qreal>(m_photo.width()) / static_cast<qreal>(m_photo.height());
        qreal w = rectInit.width();
        qreal h = floor(w*ihbiw );
        if(x+w>DrawBoardSize.width())
        {
            x=0;
            if(w>DrawBoardSize.width())
                w=DrawBoardSize.width();
            h=w*ihbiw;
        }
        if(y+h>DrawBoardSize.height())
        {
            y=0;
            if(h>DrawBoardSize.height())
                h=DrawBoardSize.height();

            w=h*iwbih;
        }
        setGeometry(QRectF(x, y, w, h));
    }

}
ePhoto::ePhoto(QRectF rectInit,const QString &file, InteractiveType type, QGraphicsItem *parent) :
    eObject(rectInit,type, parent)
{
    m_iType=eObject::Photo;
    onResChanged(file);
    setPlayArg(10, 1, 0, 0);
    qreal x=rectInit.left();
    qreal y=rectInit.top();
    qreal w=rectInit.width();
    qreal h=rectInit.height();
    setGeometry(QRectF(x, y, w, h));
}
ePhoto::ePhoto(const QJsonObject &json, const QString &pRoot, InteractiveType type, QGraphicsItem *parent) :
    eObject(json["geometry"].toObject(), type, parent)
{
    m_iType=eObject::Photo;
    QJsonDocument jRoot(json);
    QString file0 = pRoot                              + MACRO_FENGEFU + jRoot["widget"]["file"].toString();
    QString file1 = jRoot["widget"]["path"].toString() + MACRO_FENGEFU + jRoot["widget"]["file"].toString();
    QString file2 = jRoot["widget"]["path"].toString() + MACRO_FENGEFU + jRoot["widget"]["yuanshi_file"].toString();
    QString file3 = jRoot["widget"]["computer_pic_file"].toString() ;
    QString file4 = jRoot["widget"]["path"].toString() + MACRO_FENGEFU +"card_"+ jRoot["widget"]["file"].toString();

    QFile f0(file0);
    QFile f1(file1);
    QFile f2(file2);
    QFile f3(file3);
    QFile f4(file4);
    QString file;
    if(f0.exists()) {
        file = file0;
    } else if(f1.exists()) {
        file = file1;
    }
    else if(f2.exists()) {
            file = file2;
        }
    else if(f3.exists())
    {
        file = file3;
    }
    else if(f4.exists())
    {
        file = file4;
    }
    else {
        setGeometry(RECTF_INVALID);
        return;
    }
    onResChanged(file);
    setPlayArg(jRoot["play"]["playDuration"].toInt(),
               jRoot["play"]["playTimes"].toInt(),
               jRoot["play"]["enterStyle"].toInt(),
               jRoot["play"]["enterDuration"].toInt());

    m_attr.name          = json["widget"]["file"].toString();
    m_attr.yuanshi_name          = json["widget"]["yuanshi_file"].toString();
    m_attr.computer_pic_file          = json["widget"]["computer_pic_file"].toString();
    m_attr.path          = json["widget"]["path"].toString();
    m_attr.playDuration  = json["play"]["playDuration"].toInt();
    m_attr.playTimes     = json["play"]["playTimes"].toInt();
    m_attr.enterStyle    = json["play"]["enterStyle"].toInt();
    m_attr.enterDuration = json["play"]["enterDuration"].toInt();

}

void ePhoto::setElement(const QJsonObject &json, Data &attr)
{
    attr.name          = json["widget"]["file"].toString();
    attr.yuanshi_name          = json["widget"]["yuanshi_file"].toString();
    attr.computer_pic_file          = json["widget"]["computer_pic_file"].toString();
    attr.path          = json["widget"]["path"].toString();
    attr.playDuration  = json["play"]["playDuration"].toInt();
    attr.playTimes     = json["play"]["playTimes"].toInt();
    attr.enterStyle    = json["play"]["enterStyle"].toInt();
    attr.enterDuration = json["play"]["enterDuration"].toInt();


}

void ePhoto::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->save();
    painter->drawImage(rect(), m_photo);
    painter->restore();
    eObject::paint(painter, option, widget);
}
void ePhoto:: deleteContent()
{
    QFile file(m_attr.path+"/card_"+m_attr.name);
    if(file.exists())
        file.remove();
    QFile file2(m_attr.path+"/"+m_attr.name);
    if(file2.exists())
        file2.remove();
    QFile file1(m_attr.path+"/"+m_attr.yuanshi_name);
    if(file1.exists())
        file1.remove();
}
QWidget* ePhoto::wAttr()
{
    QWidget *wObj = eObject::wAttr();
    QWidget *w = wAttrElement();
    static_cast<QBoxLayout*>(w->layout())->insertWidget(0, wObj);
    return w;
}

QWidget* ePhoto::wAttrElement()
{
    ePhotoAttr *w = new ePhotoAttr(m_attr);
    connect(w, SIGNAL(sResChanged(const QString &)),       this, SLOT(onResChanged(const QString &)));
    connect(w, SIGNAL(sAttrChanged(const ePhoto::Data &)), this, SLOT(onAttrChanged(const ePhoto::Data &)));
    return w;
}
#include <QMessageBox>
QJsonObject ePhoto::save(const QString &pRoot)
{
    QString fileOld = m_attr.computer_pic_file;
    QString file0 = m_attr.path + PAGEDEL_SUFFIX + MACRO_FENGEFU + m_attr.name;
    QString file1 = m_attr.path + MACRO_FENGEFU + m_attr.name;
    QString file2 = m_attr.path + MACRO_FENGEFU + m_attr.yuanshi_name;
    QString file3 = m_attr.path + PAGEDEL_SUFFIX + MACRO_FENGEFU + m_attr.yuanshi_name;
    QFile fOld(fileOld);
    QFile f0(file0);
    QFile f1(file1);
    QFile f2(file2);
    QFile f3(file3);

    QString old_file;
    QString file_full=old_file.replace(MACRO_DANYINFANXIEGAN, MACRO_DANYINXIEGAN);
//    QString strFileMD5=getFileMd5(file_full);
//    m_attr.name=strFileMD5;
//    QString new_file = pRoot + MACRO_FENGEFU + strFileMD5;
    QString new_file = pRoot + MACRO_FENGEFU + m_attr.yuanshi_name;
    if(fOld.exists()) {
        old_file = fileOld;
    }
    else {
        if(f0.exists()) {
            old_file = file0;
        }
        else
        {
            if(f3.exists())
            {
                old_file = file3;
            }
            else {
                if(f1.exists())
                {
                    old_file = file1;
                }
                else {
                    if(f2.exists())
                    {
                        old_file = file2;
                    }
                    else {
                        return QJsonObject();
                    }
                }
            }

        }
    }


    //QMessageBox::warning(nullptr, "Tip", tr("1"));


    QFile old_f(old_file);
    QFile new_f(new_file);
    if(!new_f.exists())
    {
        old_f.copy(new_file);
        QImage imageOlde(old_file);
        qreal x=rect().left();
        qreal y=rect().top();
        qreal w=rect().width();
        qreal h=rect().height();
        if(h<=1)
            h=1;
        qreal bili=w/h;
        if(imageOlde.height()!=0)
        {
            qreal ImageBili=imageOlde.width()/imageOlde.height();
            //QMessageBox::warning(nullptr, "Tip", tr("2"));
            if(ImageBili>=bili && ImageBili!=0)
            {
                QImage fitimgpic=imageOlde.scaled(rect().width(),rect().width()/ImageBili,Qt::KeepAspectRatioByExpanding);
                QString strControllerPicPathName=pRoot+MACRO_FENGEDANFU+"card_"+m_attr.name;
                fitimgpic.save(strControllerPicPathName);
                //QMessageBox::warning(nullptr, "Tip", tr("3"));

            }
            else {
               QImage fitimgpic= imageOlde.scaled(rect().height()*ImageBili,rect().height(),Qt::KeepAspectRatioByExpanding);
               QString strControllerPicPathName=pRoot+MACRO_FENGEDANFU+"card_"+m_attr.name;
               if(fitimgpic.save(strControllerPicPathName)==false)
               {
                  // QMessageBox::warning(nullptr, "Tip", strControllerPicPathName+"\r\n"+old_file+"\r\n"+new_file);
                     old_f.copy(strControllerPicPathName);
               }
               else {

               }


            }

        }
    }
    else {
        QString strControllerPicPathName=pRoot+MACRO_FENGEDANFU+"card_"+m_attr.name;
        QFile new_card_pic(strControllerPicPathName);
        if(!new_card_pic.exists())
        {
            QImage imageOlde(old_file);
            qreal x=rect().left();
            qreal y=rect().top();
            qreal w=rect().width();
            qreal h=rect().height();
            if(h<=1)
                h=1;
            qreal bili=w/h;
            if(imageOlde.height()!=0)
            {
                qreal ImageBili=imageOlde.width()/imageOlde.height();
                if(ImageBili>=bili && ImageBili!=0)
                {
                    QImage fitimgpic=imageOlde.scaled(rect().width(),rect().width()/ImageBili,Qt::KeepAspectRatioByExpanding);
                    fitimgpic.save(strControllerPicPathName);
                    //QMessageBox::warning(nullptr, "Tip", tr("3"));

                }
                else {
                    QImage fitimgpic= imageOlde.scaled(rect().height()*ImageBili,rect().height(),Qt::KeepAspectRatioByExpanding);
                    if(fitimgpic.save(strControllerPicPathName)==false)
                    {
                        // QMessageBox::warning(nullptr, "Tip", strControllerPicPathName+"\r\n"+old_file+"\r\n"+new_file);
                        old_f.copy(strControllerPicPathName);
                    }
                    else {

                    }


                }

            }
            //QMessageBox::warning(nullptr, "Tip", tr("2"));

        }
    }

    m_attr.path = pRoot;
    if(m_CropFlag && !m_photo.isNull())//如果图 剪切过
    {
        QString strNewPicPathName=m_attr.path+MACRO_FENGEDANFU+m_attr.yuanshi_name;


        QString strControllerPicPathName=pRoot+MACRO_FENGEDANFU+"card_"+m_attr.name;
        m_photo.save(strNewPicPathName);
        m_photo.save(strControllerPicPathName);

    }

    return elementJson();
}

QStringList ePhoto::filesList() const
{
    QStringList list;
    list.append(m_attr.path + MACRO_FENGEFU + m_attr.name);
    return list;
}

QJsonObject ePhoto::elementJson() const
{
    QJsonObject oRoot;
    QJsonObject oWidget;
    QJsonObject oPlay;
    // Interior
    oRoot["elementType"]   = "Photo";
    oRoot["elementTypeId"] = type();
    oRoot["geometry"]      = eObject::elementJson();
    // Widget
    oWidget["file"]        = m_attr.name;
    oWidget["computer_pic_file"]        = m_attr.computer_pic_file;
    oWidget["yuanshi_file"]        = m_attr.yuanshi_name;
    //oWidget["path"]        = m_attr.path;
    QString strtempPath=   m_attr.path;
    strtempPath.replace(MACRO_DANYINFANXIEGAN, MACRO_DANYINXIEGAN);
    oWidget["path"]        = strtempPath;
    oRoot["widget"]        = oWidget;
    // Play
    oPlay["playDuration"]  = m_attr.playDuration;
    oPlay["playTimes"]     = m_attr.playTimes;
    oPlay["enterStyle"]    = m_attr.enterStyle;
    oPlay["enterDuration"] = m_attr.enterDuration;
    oRoot["play"]          = oPlay;
    return oRoot;
}

int ePhoto::onResChanged(const QString &file)
{
    QFileInfo fi(file);
    m_attr.computer_pic_file=file;
    m_attr.name = fi.fileName();
    if(!fi.fileName().contains("yuanshi_"))
    {
         m_attr.yuanshi_name ="yuanshi_"+fi.fileName();
    }
    else {
        m_attr.yuanshi_name =fi.fileName();

    }
    m_attr.path = fi.absolutePath();
    if(fi.exists())
    {        qDebug()  << file<< "*********old";

        m_photo = QImage(file);
        if(m_photo.isNull())
        {

            QString strAppPath=QApplication::applicationDirPath();
            strAppPath.replace(MACRO_DANYINFANXIEGAN, MACRO_DANYINXIEGAN);
            process = new QProcess(nullptr);
            process->setWorkingDirectory(strAppPath);
            //connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(ConvertImage(int,QProcess::ExitStatus)));
            //connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(outputCommand()));
            //connect(process,SIGNAL(readyReadStandardError()),this,SLOT(outputCommand()));
            QStringList args;
            args<<"-i"<<file;
            args<<"-vf"<<"scale=1920:-1";
            QString strProgramItemPath = LoAppConfig::getInstance()->NProgramsLocation();
            //原始节目保存的路径
            m_strNewFileName=strProgramItemPath+"/"+fi.fileName();
            m_strNewFileName.replace(MACRO_DANYINFANXIEGAN, MACRO_DANYINXIEGAN);
            args<<m_strNewFileName;

           // QString strCmd="ffmpeg -i \""+file+" -vf “scale=1920:-1” output.jpg";
            process->start("ffmpeg",args);
            QFileInfo ff(m_strNewFileName);
            int iReTryCount=0;
            while(!ff.exists())
            {
                QThread::sleep(1);
                iReTryCount++;

                if(iReTryCount>10)
                    break;
            }

            m_attr.computer_pic_file=m_strNewFileName;
            QFileInfo fiNew(m_strNewFileName);
            m_attr.name = fiNew.fileName();
            if(!fiNew.fileName().contains("yuanshi_"))
            {
                 m_attr.yuanshi_name ="yuanshi_"+fiNew.fileName();
            }
            else {
                m_attr.yuanshi_name =fiNew.fileName();

            }
            m_attr.path = fiNew.absolutePath();
            m_photo = QImage(m_strNewFileName);
            setPlayArg(10, 1, 0, 0);
            int x=m_rectInit.left();
            int y=m_rectInit.top();
            qreal ihbiw=static_cast<qreal>(m_photo.height())/ static_cast<qreal>(m_photo.width());
            qreal iwbih=static_cast<qreal>(m_photo.width()) / static_cast<qreal>(m_photo.height());
            qreal w = m_rectInit.width();
            qreal h = floor(w*ihbiw );
            if(x+w>m_DrawBoardSize.width())
            {
                x=0;
                if(w>m_DrawBoardSize.width())
                    w=m_DrawBoardSize.width();
                h=w*ihbiw;
            }
            if(y+h>m_DrawBoardSize.height())
            {
                y=0;
                if(h>m_DrawBoardSize.height())
                    h=m_DrawBoardSize.height();

                w=h*iwbih;
            }
            setGeometry(QRectF(x, y, w, h));
            return 2;



        }
        else
        {
            //QString strCmd="ffmpeg -i \""+file+" -vf “scale=1920:-1” output.jpg";
        }
        //m_photo.load(file);
         //QPixmap objPixmap(file);



    }
    else {
        QString strFileNew=fi.path()+"/"+m_attr.yuanshi_name;
        qDebug()  << strFileNew<< "*********new";
        m_photo = QImage(strFileNew);

    }
}
void ePhoto::ConvertImage(int i,QProcess::ExitStatus)
{
    Q_UNUSED(i);
    delete process;
    m_attr.computer_pic_file=m_strNewFileName;
    QFileInfo fiNew(m_strNewFileName);
    m_attr.name = fiNew.fileName();
    if(!fiNew.fileName().contains("yuanshi_"))
    {
         m_attr.yuanshi_name ="yuanshi_"+fiNew.fileName();
    }
    else {
        m_attr.yuanshi_name =fiNew.fileName();

    }
    m_attr.path = fiNew.absolutePath();
    m_photo = QImage(m_strNewFileName);
    setPlayArg(10, 1, 0, 0);
    int x=m_rectInit.left();
    int y=m_rectInit.top();
    qreal ihbiw=static_cast<qreal>(m_photo.height())/ static_cast<qreal>(m_photo.width());
    qreal iwbih=static_cast<qreal>(m_photo.width()) / static_cast<qreal>(m_photo.height());
    qreal w = m_rectInit.width();
    qreal h = floor(w*ihbiw );
    if(x+w>m_DrawBoardSize.width())
    {
        x=0;
        if(w>m_DrawBoardSize.width())
            w=m_DrawBoardSize.width();
        h=w*ihbiw;
    }
    if(y+h>m_DrawBoardSize.height())
    {
        y=0;
        if(h>m_DrawBoardSize.height())
            h=m_DrawBoardSize.height();

        w=h*iwbih;
    }
    setGeometry(QRectF(x, y, w, h));
}
void ePhoto::onAttrChanged(const ePhoto::Data &data)
{
    setPlayArg(data.playDuration, data.playTimes, data.enterStyle, data.enterDuration);
}

void ePhoto::setPlayArg(int pd, int pt, int es, int ed)
{
    m_attr.playDuration  = pd;
    m_attr.playTimes     = pt;
    m_attr.enterStyle    = es;
    m_attr.enterDuration = ed;
}
void ePhoto::CropCurImage(QRect rt)
{
    stopElectment();
    m_photo=m_photo.copy(rt);
    m_CropFlag=true;
}
