#include "database.h"
#include "utils.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDate>
#include <QFile>
#include <QRect>
#include <QStandardPaths>
#include <QDebug>
#include <DatabaseSql.h>

DataBase::DataBase(QObject *parent) : QObject(parent), idleItemId(0)
{
    if (!QSqlDatabase::drivers().contains("QSQLITE")) {
        qWarning() << "Unable to load database, this demo needs the SQLITE3 driver ! ! !";
    }
    if (QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).count() <= 0) {
        qWarning() << "The directory containing the configuration file was not found ! ! !";
    }
    if (!QFile::exists(QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)[0] + "/ukui/panel.conf")) {
        qWarning() << "There are no /ukui/panel.conf in the directory ! ! !";
    }
    QString dbPath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation)[0] + "/ukui/appList.db";

    // 创建一个数据库连接，指定数据库驱动
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);
}

DataBase::~DataBase()
{
    db.close();
}

bool DataBase::openDatabase()
{
    if (!db.open()) {
        qDebug() << db.lastError().text();
        return false;
    }
    if (!checkTables()) {
        return false;
    }
    qDebug() << "DataBase Tables: " << db.tables();
    return true;
}

void DataBase::createItemsData()
{
    QString desktopName("widgetPlugin1");
    QString sql = SELECT_ITEMLIST_BY_DESKTOPNAME;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":desktopName", desktopName);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return;
    }
    while(sqlQuery.next()) {
        quint32 id = 0;
        id = sqlQuery.value(0).toUInt();
        if(id > 0) {
            return;
        }
    }
    addItem(0, QLatin1String("taskbar"), "taskbar", "null", 3, {1, 1});
}

bool DataBase::isTableExist(const QString &tableName)
{
    if (db.tables().contains(tableName, Qt::CaseInsensitive)) {
        return true;
    } else {
        return false;
    }
}

quint32 DataBase::getIdleItemID()
{
    idleItemId = 0;
    QVector<quint32> itemIdList;
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(SELECT_ITEMLIST)) {
        qWarning() << __func__ << sqlQuery.lastError();
    } else {
        while (sqlQuery.next()) {
            quint32 itemId = sqlQuery.value(1).toUInt();
            itemIdList.append(itemId);
        }
    }
    qSort(itemIdList);
    for (int var = 0; var < itemIdList.size(); ++var) {
        if (itemIdList[var] != var) {
            idleItemId = var;
            break;
        }
    }
    if (!idleItemId) {
        idleItemId = itemIdList.size();
    }
    qDebug() << "idleItemId =" << idleItemId;
    return idleItemId;
}

QMap<quint32, UKUI::BaseItem *> DataBase::queryAllItemData()
{
    QMap<quint32, UKUI::BaseItem *> itemList;
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(SELECT_ITEMLIST)) {
        qWarning() << __func__ << sqlQuery.lastError();
        return itemList;
    } else {
        while(sqlQuery.next()) {
            quint32 id = sqlQuery.value(1).toUInt();
            QString desktopName = sqlQuery.value(2).toString();
            QString name = sqlQuery.value(3).toString();
            QString iconName = sqlQuery.value(4).toString();
            int type = sqlQuery.value(5).toInt();
            QStringList list = sqlQuery.value(6).toString().split(',');
            QString x_placeholder = list.at(0);
            QString y_placeholder = list.at(1);
            QList<int> placeHolder = {x_placeholder.toInt(), y_placeholder.toInt()};

            QStringList categories = sqlQuery.value(7).toString().split(',');
            QList<int> category_list;
            foreach (auto category, categories) {
                category_list.append(category.toInt());
            }
//            qDebug() << QString("desktopName:%1    name:%2    id:%3    iconName:%4    type:%5").arg(desktopName).arg(name).arg(id).arg(iconName).arg(type)
//                     << "placeHolder:" << placeHolder;
//            QString absoluteIconName = getAbsoluteIconPath(iconName);

            if (id < 0 || desktopName.length() <= 0 || name.length() <= 0 || iconName.length() <= 0||
                    type <= 0 || x_placeholder <= 0 || y_placeholder <= 0 || category_list.length() <= 0) {
                qDebug() << "The DataBase data read from itemlist is not in the correct format."
                            " It may have been accidentally tampered with!!" << endl;
                if (!deleteBadItemListData(sqlQuery.value(0).toUInt())) {
                    qWarning() << "从列表中删除应用失败" << __func__;
                }
                updatePageItem();
                updateSetItem();
            }

            switch (type) {
            case DataBase::Icon:
                itemList[id] = new UKUI::IconItem(desktopName, name, id, iconName, category_list);
                break;
            case DataBase::Group:
                itemList[id] = new UKUI::GroupItem(name, id);
                break;
            case DataBase::Container:
                itemList[id] = new UKUI::ContainerItem(name, id, placeHolder);
                break;
            case DataBase::Widget:
                itemList[id] = new UKUI::Widget(desktopName, name, id, placeHolder);
                break;
            default:
                break;
            }
        }
    }
    return itemList;
}

