#include "wpageitem.h"
#include "wpageattr.h"
#include "wpageitemwidget.h"
#include "wProgramManager/wEditProgram/wElement/eobject.h"
#include "wProgramManager/wEditProgram/wElement/etext.h"
#include "wProgramManager/wEditProgram/wElement/ephoto.h"
#include "wProgramManager/wEditProgram/wElement/emovie.h"
#include "wProgramManager/wEditProgram/wElement/egif.h"
#include "wProgramManager/wEditProgram/wElement/edclock.h"
#include "wProgramManager/wEditProgram/wElement/eaclock.h"
#include "wProgramManager/wEditProgram/wElement/etemp.h"
#include "wProgramManager/wEditProgram/wElement/eweather.h"
#include "wProgramManager/wEditProgram/wElement/etimer.h"
#include "wProgramManager/wEditProgram/wElement/ewindow.h"

wPageItem::wPageItem(const QJsonDocument &json, const QString &path, const QSize &resolution, QListWidget *view, int type) :
    QObject(view),
    QListWidgetItem(view, type),
    m_jRoot(json),
    m_jOldRoot(json),
    m_strProgramItemPath(path),
    m_resolution(resolution)
{
    init();
}

wPageItem::wPageItem(const wPageItem &other) :
    QObject(other.listWidget()),
    QListWidgetItem(other),
    m_jRoot(other.jRoot()),
    m_jOldRoot(other.jRoot()),
    m_strProgramItemPath(other.pRoot()),
    m_resolution(other.resolution())
{
    init();
}

wPageItem::~wPageItem()
{
    m_scene->deleteLater();
//    delete m_scene; // Crash when app closing.
}

void wPageItem::init()
{
    QRectF rect(0, 0, m_resolution.width(), m_resolution.height());
    m_scene = new QGraphicsScene();
    m_scene->setObjectName("wDrawingScene");
    m_scene->setSceneRect(rect);

    QPen   pen(Qt::black);
    QBrush bsh(Qt::black);
    auto wBackground = m_scene->addRect(rect, pen, bsh);
    auto flags = wBackground->flags();
    flags &= ~QGraphicsItem::ItemIsMovable;
    flags &= ~QGraphicsItem::ItemIsSelectable;
    flags &= ~QGraphicsItem::ItemIsFocusable;
    wBackground->setFlags(flags);
    m_wBackground = wBackground;

    QJsonArray elements = m_jRoot["elements"].toArray();
    int n = elements.count();
    for(int i=0; i<n; i++) {
        QJsonObject json = elements.at(i).toObject();
        restoreElement(json);
    }
}
//根据json中的elementTypeId来判断创建对应的媒体组件属性页
void wPageItem::restoreElement(const QJsonObject &json)
{
//    int type = json["elementTypeId"].toInt();
//    const QString &pRoot = m_strProgramItemPath;
//    eObject *element = nullptr;
//    switch (type) {
//    case eObject::Text :
//        element = new eText(json);
//        break;
//    case eObject::Photo :
//        element = new ePhoto(json, pRoot);
//        break;
//    case eObject::Movie :
//        element = new eMovie(json, pRoot);
//        break;
//    case eObject::Gif :
//        element = new eGif(json, pRoot);
//        break;
//    case eObject::DClock :
//        element = new eDClock(json);
//        break;
//    case eObject::AClock :
//        element = new eAClock(json);
//        break;
//    case eObject::Office :
//        break;
//    case eObject::Temp :
//        element = new eTemp(json);
//        break;
//    case eObject::Weather :
//        element = new eWeather(json);
//        break;
//    case eObject::Rss :
//        break;
//    case eObject::Timer :
//        element = new eTimer(json);
//        break;
//    case eObject::ColorText :
//        break;
//    case eObject::Window :
//        element = new eWindow(json, pRoot);
//        break;
//    default:
//        element = nullptr;
//        break;
//    }
    QString type = json["elementType"].toString();
    const QString &pRoot = m_strProgramItemPath;
    eObject *element = nullptr;
    if(type=="Text")
        element = new eText(json);
    else if(type=="Photo")
        element = new ePhoto(json, pRoot);
    else if(type=="Movie")
        element = new eMovie(json, pRoot);
    else if(type=="Gif")
        element = new eGif(json, pRoot);
    else if(type=="DClock")
        element = new eDClock(json);
    else if(type=="AClock")
        element = new eAClock(json);
    else if(type=="Office")
        element = nullptr;
    else if(type=="Temp")
        element = new eTemp(json);
    else if(type=="Weather")
        element = new eWeather(json);
    else if(type=="Rss")
        element = nullptr;
    else if(type=="Timer")
        element = new eTimer(json);
    else if(type=="ColorText")
        element = nullptr;
    else if(type=="Window")

        element = new eWindow(json, pRoot);
    else
        element = nullptr;


    if(element != nullptr) {
        m_scene->addItem(element);
        element->setRLimit(QRectF(0, 0, m_resolution.width(), m_resolution.height()));
    }
}
void wPageItem::connectCiTieSignal(wDrawingBoard *drawingboard)
{
    QStringList flist;
    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element!=nullptr)
            {
                 connect(element,SIGNAL(sigCiTie(bool,int)),drawingboard,SLOT(OnCiTieProcess(bool,int)));
            }
        }
    }

}
void wPageItem::disconnectCiTieSignal(wDrawingBoard *drawingboard)
{
    QStringList flist;
    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element!=nullptr)
            {
                 disconnect(element,SIGNAL(sigCiTie(bool,int)),drawingboard,SLOT(OnCiTieProcess(bool,int)));
            }
        }
    }

}

