#include "wpagelist.h"
#include "wpageitem.h"
#include "wpageitemwidget.h"
#include <LoUIClass/x_uimsgboxokcancel.h>
//节目编辑主页中靠左边的页切换类表组件
wPageList::wPageList(const QString &pRoot, int w, int h, QWidget *parent) :
    QWidget(parent),
    m_strProgramItemPath(pRoot),
    m_width(w),
    m_height(h)
{
    setAttribute(Qt::WA_DeleteOnClose);
    QToolBar *tb_page_list = new QToolBar(this);
    tb_page_list->setIconSize(QSize(16,16));
    tb_page_list->setProperty("ssType", "progEditor");
    tb_page_list->setProperty("ssName", "pageManager");

 //   QAction *spacer     = new QAction();
    QAction *act_add    = new QAction(QIcon(":/res/ProgramManager/EditProgram/Add.png"),    tr("Add page"));
    QAction *act_copy   = new QAction(QIcon(":/res/ProgramManager/EditProgram/Copy.png"),   tr("Copy page"));
    QAction *act_del    = new QAction(QIcon(":/res/ProgramManager/EditProgram/Delete.png"), tr("Delete page"));
    QAction *act_goup   = new QAction(QIcon(":/res/ProgramManager/EditProgram/GoUp.png"),   tr("Move up"));
    QAction *act_godown = new QAction(QIcon(":/res/ProgramManager/EditProgram/GoDown.png"), tr("Move down"));
    tb_page_list->setStyleSheet("padding-left:6px;");
 //   tb_page_list->addAction(spacer);
    tb_page_list->addAction(act_add);
    tb_page_list->addAction(act_copy);
    tb_page_list->addAction(act_del);
    tb_page_list->addAction(act_goup);
    tb_page_list->addAction(act_godown);

    m_wPageList = new QListWidget(this);
    m_wPageList->setProperty("ssType", "progEditor");
    m_wPageList->setProperty("ssName", "pageViewer");

    QVBoxLayout *playout = new QVBoxLayout();
    m_ProgramListLable=new QLabel(tr("program"));
    m_ProgramListLable->setStyleSheet("background-color:#A8A8A8");
    m_ProgramListLable->setAlignment(Qt::AlignCenter);
    playout->addWidget(m_ProgramListLable, 0);
    playout->addWidget(tb_page_list, 1);
    playout->addWidget(m_wPageList, 2);
    playout->setSpacing(0);
    playout->setContentsMargins(0, 0, 0, 0);
    setLayout(playout);

    connect(act_add,    SIGNAL(triggered(bool)), this, SLOT(onAdd()));
    connect(act_copy,   SIGNAL(triggered(bool)), this, SLOT(onCopy()));
    connect(act_del,    SIGNAL(triggered(bool)), this, SLOT(onDelete()));
    connect(act_goup,   SIGNAL(triggered(bool)), this, SLOT(onGoUp()));
    connect(act_godown, SIGNAL(triggered(bool)), this, SLOT(onGoDown()));
    connect(m_wPageList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)),
            this,        SLOT(onCurrentItemChanged(QListWidgetItem*, QListWidgetItem*)));

}
void wPageList::Init()
{
    if(load()<=0)
    {
        onAdd();
        save();
    }
}
int wPageList::load()
{
    QDir dRoot(m_strProgramItemPath);
    int iCount=0;
    if(dRoot.exists()) {
        QStringList name_list = dRoot.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
        QList<QJsonDocument> json_list;
        foreach(QString name, name_list) {
            QDir dir(m_strProgramItemPath + MACRO_FENGEFU + name);
            if(dir.exists("page.json")) {
                QFile fPro(dir.path() + MACRO_FENGEFU+"page.json");
                fPro.open(QIODevice::ReadOnly);
                json_list.push_back(QJsonDocument::fromJson(fPro.readAll()));
                iCount++;
                fPro.close();
            }
        }
        if(!json_list.isEmpty())
        {
            std::sort(json_list.begin(), json_list.end(), [](const QJsonDocument &a, const QJsonDocument &b)
            {
                return a["order"].toInt() < b["order"].toInt();
            });
            foreach(QJsonDocument json, json_list) {
                onRestore(json);
            }
        }
    }
    return iCount;
}
bool wPageList::IsChanged()
{
    //读取初始的文件所有page.json
    QDir dRoot(m_strProgramItemPath);
    int iCount=0;
    if(dRoot.exists()) {
        QStringList name_list = dRoot.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
        QList<QJsonDocument> json_list;
        foreach(QString name, name_list) {
            QDir dir(m_strProgramItemPath + MACRO_FENGEFU + name);
            if(dir.exists("page.json")) {
                QFile fPro(dir.path() + MACRO_FENGEFU+"page.json");
                fPro.open(QIODevice::ReadOnly);
                json_list.push_back(QJsonDocument::fromJson(fPro.readAll()));
                iCount++;
                fPro.close();
            }
        }
        //如果pagelist个数不同则提示保存
        if(iCount!= m_wPageList->count())
            return true;
        if(!json_list.isEmpty())
        {
            //把json_list按照order键排序
            std::sort(json_list.begin(), json_list.end(), [](const QJsonDocument &a, const QJsonDocument &b)
            {
                return a["order"].toInt() < b["order"].toInt();
            });
            //int itempIndex=0;
            for(int itempIndex=0;itempIndex<json_list.count();itempIndex++)
            {
                wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(itempIndex));
                if(item->IsChange(json_list[itempIndex]))
                    return true;
            }
        }
    }
        return false;
}