QMap<quint32, QList<QList<quint32>>> DataBase::queryAllFlipSetData()
{
    bool findDeletedItemBelongPage = false;
    QMap<quint32, QList<QList<quint32>>> allSets;
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(SELECT_SETS)) {
        qWarning() << __func__ << sqlQuery.lastError();
        return allSets;
    } else {
        while(sqlQuery.next()) {
            if (sqlQuery.value(3).toInt() == 0) {
                int setId = sqlQuery.value(1).toInt();
                QStringList sequence = sqlQuery.value(2).toString().split(';');

                for (int i = 0; i < sequence.size(); ++i) {
                    QStringList setPageItem = sequence.at(i).split(",");
                    QList<quint32> itemList;
                    for (int j = 0; j < setPageItem.size(); ++j) {
                        if(queryItemIdFromList(setPageItem.at(j).toUInt())) {
                            itemList.append(setPageItem.at(j).toUInt());
                        } else {
                            findDeletedItemBelongPage = true;
                        }
                    }
                    allSets[setId].append(itemList);
                    if (findDeletedItemBelongPage) {
                        findDeletedItemBelongPage = false;
                        if (!setFlipSetData(setId, allSets[setId])) {
                            qWarning() << __func__ << "设置flipset数据失败";
                            return {{}};
                        }
                    }
                }
            }
        }
    }
    //    qDebug() << __func__ << "Sets:" << allSets;
    return allSets;
}

QMap<quint32, QList<quint32>> DataBase::queryAllScrollSetData()
{
    bool findDeletedItemBelongPage = false;
    QMap<quint32, QList<quint32>> allSets;
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(SELECT_SETS)) {
        qWarning() << __func__ << sqlQuery.lastError();
        return allSets;
    } else {
        while (sqlQuery.next()) {
            if (sqlQuery.value(3).toInt() == 1) {
                int setId = sqlQuery.value(1).toInt();
                QString sequence = sqlQuery.value(2).toString();
                if (sequence.isEmpty()) {
                    allSets[setId];
                    continue;
                } else {
                    QStringList setAllItem = sequence.split(",");
                    foreach (auto item, setAllItem) {
                        if (queryItemIdFromList(item.toUInt())) {
                            allSets[setId].append(item.toUInt());
                        } else{
                            findDeletedItemBelongPage = true;
                        }
                    }
                    if (findDeletedItemBelongPage) {
                        findDeletedItemBelongPage = false;
                        if (!setScrollSetData(setId,allSets[setId])) {
                            qWarning() << __func__ << "设置scrollset数据失败";
                            return {{}};
                        }
                    }
                }
            }
        }
    }
    return allSets;
}

