#include "dpConfigurationDialog.h"
#include "ui_dpConfigurationDialog.h"
#include "dataPanel.h"
#include "global.h"
#include <QStandardItemModel>
#include <QRegularExpressionValidator>
#include <QTimer>

dpConfigurationDialog::dpConfigurationDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::dpConfigurationDialog)
    , m_curActiveTab(nullptr)
    , m_pDataPanel(nullptr)
    , m_pModel_typeSource(nullptr)
    , m_pModel_typeSelected(nullptr)
    , m_pModel_dataSource(nullptr)
    , m_pModel_dataSelected(nullptr)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus);
    setAttribute(Qt::WA_TranslucentBackground);

    initialize();
}

dpConfigurationDialog::~dpConfigurationDialog()
{
    delete ui;
}

void dpConfigurationDialog::showEvent(QShowEvent* event)
{
    //ui->stackedWidget->setCurrentIndex(0);
    ui->tabDataType->click();
    if(m_pModel_typeSelected && m_pModel_typeSelected->rowCount() == 0)
    {
        ui->errorTip->setVisible(true);
        ui->errorTip->setToolTip(QString::fromStdWString(L"要至少选择一个数据类型"));
        ui->btnConfirm->setEnabled(false);
    }
    else
    {
        ui->errorTip->setVisible(false);
        //ui->errorTip->setToolTip(QString::fromStdWString(L"要至少选择一个数据类型"));
        ui->btnConfirm->setEnabled(true);
    }
}