void wPageList::setRes(int w, int h)
{
    m_width = w;
    m_height = h;
    int n = m_wPageList->count();
    for(int i=0; i<n; i++) {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(i));
        item->setRes(w, h);
    }
}

void wPageList::keyReleaseEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Delete: onDelete(); break;
    default:break;
    }
}
//停止每个页面元素的播放，将节目目录下的每个页面的文件夹另命名
void wPageList::save0()
{
    //停止每个幻灯片的元素
    int n = m_wPageList->count();
    for(int i=0; i<n; i++) {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(i));
        item->stopElements();
    }
    QDir dRoot(m_strProgramItemPath);
    if(dRoot.exists())
    {
    }
    else
    {
       dRoot.mkdir(m_strProgramItemPath);//只创建一级子目录，即必须保证上级目录存在
    }

    QStringList list = dRoot.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    foreach(QString name, list) {
        dRoot.rename(name, name + PAGEDEL_SUFFIX);
    }
}
//保存每个页面的元素和页面属性到page.json文档
void wPageList::save1()
{
    int n = m_wPageList->count();
    for(int i=0; i<n; i++) {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(i));
        item->save(m_strProgramItemPath);
    }
}

void wPageList::save2()
{
    QDir dRoot(m_strProgramItemPath);
    QStringList filters;
    filters << "*" PAGEDEL_SUFFIX;
    QStringList list = dRoot.entryList(filters);
    foreach(QString name, list) {
        QDir dPage(m_strProgramItemPath + MACRO_FENGEFU + name);
        dPage.removeRecursively();
    }
    int n = m_wPageList->count();
    for(int i=0; i<n; i++) {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(i));
        item->playElements();
    }
}

void wPageList::save()
{
    save0();
    save1();
    save2();
}

void wPageList::saveAs()
{
    save0();
    save1();
    save2();
}

void wPageList::setting()
{
}

void wPageList::onRestore(const QJsonDocument &json)
{
    QString path = m_strProgramItemPath + MACRO_FENGEFU + json["name"].toString();
    wPageItem *item = new wPageItem(json, path, QSize(m_width, m_height));
    wPageItemWidget *w = item->wPage();
    m_wPageList->addItem(item);
    m_wPageList->setItemWidget(item, w);
}