QMap<quint32, QList<quint32>> DataBase::queryAllPageData()
{
    bool findDeletedItemBelongPage = false;
    QMap<quint32, QList<quint32>> allPage;
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(SELECT_PAGE)) {
        qWarning() << __func__ << sqlQuery.lastError();
        return allPage;
    } else {
        while (sqlQuery.next()) {
            int pageId = sqlQuery.value(1).toInt();
            QStringList sequence = sqlQuery.value(2).toString().split(',');
            for (int i = 0; i < sequence.size(); ++i) {
                QString itemId = sequence.at(i);
                if (queryItemIdFromList(itemId.toUInt())) {
                    allPage[pageId].append(itemId.toUInt());
                } else {
                    findDeletedItemBelongPage = true;
                }
            }
            if (findDeletedItemBelongPage) {
                findDeletedItemBelongPage = false;
                if (!setPageData(pageId,allPage[pageId])) {
                    qWarning() << __func__ << "设置page数据失败";
                    return {{}};
                }
            }
        }
    }
    //    qDebug() << __func__ << "Page:" << allPage;
    return allPage;
}

void DataBase::queryItemDataFromID(int id)
{
    QString sql = SELECT_ITEMLIST_BY_ID;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":id", id);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return;
    }
    while (sqlQuery.next()) {
        QString desktopName = sqlQuery.value(2).toString();
        QString name = sqlQuery.value(3).toString();
        QString iconName = sqlQuery.value(4).toString();
        int type = sqlQuery.value(5).toInt();
        int parent_id = sqlQuery.value(10).toInt();
        int page = sqlQuery.value(11).toInt();
        QRect geometry = QRect(sqlQuery.value(6).toInt(), sqlQuery.value(7).toInt(), sqlQuery.value(8).toInt(), sqlQuery.value(9).toInt());
        qDebug() << endl << QString("id:%1    name:%2    type:%3    parent_id:%4    page:%5    desktopName:%6    iconName:%7").arg(id).arg(name).arg(type).arg(parent_id).arg(page).arg(desktopName).arg(iconName)
                 << "    geometry =" << geometry << endl;
    }
}

QList<quint32> DataBase::querySetDataFromID(int setId)
{
    QList<quint32> itemList;
    QString sql = SELECT_SETS_BY_SETID;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":setId", setId);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return itemList;
    }
    while (sqlQuery.next()) {
        QStringList itemListStr = sqlQuery.value(2).toString().split(',');
        if (itemListStr.size() == 1 && itemListStr.at(0).isEmpty()) {
            return itemList;
        }
        for (int i = 0; i < itemListStr.size(); i++) {
            itemList.append(static_cast<QString>(itemListStr.at(i)).toUInt());
        }
        return itemList;
    }
    return itemList;
}

QList<quint32> DataBase::queryPageDataFromID(int pageId)
{
    QList<quint32> itemList;
    QString sql = SELECT_PAGE_BY_PAGEID;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":pageId", pageId);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return itemList;
    }
    while (sqlQuery.next()) {
        QStringList itemListStr = sqlQuery.value(2).toString().split(',');
        if (itemListStr.size() == 1 && itemListStr.at(0).isEmpty()) {
            return itemList;
        }
        for (int i = 0; i < itemListStr.size(); i++) {
            itemList.append(static_cast<QString>(itemListStr.at(i)).toUInt());
        }
        return itemList;
    }
    return itemList;
}

quint32 DataBase::queryIdFromDesktopName(QString desktopName)
{
    QString sql = SELECT_ITEMLIST_BY_DESKTOPNAME;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":desktopName", desktopName);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return 0;
    }
    while (sqlQuery.next()) {
        quint32 id = sqlQuery.value(1).toUInt();
        //        qDebug() << __func__ << "id =" << id;
        return id;
    }
    return 0;
}

QVariant DataBase::addItem(quint32 itemId, const QString &desktopName, const QString &name, const QString &iconName, const QVariant &type,
                                    const QList<quint32> &_placeholder, const QList<int> &_categories)
{
    QString placeholder = UKUI::fromQListUIntToString(_placeholder);
    QString categories = UKUI::fromQListIntToString(_categories);
    QSqlQuery sqlQuery;
    if (!sqlQuery.prepare(QLatin1String(INSERT_ITEMLIST))) {
        qWarning() << __func__ << sqlQuery.lastError().text();
        return QVariant();
    }
    sqlQuery.addBindValue(itemId);
    sqlQuery.addBindValue(desktopName);
    sqlQuery.addBindValue(name);
    sqlQuery.addBindValue(iconName);
    sqlQuery.addBindValue(type);
    sqlQuery.addBindValue(placeholder);
    sqlQuery.addBindValue(categories);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
    }
    return sqlQuery.lastInsertId();
}