void dpConfigurationDialog::initialize()
{
    ui->tabDataType->setProperty("index", 0);
    connect(ui->tabDataType, SIGNAL(clicked()), this, SLOT(onBtnClicked_tabBtn()));
    ui->tabDataSource->setProperty("index", 1);
    connect(ui->tabDataSource, SIGNAL(clicked()), this, SLOT(onBtnClicked_tabBtn()));
    ui->tabDisplaySetting->setProperty("index", 2);
    connect(ui->tabDisplaySetting, SIGNAL(clicked()), this, SLOT(onBtnClicked_tabBtn()));
    m_curActiveTab = ui->tabDataType;

    ui->stackedWidget->setCurrentIndex(0);

    connect(ui->btnConfirm, SIGNAL(clicked()), this, SLOT(onBtnClicked_confirm()));
    connect(ui->btnCancle, SIGNAL(clicked()), this, SLOT(onBtnClicked_cancle()));

    connect(ui->btnReomve_type, SIGNAL(clicked()), this, SLOT(onBtnClicked_remove_type()));
    connect(ui->btnReomve_source, SIGNAL(clicked()), this, SLOT(onBtnClicked_remove_source()));

    connect(ui->typeSourceList, &QListView::clicked, this, &dpConfigurationDialog::onItemClicked_typeSource);
    connect(ui->dataSourceList, &QListView::clicked, this, &dpConfigurationDialog::onItemClicked_dataSource);

    ///数据类型
    //typeSourceList
    m_pModel_typeSource = new QStandardItemModel(this);
    ui->typeSourceList->setModel(m_pModel_typeSource);
    /*QStringList typeSourceTextList;
    typeSourceTextList << QString::fromStdWString(L"电压") << QString::fromStdWString(L"电流") << QString::fromStdWString(L"功率");
    for(QString& text: typeSourceTextList)
    {
        QStandardItem* item = new QStandardItem(text);
        item->setEditable(false); //不可编辑
        m_pModel_typeSource->appendRow(item);
    }*/
    QStandardItem* item = new QStandardItem(QString::fromStdWString(L"电压"));
    item->setData(RealTimeDataType::voltage, Qt::UserRole + itemRole_dataType);
    item->setEditable(false); //不可编辑
    m_pModel_typeSource->appendRow(item);
    item = new QStandardItem(QString::fromStdWString(L"电流"));
    item->setData(RealTimeDataType::current, Qt::UserRole + itemRole_dataType);
    item->setEditable(false); //不可编辑
    m_pModel_typeSource->appendRow(item);
    item = new QStandardItem(QString::fromStdWString(L"功率"));
    item->setData(RealTimeDataType::power, Qt::UserRole + itemRole_dataType);
    item->setEditable(false); //不可编辑
    m_pModel_typeSource->appendRow(item);
    //typeSelectedList
    ui->typeSelectedList->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_pModel_typeSelected = new QStandardItemModel(this);
    ui->typeSelectedList->setModel(m_pModel_typeSelected);

    ///数据源
    //dataSourceList
    m_pModel_dataSource = new QStandardItemModel(this);
    ui->dataSourceList->setModel(m_pModel_dataSource);
    createDataSourceList();
    //sourceSelectedList
    ui->dataSelectedList->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_pModel_dataSelected = new QStandardItemModel(this);
    ui->dataSelectedList->setModel(m_pModel_dataSelected);

    ///数据配置
    QRegularExpression regExp_ip("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}"
                                 "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    QRegularExpressionValidator* validator_ip = new QRegularExpressionValidator(regExp_ip, this);
    ui->serviceIP->setValidator(validator_ip);
    QRegularExpression regExp_port("^(?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$");
    QRegularExpressionValidator* validator_port = new QRegularExpressionValidator(regExp_port, this);
    ui->servicePort->setValidator(validator_port);
}

void dpConfigurationDialog::copyModelData(QStandardItemModel* sourceModel, QStandardItemModel* destModel)
{
    if(!sourceModel || !destModel)
        return;

    for(int row = 0; row < destModel->rowCount(); row++)
    {
        for(int col = 0; col < destModel->columnCount(); col++)
        {
            QStandardItem* item = destModel->item(row, col);
            if(item)
                delete item;
        }
    }
    destModel->clear(); //只做clear不会释放其中的item

    for(int row = 0; row < sourceModel->rowCount(); row++)
    {
        QList<QStandardItem*> itemList;
        for(int col = 0; col < sourceModel->columnCount(); col++)
        {
            QStandardItem* item = sourceModel->item(row, col);
            if(item)
            {
                QStandardItem* newItem = new QStandardItem(item->text());
                itemList.push_back(newItem);
            }
        }
        destModel->appendRow(itemList);
    }
}

void dpConfigurationDialog::createDataSourceList()
{
    //demo先临时写死，后续改为接口动态创建
    QStandardItem* rootItem = m_pModel_dataSource->invisibleRootItem();
    QStandardItem* stationItem = new QStandardItem("测试站");
    stationItem->setEditable(false);
    stationItem->setData("station", Qt::UserRole + itemRole_tag);
    rootItem->appendRow(stationItem);
    QStandardItem* componentItem = new QStandardItem("异步电机");
    componentItem->setEditable(false);
    componentItem->setData("component", Qt::UserRole + itemRole_tag);
    stationItem->appendRow(componentItem);
    QStandardItem* currentItem = new QStandardItem("电流");
    currentItem->setEditable(false);
    currentItem->setData("current", Qt::UserRole + itemRole_tag);
    currentItem->setData(0, Qt::UserRole + itemRole_stationID);
    currentItem->setData(0, Qt::UserRole + itemRole_componentID);
    currentItem->setData(0, Qt::UserRole + itemRole_pointID);
    currentItem->setData(RealTimeDataType::current, Qt::UserRole + itemRole_dataType);
    componentItem->appendRow(currentItem);
    QStandardItem* voltageItem = new QStandardItem("电压");
    voltageItem->setEditable(false);
    voltageItem->setData("voltage", Qt::UserRole + itemRole_tag);
    voltageItem->setData(0, Qt::UserRole + itemRole_stationID);
    voltageItem->setData(0, Qt::UserRole + itemRole_componentID);
    voltageItem->setData(1, Qt::UserRole + itemRole_pointID);
    voltageItem->setData(RealTimeDataType::voltage, Qt::UserRole + itemRole_dataType);
    componentItem->appendRow(voltageItem);
    QStandardItem* powerItem = new QStandardItem("功率");
    powerItem->setEditable(false);
    powerItem->setData("power", Qt::UserRole + itemRole_tag);
    powerItem->setData(0, Qt::UserRole + itemRole_stationID);
    powerItem->setData(0, Qt::UserRole + itemRole_componentID);
    powerItem->setData(2, Qt::UserRole + itemRole_pointID);
    powerItem->setData(RealTimeDataType::voltage, Qt::UserRole + itemRole_dataType);
    componentItem->appendRow(powerItem);
    ui->dataSourceList->expandAll();
}

void dpConfigurationDialog::setPanel(DataPanel* pPanel)
{
    m_pDataPanel = pPanel;
    copyModelData(pPanel->m_cofigurationResults.m_pModel_dataType, m_pModel_typeSelected);
    copyModelData(pPanel->m_cofigurationResults.m_pModel_dataSource, m_pModel_dataSelected);
    // m_pModel_typeSelected = pPanel->m_cofigurationResults.m_pModel_dataType;
    // if(m_pModel_typeSelected)
    //     ui->typeSelectedList->setModel(m_pModel_typeSelected);
    ui->serviceIP->setText(pPanel->m_cofigurationResults.dataServiceIP);
    ui->servicePort->setText(QString::number(pPanel->m_cofigurationResults.dataServicePort));
}

void dpConfigurationDialog::onBtnClicked_tabBtn()
{
    QPushButton* pTab = qobject_cast<QPushButton*>(sender());
    if(pTab == m_curActiveTab)
        return;

    if(m_curActiveTab)
    {
        m_curActiveTab->setStyleSheet("QPushButton\n"
                                      "{\n"
                                      "color: rgb(250, 250, 250);\n"
                                      "font: 700 12pt \"黑体\";\n"
                                      "border:0px;\n"
                                      "background-color:transparent;\n"
                                      "}\n"
                                      "QPushButton:hover\n"
                                      "{\n"
                                      "}\n"
                                      "QPushButton:pressed\n"
                                      "{\n"
                                      "}");
    }
    if(pTab)
    {
        pTab->setStyleSheet("QPushButton\n"
                                      "{\n"
                                      "color: rgb(250, 250, 250);\n"
                                      "font: 700 12pt \"黑体\";\n"
                                      "border:1px solid rgb(200,200,200);\n"
                                      "border-bottom:0px;\n"
                                      "background-color:rgba(36,43,50, 250);\n"
                                      "}\n"
                                      "QPushButton:hover\n"
                                      "{\n"
                                      "}\n"
                                      "QPushButton:pressed\n"
                                      "{\n"
                                      "}");

        int nIndex = pTab->property("index").toInt();
        ui->stackedWidget->setCurrentIndex(nIndex);
    }
    m_curActiveTab = pTab;

}

void dpConfigurationDialog::onBtnClicked_confirm()
{
    hide();
    emit sgl_hide();

    if(m_pDataPanel)
    {
        //m_pDataPanel->m_cofigurationResults.m_pModel_dataType = m_pModel_typeSelected;
        copyModelData(m_pModel_typeSelected, m_pDataPanel->m_cofigurationResults.m_pModel_dataType);
        //m_pDataPanel->configurationComplete();
        copyModelData(m_pModel_dataSelected, m_pDataPanel->m_cofigurationResults.m_pModel_dataSource);
        m_pDataPanel->m_cofigurationResults.dataServiceIP = ui->serviceIP->text();
        m_pDataPanel->m_cofigurationResults.dataServicePort = ui->servicePort->text().toInt();
        m_pDataPanel->configurationComplete();
    }
}

void dpConfigurationDialog::onBtnClicked_cancle()
{
    hide();
    emit sgl_hide();
}

void dpConfigurationDialog::onItemClicked_typeSource(const QModelIndex& index)
{
    QStandardItem* item = m_pModel_typeSource->itemFromIndex(index);
    if(item)
    {
        bool bIsHad = false;
        for(int i = 0; i< m_pModel_typeSelected->rowCount(); i++)
        {
            QString itemText = m_pModel_typeSelected->item(i, 0)->text();
            if(itemText == item->text())
            {
                bIsHad = true;
                break;
            }
        }

        if(!bIsHad && m_pModel_typeSelected)
        {
            int nMaximumType = m_pModel_typeSelected->rowCount();
            if(m_pDataPanel && (m_pDataPanel->getType() == lineChart || m_pDataPanel->getType() == curveChart))
                nMaximumType = 2;

            if(m_pModel_typeSelected->rowCount() >= nMaximumType)
            {
                if(!ui->errorTip->isVisible())
                {
                    ui->errorTip->setVisible(true);
                    ui->errorTip->setToolTip(QString("当前面板最多展示 %1 种类型数据").arg(nMaximumType));
                    //QTimer::singleShot(6000, this, [this]{ui->errorTip->setVisible(false);});
                }
                return;
            }

            QStandardItem* newItem = new QStandardItem(item->text());
            newItem->setEditable(false);
            m_pModel_typeSelected->appendRow(newItem);
            ui->typeSelectedList->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);

            if(ui->errorTip->isVisible())
            {
                ui->errorTip->setVisible(false);
                ui->btnConfirm->setEnabled(true);
            }
        }
    }
}
void dpConfigurationDialog::onBtnClicked_remove_type()
{
    QItemSelectionModel* selectionModel = ui->typeSelectedList->selectionModel();
    if(selectionModel && m_pModel_typeSelected)
    {
        int nCurrentRow = selectionModel->currentIndex().row();
        if(nCurrentRow == -1)
            return;

        QList<QStandardItem*> items = m_pModel_typeSelected->takeRow(nCurrentRow);
        for(QStandardItem* item: items)
            delete item;

        if(m_pModel_typeSelected->rowCount() == 0)
        {
            ui->errorTip->setVisible(true);
            ui->errorTip->setToolTip(QString::fromStdWString(L"要至少选择一个数据类型"));
            ui->btnConfirm->setEnabled(false);
        }
        else if(ui->errorTip->isVisible())
            ui->errorTip->setVisible(false);
    }
}