void wPageList::onAdd()
{
    int order  = m_wPageList->count();
    int repeat = 1;

    QJsonObject   obj_root;
    QJsonObject   obj_date;
    QJsonArray    obj_plans;
    QJsonDocument json;
    QDateTime now = QDateTime::currentDateTime();
    QDate tmpdate;
    tmpdate = now.date();
    QString _tmpdate;
    _tmpdate = tmpdate.toString("yyyy-MM-dd");
    QDateTime end = now.addSecs(2678400);
    QDate tmpdateend;
    tmpdateend = end.date();
    QString _tmpdateend;
    _tmpdateend = tmpdateend.toString("yyyy-MM-dd");
 //   QString straa=QDate::currentDate().toString();
    obj_date["isValid"] = QJsonValue(false);
    obj_date["start"]   = QJsonValue(_tmpdate);
    obj_date["end"]     = QJsonValue(_tmpdateend);

    obj_root["name"]      = QJsonValue(genNewPageName());
    obj_root["order"]     = QJsonValue(order);
    obj_root["repeat"]    = QJsonValue(repeat);
    obj_root["validDate"] = obj_date;
    obj_root["plans"]     = obj_plans;

    json.setObject(obj_root);
    QString path = m_strProgramItemPath + MACRO_FENGEFU + json["name"].toString();
    wPageItem *item = new wPageItem(json, path, QSize(m_width, m_height));
    wPageItemWidget *w = item->wPage();
    m_wPageList->addItem(item);
    m_wPageList->setItemWidget(item, w);
    m_wPageList->setCurrentItem(item);
}

void wPageList::onCopy()
{
    if(m_wPageList->count() > 0) {
        wPageItem *cur = static_cast<wPageItem*>(m_wPageList->currentItem());
        cur->updateJson();
        wPageItem *item = cur->clone();
        QJsonDocument json  = item->jRoot();
        QJsonObject   oRoot = json.object();
        //复制创建一个新的pageitem
        oRoot["name"]  = QJsonValue(genNewPageName());
        oRoot["order"] = QJsonValue(m_wPageList->count());
        json.setObject(oRoot);
        item->setJRoot(json);

        wPageItemWidget *w = item->wPage();
        m_wPageList->addItem(item);
        m_wPageList->setItemWidget(item, w);
        m_wPageList->setCurrentItem(item);
    }
}

void wPageList::onDelete()
{
    if(m_wPageList->count() == 1)
    {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->currentItem());

        emit sigDeletePageItem(item);
        return;
    }
    if(m_wPageList->count() > 1) {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->currentItem());
        //m_wPageList->setCurrentRow(-1);
        X_UIMsgBoxOkCancel *dlg = new X_UIMsgBoxOkCancel(tr("Tip Info"),tr("Are you sure you want to delete this program page?"), this);
        if(dlg->exec() == QDialog::Accepted)
        {
            delete item;
            if(m_wPageList->count() > 0) {
                m_wPageList->setCurrentRow(0);
            }
            flashOrder();
        }
        else {

        }
    }
}

void wPageList::onGoUp()
{
    if(m_wPageList->count() > 1) {
        int index = m_wPageList->currentRow();
        if(index > 0) {
            wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(index));
            m_wPageList->takeItem(index);
            wPageItemWidget *w = item->wPage();
            m_wPageList->insertItem(index-1, item);
            m_wPageList->setItemWidget(item, w);
            m_wPageList->setCurrentRow(index-1);
        }
        flashOrder();
    }
}

void wPageList::onGoDown()
{
    if(m_wPageList->count() > 1) {
        int index = m_wPageList->currentRow();
        if(index < (m_wPageList->count()-1)) {
            wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(index));
            m_wPageList->takeItem(index);
            wPageItemWidget *w = item->wPage();
            m_wPageList->insertItem(index+1, item);
            m_wPageList->setItemWidget(item, w);
            m_wPageList->setCurrentRow(index+1);
        }
        flashOrder();
    }
}

void wPageList::onCurrentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    wPageItem *curItem = static_cast<wPageItem*>(current);
    wPageItem *preItem = static_cast<wPageItem*>(previous);
    if(nullptr != preItem) {
        preItem->scene()->clearSelection();
    }
    emit sigPageSelected(curItem);
}

QString wPageList::genNewPageName()
{
    //return tr("New") + QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz");
    return QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz");
}

void wPageList::flashOrder()
{
    int n = m_wPageList->count();
    for(int i=0; i<n; i++) {
        wPageItem *item = static_cast<wPageItem*>(m_wPageList->item(i));
        QJsonDocument jRoot = item->jRoot();
        QJsonObject obj_root = jRoot.object();
        obj_root["order"] = QJsonValue(i);
        jRoot.setObject(obj_root);
        item->setJRoot(jRoot);
    }
}