bool DataBase::modifyItemData(quint32 id, const QString &desktopName, const QString &name, const QString &iconName, const QList<int> &_categories)
{
    QString categories = UKUI::fromQListIntToString(_categories);
    QSqlQuery sqlQuery;
    sqlQuery.prepare(UPDATE_ITEMLIST);
    sqlQuery.addBindValue(desktopName);
    sqlQuery.addBindValue(name);
    sqlQuery.addBindValue(iconName);
    sqlQuery.addBindValue(categories);
    sqlQuery.addBindValue(id);
    if (!sqlQuery.exec()) {
        qWarning() << "修改应用的数据失败" << __func__ << sqlQuery.lastError();
        return false;
    }
    return true;
}

QVariant DataBase::addFlipSet(quint32 setId, const QList<QList<quint32>> &sequence)
{
    QString itemSequence;
    if(!sequence.isEmpty()) {
        itemSequence += UKUI::fromQListUIntToString(sequence.first());
        for(int i = 1; i < sequence.size(); i++) {
            QList<quint32> setPageItemSeq = sequence.at(i);
            itemSequence += QString(";") += UKUI::fromQListUIntToString(setPageItemSeq);
        }
    }
    qDebug() << __func__ << itemSequence;

    QSqlQuery sqlQuery;
    if (!sqlQuery.prepare(QLatin1String(INSERT_SETS))) {
        qWarning() << __func__ << sqlQuery.lastError().text();
        return QVariant();
    }
    sqlQuery.addBindValue(setId);
    sqlQuery.addBindValue(itemSequence);
    sqlQuery.addBindValue(0);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return QVariant();
    }
    return sqlQuery.lastInsertId();
}

QVariant DataBase::addScrollSet(quint32 setId, const QList<quint32> &sequence)
{
    QString itemSequence;
    if (!sequence.isEmpty()) {
        itemSequence = UKUI::fromQListUIntToString(sequence);
    }
    QSqlQuery sqlQuery;
    if (!sqlQuery.prepare(QLatin1String(INSERT_SETS))) {
        qWarning() << __func__ << sqlQuery.lastError().text();
    }
    sqlQuery.addBindValue(setId);
    sqlQuery.addBindValue(itemSequence);
    sqlQuery.addBindValue(1);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
    }
    return sqlQuery.lastInsertId();
}

bool DataBase::setFlipSetData(quint32 setId, const QList<QList<quint32>> &sequence)
{
    QString itemSequence;
    if(!sequence.isEmpty()) {
        itemSequence += UKUI::fromQListUIntToString(sequence.first());
        for(int i = 1; i < sequence.size(); i++) {
            QList<quint32> setPageItemSeq = sequence.at(i);
            itemSequence += QString(";") += UKUI::fromQListUIntToString(setPageItemSeq);
        }
    }
    qDebug() << __func__ << "itemSequence:" << itemSequence;

    QSqlQuery sqlQuery;
    sqlQuery.prepare(UPDATE_SETS);
    sqlQuery.addBindValue(itemSequence);
    sqlQuery.addBindValue(setId);
    if (!sqlQuery.exec()) {
        qWarning() << "修改flipsets数据失败" << __func__ << __LINE__ << sqlQuery.lastError();
        return false;
    }
    return true;
}

bool DataBase::setScrollSetData(quint32 setId, const QList<quint32> &sequence)
{
    QString itemSequence;
    if(!sequence.isEmpty())
        itemSequence = UKUI::fromQListUIntToString(sequence);
    qDebug() << __func__ << itemSequence << setId;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(UPDATE_SETS);
    sqlQuery.addBindValue(itemSequence);
    sqlQuery.addBindValue(setId);
    if (!sqlQuery.exec()) {
        qWarning() << "修改scrollsets数据失败" << __func__ << __LINE__ << sqlQuery.lastError();
        return false;
    }
    return true;
}