void dpConfigurationDialog::onItemClicked_dataSource(const QModelIndex& index)
{
    QStandardItem* item = m_pModel_dataSource->itemFromIndex(index);
    if(item)
    {
        QString strTag = item->data(Qt::UserRole + itemRole_tag).toString();
        if(strTag != "point")
            return;

        QString strText = "";
        QStandardItem* compontItme = item->parent();
        if(compontItme && compontItme->data(Qt::UserRole + itemRole_tag).toString() == "component")
        {
            QStandardItem* stationItme = compontItme->parent();
            if(stationItme && stationItme->data(Qt::UserRole + itemRole_tag).toString() == "station")
                strText = stationItme->text() + "." + compontItme->text();
            else
                strText = compontItme->text();
        }
        if(strText.isEmpty())
            strText = item->text();
        else
            strText = strText + "." + item->text();

        bool bIsHad = false;
        for(int i = 0; i< m_pModel_dataSelected->rowCount(); i++)
        {
            QString itemText = m_pModel_dataSelected->item(i, 0)->text();
            if(itemText == strText)
            {
                bIsHad = true;
                break;
            }
        }

        if(!bIsHad && m_pModel_dataSelected)
        {
            QStandardItem* newItem = new QStandardItem(strText);
            newItem->setEditable(false);
            newItem->setData(item->data(Qt::UserRole + itemRole_stationID), Qt::UserRole + itemRole_stationID);
            newItem->setData(item->data(Qt::UserRole + itemRole_componentID), Qt::UserRole + itemRole_componentID);
            newItem->setData(item->data(Qt::UserRole + itemRole_pointID), Qt::UserRole + itemRole_pointID);
            m_pModel_dataSelected->appendRow(newItem);
            QColor color = g_globlaColor.value(newItem->row() % g_globlaColor.size());
            newItem->setData(color, Qt::DecorationRole);
            ui->dataSelectedList->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
        }
    }
}
void dpConfigurationDialog::onBtnClicked_remove_source()
{
    QItemSelectionModel* selectionModel = ui->dataSelectedList->selectionModel();
    if(selectionModel && m_pModel_dataSelected)
    {
        int nCurrentRow = selectionModel->currentIndex().row();
        QList<QStandardItem*> items = m_pModel_dataSelected->takeRow(nCurrentRow);
        for(QStandardItem* item: items)
            delete item;

        //更新颜色-从当前删除项往后的所有项
        for(int row = nCurrentRow; row < m_pModel_dataSelected->rowCount(); row++)
        {
            QStandardItem* item = m_pModel_dataSelected->item(row, 0);
            if(item)
            {
                QColor color = g_globlaColor.value(item->row() % g_globlaColor.size());
                item->setData(color, Qt::DecorationRole);
            }
        }
    }
}