void wPageItem::ClearAllContent()
{

}
QStringList wPageItem::filesList() const
{
    QStringList flist;
    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element->interactiveType() == eObject::Dynamic)
                flist.append(element->filesList());
        }
    }
    return flist;
}
//创建左边幻灯片，返回改项组件指针
wPageItemWidget* wPageItem::wPage(bool newOne)
{
    if(newOne) {
        m_wPage = new wPageItemWidget(m_scene);
        m_wPage->onRepeatChanged(jRoot()["repeat"].toInt());
    }
    return m_wPage;
}
//创建右边页属性组件，返回页属性组件指针
wPageAttr *wPageItem::wAttr(bool newOne)
{
    if(newOne) {
        m_wPageAttr = new wPageAttr(this);
        m_globalstrSavePath=m_strProgramItemPath;//+MACRO_FENGEFU + m_jRoot["name"].toString();

    }
    return m_wPageAttr;
}


void wPageItem::save(const QString &pParent)
{
    //pagelist中的一个pageitem，在节目名的目录下，根据pageitem的pagename创建文件夹，文件夹中包含page.json
    QString pRoot = pParent + MACRO_FENGEFU + name();
    QDir dRoot(pRoot);
    if(!dRoot.exists()) //如果目录不存在则创建目录
    {
        QDir dParent(pParent);
        dParent.mkdir(name());
    }

    if(dRoot.exists()) {
        QJsonArray oElements;
        QJsonObject oRoot = m_jRoot.object();
        QList<QGraphicsItem *> list = m_scene->items();
        //循环查找元素，将元素写入page.json
        foreach(QGraphicsItem *item, list) {
            if(item->type() > QGraphicsItem::UserType) {
                eObject *element = static_cast<eObject*>(item);
                if(element->interactiveType() == eObject::Dynamic)
                    oElements.append(element->save(pRoot));
            }
        }
        oRoot["elements"] = oElements;
        m_jRoot.setObject(oRoot);
        m_strProgramItemPath = pRoot;
        QFile f(pRoot + "\\page.json");
        f.open(QIODevice::WriteOnly);
        f.write(m_jRoot.toJson());
        f.close();
    }
}
//更新页属性参数到page.json
void wPageItem::updateJson()
{
    QJsonObject oRoot = m_jRoot.object();
    QJsonArray oElements;
    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element->interactiveType() == eObject::Dynamic)
                oElements.append(element->elementJson());
        }
    }
    oRoot["elements"] = oElements;
    m_jRoot.setObject(oRoot);
}
bool wPageItem::IsChange(const QJsonDocument &OldJsonDocument)
{
 //   QJsonObject oRoot1 = m_jOldRoot.object();
    updateJson();
    QJsonObject oRoot = m_jRoot.object();
    QJsonObject oOldRoot = OldJsonDocument.object();

    if(oRoot["name"]!=oOldRoot["name"])
         return true;
    if(oRoot["order"]!=oOldRoot["order"])
         return true;
    if(oRoot["repeat"]!=oOldRoot["repeat"])
         return true;
    if(oRoot["validDate"]!=oOldRoot["validDate"])
         return true;
    if(oRoot["plans"]!=oOldRoot["plans"])
         return true;
    QJsonArray oElements = oRoot["elements"].toArray();
    QJsonArray oOldElements = oOldRoot["elements"].toArray();
    int n = oElements.count();
    for(int i=0; i<n; i++) {
        QJsonObject oElement = oElements.at(i).toObject();
        QJsonObject oOldElement = oOldElements.at(i).toObject();
        if(oElement["elementType"]!=oOldElement["elementType"])
            return true;
        if(oElement["elementTypeId"]!=oOldElement["elementTypeId"])
            return true;
        if(oElement["geometry"]!=oOldElement["geometry"])
            return true;
        if(oElement["play"]!=oOldElement["play"])
            return true;
        if(oElement["elementType"]=="Window")
        {
            QJsonArray subElements=oElement["elements"].toArray();
            QJsonArray subOldElements=oOldElement["elements"].toArray();
            int nn = subElements.count();
            for (int ii=0;ii<nn;ii++) {

                QJsonObject subElement = subElements.at(ii).toObject();
                QJsonObject subOldElement = subOldElements.at(ii).toObject();
                if(subElement["elementType"]!=subOldElement["elementType"])
                    return true;
                if(subElement["elementTypeId"]!=subOldElement["elementTypeId"])
                    return true;
                if(subElement["geometry"]!=subOldElement["geometry"])
                    return true;
                if(subElement["play"]!=subOldElement["play"])
                    return true;
                QJsonObject oSubWidget = subElement.value("widget").toObject();
                QJsonObject oSubOldWidget = subOldElement.value("widget").toObject();
                QString aaa=oSubWidget.value("file").toString();
                QString bbb=oSubOldWidget.value("file").toString();
                if(aaa!=bbb)
                    return true;
                aaa=oSubWidget.value("path").toString();
                bbb=oSubOldWidget.value("path").toString();
                if(aaa!=bbb)
                    return true;
            }
        }
        else {
            QJsonObject oWidget = oElement.value("widget").toObject();
            QJsonObject oOldWidget = oOldElement.value("widget").toObject();
            QString aa=oWidget.value("file").toString();
            QString bb=oOldWidget.value("file").toString();
            if(aa!=bb)
                return true;
            aa=oWidget.value("path").toString();
            bb=oOldWidget.value("path").toString();
            if(aa!=bb)
                return true;

        }

    }
    if(oRoot["validDate"]!=oOldRoot["validDate"])
         return true;

    if(oRoot != oOldRoot)
        return true;
    return false;
}
void wPageItem::setRes(qreal w, qreal h)
{
    m_resolution = QSizeF(w, h);
    QRectF rect(0, 0, w, h);
    m_scene->setSceneRect(rect);
    m_wBackground->setRect(rect);
    m_wPage->updateScale(m_scene);

    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element->interactiveType() == eObject::Dynamic)
                element->setRLimit(QRectF(0, 0, w, h));
        }
    }

    m_scene->update(m_scene->sceneRect());
}

void wPageItem::playElements()
{
    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element->interactiveType() == eObject::Dynamic)
                emit element->sPlayBQ();
        }
    }
}

void wPageItem::stopElements()
{
    QList<QGraphicsItem *> list = m_scene->items();
    foreach(QGraphicsItem *item, list) {
        if(item->type() > QGraphicsItem::UserType) {
            eObject *element = static_cast<eObject*>(item);
            if(element->interactiveType() == eObject::Dynamic)
                emit element->sStopBQ();
        }
    }
}
//使用json键值对更新json文档
void wPageItem::onAttrUpdated(const QJsonObject &json)
{
    QJsonObject oRoot = m_jRoot.object();
    oRoot["name"]      = json["name"];
    oRoot["repeat"]    = json["repeat"];
    oRoot["validDate"] = json["validDate"];
    oRoot["plans"]     = json["plans"];
    m_jRoot.setObject(oRoot);
}