bool DataBase::modifySetName(quint32 setId, QString name)
{
    if(name.isEmpty())
        return false;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(UPDATE_ITEMLIST_NAME_ITEMID);
    sqlQuery.addBindValue(name);
    sqlQuery.addBindValue(setId);
    if(!sqlQuery.exec()) {
        qDebug() << sqlQuery.lastError();
        return false;
    }
    return true;
}

bool DataBase::addPage(quint32 pageId, const QList<quint32> &sequence)
{
    QString itemSequence = UKUI::fromQListUIntToString(sequence);
    QSqlQuery sqlQuery;
    if (!sqlQuery.prepare(QLatin1String(INSERT_PAGE))) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    sqlQuery.addBindValue(pageId);
    sqlQuery.addBindValue(itemSequence);
    if (!sqlQuery.exec()) {
        qWarning() << "数据库中添加 page 数据失败" << __func__ << sqlQuery.lastError();
        return false;
    }
    return true;
}

bool DataBase::setPageData(quint32 pageId, const QList<quint32> &sequence)
{
    QString itemSequence = UKUI::fromQListUIntToString(sequence);
    qDebug() << __func__ << itemSequence << pageId;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(UPDATE_PAGE);
    sqlQuery.addBindValue(itemSequence);
    sqlQuery.addBindValue(pageId);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << __LINE__ << sqlQuery.lastError();
        return false;
    }
    return true;
}

bool DataBase::deleteItemListData(int id)
{
    if (isTableExist("itemlist")) {
        QSqlQuery sqlQuery;
        if (!sqlQuery.exec(QString(DELETE_ITEMLIST_BY_ITEMID).arg(id))) {
            qWarning() << "从列表中删除应用失败" << __func__ << sqlQuery.lastError();
            return false;
        }
        qDebug() << "Delete ItemList Data success ! ! !" << "Id:" << id;
    }
    return true;
}

bool DataBase::deletePageData(int id)
{
    if (id < 0) {
        qDebug() << __func__ << "param id error" << id;
        return false;
    }
    if (!isTableExist("page")) {
        qDebug() << __func__ << "page table is not exits";
        return false;
    }
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(QString(DELETE_PAGE_BY_PAGEID).arg(id))) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    qDebug() << "Delete Page Data success ! ! !" << "PageId:" << id;
    return true;
}

bool DataBase::queryItemIdFromList(int itemId)
{
    QString sql = SELECT_ITEMLIST_BY_ITEMID;
    QSqlQuery sqlQuery;
    sqlQuery.prepare(sql);
    sqlQuery.bindValue(":itemId", itemId);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << __LINE__ << sqlQuery.lastError();
        return false;
    }
    if (!sqlQuery.last()) {
        qDebug()<<"lili____sqlQuery.last()"<<sqlQuery.last()<<itemId;
        return false;
    }
    return true;
}

bool DataBase::updatePageItem()
{
    bool findDeletedItemBelongPage = false;
    QMap<quint32, QList<quint32>> allPage;
    QSqlQuery sqlQuery;
    sqlQuery.exec(SELECT_PAGE);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    while (sqlQuery.next()) {
        int pageId = sqlQuery.value(1).toInt();
        QStringList sequence = sqlQuery.value(2).toString().split(',');
        for (int i = 0; i < sequence.size(); ++i) {
            QString itemId = sequence.at(i);
            if (queryItemIdFromList(itemId.toUInt())) {
                allPage[pageId].append(itemId.toUInt());
            } else {
                findDeletedItemBelongPage = true;
            }
        }

        if (findDeletedItemBelongPage) {
            findDeletedItemBelongPage = false;
            if (!setPageData(pageId,allPage[pageId])) {
                qWarning() << __func__ << "修改page页数据失败";
                return false;
            }
        }
    }
    return true;
}

bool DataBase::updateSetItem()
{
    bool findDeletedItemBelongPage = false;
    QMap<quint32, QList<QList<quint32>>> allFilpSets;
    QMap<quint32, QList<quint32>> allScrollSets;
    QSqlQuery sqlQuery;
    sqlQuery.exec(SELECT_SETS);
    if (!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    while(sqlQuery.next()) {
        if (sqlQuery.value(3).toInt() == 0) {
            int setId = sqlQuery.value(1).toInt();
            QStringList sequence = sqlQuery.value(2).toString().split(';');
            for (int i = 0; i < sequence.size(); ++i) {
                QStringList setPageItem = sequence.at(i).split(",");
                QList<quint32> itemList;
                for (int j = 0; j < setPageItem.size(); ++j) {
                    if(queryItemIdFromList(setPageItem.at(j).toUInt())) {
                        itemList.append(setPageItem.at(j).toUInt());
                    } else {
                        findDeletedItemBelongPage = true;
                    }
                }
                allFilpSets[setId].append(itemList);
                if (findDeletedItemBelongPage) {
                    findDeletedItemBelongPage = false;
                    if (!setFlipSetData(setId,allFilpSets[setId])) {
                        qWarning() << __func__ << "修改flipset数据失败";
                        return false;
                    }
                }
            }
        } else if(sqlQuery.value(3).toInt() == 1) {
            int setId = sqlQuery.value(1).toInt();
            QString sequence = sqlQuery.value(2).toString();
            if (sequence.isEmpty()) {
                allScrollSets[setId];
                continue;
            } else {
                QStringList setAllItem = sequence.split(",");
                foreach (auto item, setAllItem) {
                    if (queryItemIdFromList(item.toUInt())) {
                        allScrollSets[setId].append(item.toUInt());
                    } else {
                        findDeletedItemBelongPage = true;
                    }
                }
                if (findDeletedItemBelongPage) {
                    findDeletedItemBelongPage = false;
                    if (!setScrollSetData(setId,allScrollSets[setId])) {
                        qWarning() << __func__ << "修改scrollset数据失败";
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

bool DataBase::deleteSetIdFromPage()
{
    bool findDeletedItemBelongPage = false;
    QMap<quint32, QList<quint32>> allPage;
    QSqlQuery sqlQuery;
    sqlQuery.exec(SELECT_PAGE);
    if(!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    while(sqlQuery.next()) {
        int pageId = sqlQuery.value(1).toInt();
        QStringList sequence = sqlQuery.value(2).toString().split(',');
        for (int i = 0; i < sequence.size(); ++i) {
            QString itemId = sequence.at(i);
            if(!queryPageItemIdFromSet(itemId.toUInt())) {
                allPage[pageId].append(itemId.toUInt());
            } else{
                findDeletedItemBelongPage = true;
            }
        }

        if (findDeletedItemBelongPage) {
            findDeletedItemBelongPage = false;
            if (!setPageData(pageId,allPage[pageId])) {
                qWarning() << __func__ << "修改page数据失败";
                return false;
            }
            qDebug() << __func__ << sequence;
        }
    }
    return true;
}

bool DataBase::queryPageItemIdFromSet(int itemId)
{
    QSqlQuery sqlQuery;
    sqlQuery.exec(SELECT_SETS);
    if(!sqlQuery.exec()) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    while(sqlQuery.next()) {
        if (sqlQuery.value(3).toInt() == 0) {
            QStringList flipSet = sqlQuery.value(2).toString().split(';');
            for (int i = 0; i < flipSet.size(); ++i) {
                QStringList setPageItem = flipSet.at(i).split(",");
                for (int j = 0; j < setPageItem.size(); ++j) {
                    if (setPageItem.at(j) == itemId) {
                        return true;
                    }
                }
            }
        }
        else if(sqlQuery.value(3).toInt() == 1) {
            QStringList scrollSet = sqlQuery.value(2).toString().split(",");
            for (int i = 0; i < scrollSet.size(); ++i) {
                QStringList setPageItem = scrollSet.at(i).split(",");
                for (int j = 0; j < setPageItem.size(); ++j) {
                    if (setPageItem.at(j) == itemId) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

bool DataBase::deleteBadItemListData(int itemId)
{
    if (!isTableExist("itemlist")) {
        qDebug() << "itemlist table is not exits" << __func__;
        return false;
    }
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(QString(DELETE_ITEMLIST_BY_ID).arg(itemId))) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    qDebug() << "Delete ItemList Data success ! ! !" << "Id:" << itemId;
    return true;
}

bool DataBase::deleteSetsData(int id)
{
    if (!isTableExist("sets")) {
        qDebug() << "sets table is not exits" << __func__;
        return false;
    }
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(QString(DELETE_SETS_BY_SETID).arg(id))) {
        qWarning() << __func__ << sqlQuery.lastError();
        return false;
    }
    qDebug() << "Delete Sets Data success ! ! !" << id;
    return true;
}

void DataBase::deleteTable(const QString &tableName)
{
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(QString(DROP_TABLE_BY_TABLENAME).arg(tableName))) {
       qWarning() << __func__ << sqlQuery.lastError();
       return;
    }
    qDebug() << "Delete Table success ! ! !";
}

bool DataBase::deleteTableAllData(const QString &tableName)
{
    if (!isTableExist(tableName)) {
        return false;
    }
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(QString(DELETE_TABLEDATA_BY_TABLENAME).arg(tableName))) {
        qDebug() << sqlQuery.lastError();
        return false;
    }
    qDebug() << "Delete Table All Data success ! ! !";
    return true;
}

bool DataBase::checkTables()
{
    QSqlQuery sqlQuery;
    if (!isTableExist("itemlist")) {
        firstInit = true;
        if (!sqlQuery.exec(QLatin1String(CREATE_TABLE_ITEMLIST))) {
            qWarning() << __func__ << sqlQuery.lastError().text();
            return false;
        }
        createItemsData();

        if (!isTableExist("sets")) {
            if (!sqlQuery.exec(QLatin1String(CREATE_TABLE_SETS))) {
                qWarning() << __func__ << sqlQuery.lastError().text();
                return false;
            }
        } else {
            if (!deleteTableAllData("sets")) {
                qWarning() << __func__ << "删除set表数据失败";
                return false;
            }
        }

        if (!isTableExist("page")) {
            if (!sqlQuery.exec(QLatin1String(CREATE_TABLE_PAGE))) {
                qWarning() << __func__ << sqlQuery.lastError().text();
                return false;
            }
        } else {
            if (!deleteTableAllData("page") ) {
                qWarning() << __func__ << "删除page表数据失败";
                return false;
            }
        }
    } else {
        if (isTableExist("sets") && isTableExist("page")) {
            return true;
        } else {
            qDebug() << isTableExist("sets") << isTableExist("page");
            if (!isTableExist("sets")) {
                if (!sqlQuery.exec(QLatin1String(CREATE_TABLE_SETS))) {
                    qWarning() << __func__ << sqlQuery.lastError().text();
                    return false;
                }
            } else {
                if (!deleteTableAllData("sets")) {
                    qWarning() << __func__ << "删除set表数据失败";
                    return false;
                }
            }

            if (!isTableExist("page")) {
                firstInit = true;
                if (!sqlQuery.exec(QLatin1String(CREATE_TABLE_PAGE))) {
                    qWarning() << __func__ << sqlQuery.lastError().text();
                    return false;
                }
            } else {
                if (!deleteTableAllData("page") ) {
                    qWarning() << __func__ << "删除page表数据失败";
                    return false;
                }
            }
        }
    }
    return true;
}

bool DataBase::checkTablesData()
{
    if (!isTableExist("itemlist") || !isTableExist("sets") || !isTableExist("page")) {
        qWarning() << __func__ << "表不存在";
        return true;
    }
    if (!updateSetItem()) {
        qWarning() << __func__ << "删除set中不存在于itemlist的id失败";
        return false;
    }
    if (!updatePageItem()) {
        qWarning() << __func__ << "删除page失败";
        return false;
    }
    if (!deleteSetIdFromPage()) {
        qWarning() << __func__ << "删除page中不存在于set的id失败";
        return false;
    }
    return true;
}

bool DataBase::getFirstInit()
{
    return firstInit;
}

void DataBase::closeDataBase()
{
    db.close();
}
