#include "ctrlbrightpanel.h"
#include "base/waitingdlg.h"
#include "globaldefine.h"
#include "deviceitem.h"
#include "tools.h"
#include "xlsxdocument.h"
#include "xlsxworkbook.h"
#include <QMessageBox>
#include <QMetaEnum>
#include <QJsonArray>
#include <QButtonGroup>
#include <QThread>
#include <QSettings>
#include <QTimeEdit>

CtrlBrightPanel::CtrlBrightPanel(QWidget *parent) : QWidget(parent) {
    auto vBox = new VBox(this);
    vBox->setContentsMargins(0,0,0,0);
    vBox->addSpacing(8);

    lbBrightCfg = new QLabel;
    auto font = lbBrightCfg->font();
    font.setPixelSize(font.pixelSize()+2);
    font.setBold(true);
    lbBrightCfg->setFont(font);
    lbBrightCfg->setAlignment(Qt::AlignCenter);
    vBox->addWidget(lbBrightCfg);
    vBox->addSpacing(9);

    auto hBox = new HBox(vBox);
    hBox->addStretch();

    radioAuto = new QRadioButton;
    radioAuto->setChecked(true);
    hBox->addWidget(radioAuto);
    hBox->addSpacing(40);

    radioManual = new QRadioButton;
    hBox->addWidget(radioManual);
    hBox->addSpacing(40);

    radioSchedule = new QRadioButton;
    hBox->addWidget(radioSchedule);
    hBox->addStretch();

    fdAdaptToOld = new QCheckBox;
    hBox->addWidget(fdAdaptToOld);


    auto line = new QFrame;
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    vBox->addWidget(line);

    auto stack = new QStackedLayout(vBox);
    {
        auto vBox = new VBox(stack);

        fdBrightTip = new QLabel;
        fdBrightTip->setAlignment(Qt::AlignCenter);
        fdBrightTip->setWordWrap(true);
        vBox->addWidget(fdBrightTip);

        auto hBox = new QHBoxLayout;
        hBox->addStretch();

        lbSensi = new QLabel;
        lbSensi->setMinimumWidth(120);
        lbSensi->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        hBox->addWidget(lbSensi);

        fdSensi = new QSlider(Qt::Horizontal);
        fdSensi->setRange(1, 100);
        hBox->addWidget(fdSensi);

        auto lbSensiValue = new QLabel(QString::number(fdSensi->value())+"%");
        lbSensiValue->setMinimumWidth(40);
        lbSensiValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        connect(fdSensi, &QSlider::valueChanged, lbSensiValue, [lbSensiValue](int value) {
            lbSensiValue->setText(QString::number(value)+"%");
        });
        hBox->addWidget(lbSensiValue);

        btnSensiSet = new QPushButton;
        btnSensiSet->setMinimumSize(60, 30);
        btnSensiSet->setProperty("ssType", "progManageTool");
        connect(btnSensiSet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "SetBrightnessSensitivity");
            json.insert("_type", "SetBrightnessSensitivity");
            json.insert("sensitivity", fdSensi->value());
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("SetBrightnessSensitivity")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, card, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("SetBrightnessSensitivity"))
                }
            }
        });
        hBox->addWidget(btnSensiSet);

        btnSensiGet = new QPushButton;
        btnSensiGet->setMinimumSize(60, 30);
        btnSensiGet->setProperty("ssType", "progManageTool");
        connect(btnSensiGet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetBrightnessSensitivity");
            json.insert("_type", "GetBrightnessSensitivity");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetBrightnessSensitivity")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                    Def_CtrlSingleGetReply
                    waitingDlg->success();
                    fdSensi->setValue(json["sensitivity"].toInt());
                });
            } else {
                foreach(auto card, *gSelCards) {
                    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                    auto cardId = card->m_strCardId;
                    connect(reply, &QNetworkReply::finished, this, [reply, cardId] {
                        QJsonDocument json;
                        QString err = checkReplyForJson(reply, &json);
                        if(err.isEmpty()) err = QString::number(json["sensitivity"].toInt());
                        gFdResInfo->append(cardId+" "+tr("GetBrightnessSensitivity")+" "+err);
                    });
                }
            }
        });
        hBox->addWidget(btnSensiGet);

        hBox->addStretch();
        vBox->addLayout(hBox);

        hBox = new QHBoxLayout;
        hBox->addStretch();

        lbMinBright = new QLabel;
        lbMinBright->setMinimumWidth(120);
        lbMinBright->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        hBox->addWidget(lbMinBright);

        fdMinBright = new QSlider(Qt::Horizontal);
        fdMinBright->setRange(1, 100);
        hBox->addWidget(fdMinBright);

        auto lbMinBrightValue = new QLabel(QString::number(fdMinBright->value())+"%");
        lbMinBrightValue->setMinimumWidth(40);
        lbMinBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        connect(fdMinBright, &QSlider::valueChanged, lbSensiValue, [lbMinBrightValue](int value) {
            lbMinBrightValue->setText(QString::number(value)+"%");
        });
        hBox->addWidget(lbMinBrightValue);

        btnMinBrightSet = new QPushButton;
        btnMinBrightSet->setMinimumSize(60, 30);
        btnMinBrightSet->setProperty("ssType", "progManageTool");
        connect(btnMinBrightSet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            auto isAdaptToOld = fdAdaptToOld->isChecked();
            QJsonObject json;
            json.insert("_id", "SetMinBrightness");
            json.insert("_type", "SetMinBrightness");
            auto brightPercent = fdMinBright->value();
            if(! isAdaptToOld) json.insert("minBrightnessPercentage", brightPercent);
            if(gSelCards->count() == 1) {
                if(isAdaptToOld) json.insert("brightness", (brightPercent * gSelCards->at(0)->BrightnessLevel + 50) / 100);
                auto waitingDlg = new WaitingDlg(this, tr("SetMinBrightness")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    if(isAdaptToOld) json.insert("brightness", (brightPercent * card->BrightnessLevel + 50) / 100);
                    Def_CtrlSetMulti(tr("SetMinBrightness"));
                }
            }
        });
        hBox->addWidget(btnMinBrightSet);

        btnMinBrightGet = new QPushButton;
        btnMinBrightGet->setMinimumSize(60, 30);
        btnMinBrightGet->setProperty("ssType", "progManageTool");
        connect(btnMinBrightGet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetMinBrightness");
            json.insert("_type", "GetMinBrightness");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetMinBrightness")+" ...");
                Def_CtrlReqPre
                auto brightLevel = card->BrightnessLevel;
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, brightLevel] {
                    Def_CtrlSingleGetReply
                    waitingDlg->success();
                    auto value = json["minBrightnessPercentage"].toInt(-1);
                    if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / brightLevel);
                    fdMinBright->setValue(value);
                });
            } else {
                foreach(auto card, *gSelCards) {
                    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                    auto cardId = card->m_strCardId;
                    auto brightLevel = card->BrightnessLevel;
                    connect(reply, &QNetworkReply::finished, this, [reply, cardId, brightLevel] {
                        QJsonDocument json;
                        QString err = checkReplyForJson(reply, &json);
                        if(err.isEmpty()) {
                            auto value = json["minBrightnessPercentage"].toInt(-1);
                            if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / brightLevel);
                            err = QString::number(value)+"%";
                        }
                        gFdResInfo->append(cardId+" "+tr("GetMinBrightness")+" "+err);
                    });
                }
            }
        });
        hBox->addWidget(btnMinBrightGet);

        hBox->addStretch();
        vBox->addLayout(hBox);


        line = new QFrame;
        line->setFrameShape(QFrame::HLine);
        line->setFrameShadow(QFrame::Sunken);
        vBox->addWidget(line);

        fdSensiTypeTip = new QLabel;
        fdSensiTypeTip->setAlignment(Qt::AlignCenter);
        fdSensiTypeTip->setWordWrap(true);
        vBox->addWidget(fdSensiTypeTip);

        hBox = new QHBoxLayout;
        hBox->addStretch();

        fdR68 = new QRadioButton("R68/RL3");
        hBox->addWidget(fdR68);

        fdRL2 = new QRadioButton("RL2");
        hBox->addWidget(fdRL2);

        hBox->addSpacing(20);

        btnUpload = new QPushButton;
        btnUpload->setMinimumSize(60, 30);
        btnUpload->setProperty("ssType", "progManageTool");
        connect(btnUpload, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QString sensorName;
            if(fdRL2->isChecked()) sensorName = fdRL2->text();
            else if(fdR68->isChecked()) sensorName = fdR68->text();
            else {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NeedSelectSensorTypeTip"));
                return;
            }
            QString xlsxFile = QFileDialog::getOpenFileName(this, tr("Open file dialog"), "/", "brightness files(*.xlsx)");
            if(xlsxFile.isEmpty() || ! QFileInfo::exists(xlsxFile)) return;
            QXlsx::Document xlsx(xlsxFile);
            auto workbook = xlsx.workbook();
            QXlsx::Worksheet *sheet = 0;
            if(workbook->sheetCount() < 2) {
                sheet = xlsx.currentWorksheet();
                if(sheet==0) {
                    QMessageBox::information(gMainWin, tr("Tip"), tr("Not found current worksheet"));
                    return;
                }
            } else {
                auto names = sensorName.split("/");
                foreach(auto name, names) {
                    auto idx = xlsx.sheetNames().indexOf(name);
                    if(idx > -1) {
                        workbook->setActiveSheet(idx);
                        sheet = dynamic_cast<QXlsx::Worksheet *>(workbook->sheet(idx));
                        break;
                    }
                }
                if(sheet==0) {
                    QMessageBox::information(gMainWin, tr("Tip"), "Not found sheet "+sensorName);
                    return;
                }
            }
            QJsonArray values;
            for(int j=0; j<255; j++) {
                auto val = sheet->read(3, j+3).toString();
                if(val.isEmpty()) {
                    QMessageBox::information(gMainWin, tr("Tip"), "Cell is empty at 3, "+QString::number(j+3));
                    return;
                }
                values.append(val);
            }
            QJsonObject json;
            json.insert("_id", "SensorBrightnessTable");
            json.insert("_type", "SensorBrightnessTable");
            json.insert("values", values);
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("SensorBrightnessTable"));
                Def_CtrlReqPre;
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter;
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("SensorBrightnessTable"));
                }
            }
        });
        hBox->addWidget(btnUpload);

        btnTableGet = new QPushButton();
        btnTableGet->setMinimumSize(60, 30);
        btnTableGet->setProperty("ssType", "progManageTool");
        connect(btnTableGet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QString strSensorType;
            if(fdRL2->isChecked()) strSensorType = fdRL2->text();
            else if(fdR68->isChecked()) strSensorType = fdR68->text();
            else {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NeedSelectSensorTypeTip"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetSensorBrightnessTable");
            json.insert("_type", "GetSensorBrightnessTable");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetSensorBrightnessTable"));
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card, strSensorType] {
                    Def_CtrlSingleGetReply
                    waitingDlg->close();
                    QStringList values = json["values"].toVariant().value<QStringList>();
                    if(values.isEmpty()) {
                        QMessageBox::information(gMainWin, tr("Tip"), tr("no sensorBrightnessTable"));
                        return;
                    }
                    QString tempFile = QCoreApplication::applicationDirPath()+"/bright-template.xlsx";
                    QFile tempQFile(tempFile);
                    if(! tempQFile.exists()) {
                        QMessageBox::information(gMainWin, tr("Tip"), tempFile+" is not exist");
                        return;
                    }
                    QString selectFilter = "*.xlsx";
                    QString savingFile = QFileDialog::getSaveFileName(this, tr("Save file"), card->m_strCardId + "BrightnessTable.xlsx", "brightness(*.xlsx );", &selectFilter, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
                    if(savingFile.isEmpty()) return;
                    tempQFile.copy(savingFile);
                    QXlsx::Document xlsx(savingFile);
                    xlsx.selectSheet(strSensorType);
                    for(int m=0; m<values.count(); m++) xlsx.write(3, m+3, values.at(m).toInt());
                    xlsx.save();
                });
            }
        });
        hBox->addWidget(btnTableGet);

        hBox->addStretch();
        vBox->addLayout(hBox);


        hBox = new QHBoxLayout;
        hBox->addStretch();

        lbCurBright = new QLabel;
        hBox->addWidget(lbCurBright);

        fdCurBright = new QLabel;
        hBox->addWidget(fdCurBright);

        btnCurBrightGet = new QPushButton;
        btnCurBrightGet->setMinimumSize(60, 30);
        btnCurBrightGet->setProperty("ssType", "progManageTool");
        connect(btnCurBrightGet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetCurrentSensorBrightness");
            json.insert("_type", "GetCurrentSensorBrightness");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetCurrentSensorBrightness"));
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] {
                    QJsonDocument json;
                    QByteArray data;
                    QString err = checkReplyForJson(reply, &json, &data);
                    if(! err.isEmpty()) {
                        waitingDlg->close();
                        QMessageBox::critical(gMainWin, tr("Error"), err);
                        return;
                    }
                    waitingDlg->success();
                    if(json["is485"].toBool()) fdR68->setChecked(true);
                    else fdRL2->setChecked(true);
                    fdCurBright->setText(QString::number(qRound(json["value"].toInt() * 100.0 / card->BrightnessLevel))+"%");
                });
            } else {
                foreach(auto card, *gSelCards) {
                    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                    connect(reply, &QNetworkReply::finished, this, [reply, card] {
                        QJsonDocument json;
                        QString err = checkReplyForJson(reply, &json);
                        if(err.isEmpty()) err = QString::number(qRound(json["value"].toInt() * 100.0 / card->BrightnessLevel))+"%";
                        gFdResInfo->append(card->m_strCardId+" "+tr("GetCurrentSensorBrightness")+" "+err);
                    });
                }
            }
        });
        hBox->addWidget(btnCurBrightGet);

        hBox->addStretch();
        vBox->addLayout(hBox);
        vBox->addStretch();
    }
    {
        auto vBox = new VBox(stack);

        auto hBox = new QHBoxLayout;
        hBox->addStretch();

        lbFixedBright = new QLabel;
        hBox->addWidget(lbFixedBright);

        fdFixedBright = new QSlider(Qt::Horizontal);
        fdFixedBright->setRange(1, 100);
        hBox->addWidget(fdFixedBright);

        auto lbBrightValue = new QLabel(QString::number(fdFixedBright->value())+"%");
        lbBrightValue->setMinimumWidth(40);
        lbBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        connect(fdFixedBright, &QSlider::valueChanged, lbBrightValue, [lbBrightValue](int value) {
            lbBrightValue->setText(QString::number(value)+"%");
        });
        hBox->addWidget(lbBrightValue);

        hBox->addStretch();

        vBox->addLayout(hBox);
        vBox->addSpacing(20);

        hBox = new QHBoxLayout;
        hBox->addStretch();

        btnFixedSet = new QPushButton;
        btnFixedSet->setMinimumSize(60, 30);
        btnFixedSet->setProperty("ssType", "progManageTool");
        connect(btnFixedSet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            auto isAdaptToOld = fdAdaptToOld->isChecked();
            QJsonObject json;
            json.insert("_id", "SetBrightness");
            json.insert("_type", "SetBrightness");
            auto percent = fdFixedBright->value();
            if(! isAdaptToOld) json.insert("brightnessPercentage", percent);
            if(gSelCards->count() == 1) {
                if(isAdaptToOld) json.insert("brightness", (percent * gSelCards->at(0)->BrightnessLevel + 50) / 100);
                auto waitingDlg = new WaitingDlg(this, tr("SetBrightness"));
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    if(isAdaptToOld) json.insert("brightness", (percent * card->BrightnessLevel + 50) / 100);
                    Def_CtrlSetMulti(tr("SetBrightness"))
                }
            }
        });
        hBox->addWidget(btnFixedSet);

        btnFixedGet = new QPushButton;
        btnFixedGet->setMinimumSize(60, 30);
        btnFixedGet->setProperty("ssType", "progManageTool");
        connect(btnFixedGet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetBrightness");
            json.insert("_type", "GetBrightness");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetBrightness"));
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] {
                    QJsonDocument json;
                    QByteArray data;
                    QString err = checkReplyForJson(reply, &json, &data);
                    if(! err.isEmpty()) {
                        waitingDlg->close();
                        QMessageBox::critical(gMainWin, tr("Error"), err);
                        return;
                    }
                    waitingDlg->success();
                    card->bright = json["brightnessPercentage"].toInt(-1);
                    if(card->bright==-1) card->bright = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel);
                    fdFixedBright->setValue(card->bright);
                });
            } else {
                foreach(auto card, *gSelCards) {
                    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                    connect(reply, &QNetworkReply::finished, this, [reply, card] {
                        QJsonDocument json;
                        QString err = checkReplyForJson(reply, &json);
                        if(err.isEmpty()) {
                            auto value = json["brightnessPercentage"].toInt(-1);
                            if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel);
                            err = QString::number(value)+"%";
                        }
                        gFdResInfo->append(card->m_strCardId+" "+tr("Brightness")+" "+err);
                    });
                }
            }
        });
        hBox->addWidget(btnFixedGet);

        hBox->addStretch();

        vBox->addLayout(hBox);
        vBox->addStretch();
    }
    {
        auto hBox = new HBox(stack);
        hBox->addStretch();
        auto vBox = new VBox(hBox);
        hBox->addStretch();

        hBox = new HBox(vBox);

        fdScheTip = new QLabel;
        fdScheTip->setWordWrap(true);
        hBox->addWidget(fdScheTip);


        hBox = new HBox(vBox);

        btnScheAdd = new QPushButton;
        btnScheAdd->setMinimumSize(60, 30);
        btnScheAdd->setProperty("ssType", "progManageTool");
        connect(btnScheAdd, &QPushButton::clicked, this, [this] {
            int row = tableSche->rowCount();
            tableSche->insertRow(row);

            auto cellWgt = new QWidget;
            auto hBox = new QHBoxLayout(cellWgt);

            auto slider = new QSlider(Qt::Horizontal);
            slider->setRange(1, 100);
            hBox->addWidget(slider);

            auto lb = new QLabel(QString::number(slider->value())+"%");
            connect(slider, &QSlider::valueChanged, lb, [lb](int value) {
                lb->setText(QString::number(value)+"%");
            });
            hBox->addWidget(lb);

            tableSche->setCellWidget(row, "bright", cellWgt);

            auto timeEdit = new QTimeEdit(QTime(0, 0));
            timeEdit->setDisplayFormat("HH:mm");
            timeEdit->setAlignment(Qt::AlignCenter);
            tableSche->setCellWidget(row, "start", timeEdit);

            timeEdit = new QTimeEdit(QTime(1, 0));
            timeEdit->setDisplayFormat("HH:mm");
            timeEdit->setAlignment(Qt::AlignCenter);
            tableSche->setCellWidget(row, "end", timeEdit);
        });
        hBox->addWidget(btnScheAdd);

        btnScheDel = new QPushButton;
        btnScheDel->setMinimumSize(60, 30);
        btnScheDel->setProperty("ssType", "progManageTool");
        connect(btnScheDel, &QPushButton::clicked, this, [this] {
            auto selected = tableSche->selectedRanges();
            if(! selected.isEmpty()) tableSche->model()->removeRows(selected[0].topRow(), selected[0].rowCount());
        });
        hBox->addWidget(btnScheDel);

        btnScheClear = new QPushButton;
        btnScheClear->setMinimumSize(60, 30);
        btnScheClear->setProperty("ssType", "progManageTool");
        connect(btnScheClear, &QPushButton::clicked, this, [this] {tableSche->setRowCount(0);});
        hBox->addWidget(btnScheClear);

        hBox->addStretch();

        lbDefBright = new QLabel;
        lbDefBright->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        lbDefBright->setMinimumWidth(120);
        hBox->addWidget(lbDefBright);

        fdDefBright = new QSlider(Qt::Horizontal);
        fdDefBright->setRange(0, 100);
        fdDefBright->setValue(100);
        fdDefBright->setMinimumWidth(120);
        hBox->addWidget(fdDefBright);

        auto lbDefBrightValue = new QLabel(QString::number(fdDefBright->value())+"%");
        lbDefBrightValue->setMinimumWidth(40);
        lbDefBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        connect(fdDefBright, &QSlider::valueChanged, lbDefBrightValue, [lbDefBrightValue](int value) {
            lbDefBrightValue->setText(QString::number(value)+"%");
        });
        hBox->addWidget(lbDefBrightValue);

        hBox->addStretch();

        btnScheImport = new QPushButton;
        btnScheImport->setMinimumSize(QSize(60, 30));
        btnScheImport->setProperty("ssType", "progManageTool");
        connect(btnScheImport, &QPushButton::clicked, this, [this] {
            auto dir = QSettings().value("CtrlScheduleDir").toString();
            if(dir.isEmpty()) dir = "/";
            QString scheFile = QFileDialog::getOpenFileName(this, tr("Import File"), dir, tr("BrightnessSchedule (*.bjs)"));
            if(scheFile.isEmpty()) return;
            QFile scheQFile(scheFile);
            if(! scheQFile.open(QIODevice::ReadOnly)) return;
            auto data = scheQFile.readAll();
            scheQFile.close();
            auto json = QJsonDocument::fromJson(data);
            tableSche->setRowCount(0);
            fdDefBright->setValue(json["defaultBrightness"].toInt());
            auto jsitems = json["items"].toArray();
            foreach(QJsonValue jsitem, jsitems) {
                auto schedule = jsitem["schedules"][0];
                int row = tableSche->rowCount();
                tableSche->insertRow(row);

                auto cellWgt = new QWidget;
                auto hBox = new QHBoxLayout(cellWgt);

                auto slider = new QSlider(Qt::Horizontal);
                slider->setRange(1, 100);
                slider->setValue(jsitem["brightness"].toInt());
                hBox->addWidget(slider);

                auto lb = new QLabel(QString::number(slider->value())+"%");
                connect(slider, &QSlider::valueChanged, lb, [lb](int value) {
                    lb->setText(QString::number(value)+"%");
                });
                hBox->addWidget(lb);
                tableSche->setCellWidget(row, "bright", cellWgt);

                auto timeEdit = new QTimeEdit(QTime::fromString(schedule["startTime"].toString(), "HH:mm"));
                timeEdit->setDisplayFormat("HH:mm");
                timeEdit->setAlignment(Qt::AlignCenter);
                tableSche->setCellWidget(row, "start", timeEdit);

                timeEdit = new QTimeEdit(QTime::fromString(schedule["endTime"].toString(), "HH:mm"));
                timeEdit->setDisplayFormat("HH:mm");
                timeEdit->setAlignment(Qt::AlignCenter);
                tableSche->setCellWidget(row, "end", timeEdit);
            }
        });
        hBox->addWidget(btnScheImport);

        btnScheExport = new QPushButton;
        btnScheExport->setMinimumSize(QSize(60, 30));
        btnScheExport->setProperty("ssType", "progManageTool");
        connect(btnScheExport, &QPushButton::clicked, this, [this] {
            QSettings settings;
            auto dir = settings.value("CtrlScheduleDir").toString();
            if(dir.isEmpty()) dir = "/";
            QString scheFile = QFileDialog::getSaveFileName(this, tr("Save File"), dir, tr("BrightnessSchedule (*.bjs)"));
            if(scheFile.isEmpty()) return;
            settings.setValue("CtrlScheduleDir", QFileInfo(scheFile).absolutePath());
            QFile scheQFile(scheFile);
            if(! scheQFile.open(QIODevice::WriteOnly)) return;
            QJsonArray items;
            for(int i=0; i<tableSche->rowCount(); i++) items.append(QJsonObject{
                {"brightness", static_cast<QSlider*>(tableSche->cellWidget(i, "bright")->layout()->itemAt(0)->widget())->value()},
                {"schedules", QJsonArray{QJsonObject{
                    {"startTime", static_cast<QTimeEdit*>(tableSche->cellWidget(i, "start"))->text()},
                    {"endTime", static_cast<QTimeEdit*>(tableSche->cellWidget(i, "end"))->text()}
                }}}
            });
            scheQFile.write(QJsonDocument(QJsonObject{{"defaultBrightness", fdDefBright->value()}, {"items", items}}).toJson());
            scheQFile.close();
        });
        hBox->addWidget(btnScheExport);


        tableSche = new Table({
              {"bright", "", 300},
              {"start", "", 100},
              {"end", "", 100}
        });
        tableSche->setDefs();
        tableSche->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
        vBox->addWidget(tableSche);

        hBox = new HBox(vBox);
        hBox->addStretch();

        btnScheSet = new QPushButton;
        btnScheSet->setMinimumSize(QSize(60, 30));
        btnScheSet->setProperty("ssType", "progManageTool");
        connect(btnScheSet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            auto isAdaptToOld = fdAdaptToOld->isChecked();
            QJsonObject json;
            json.insert("_id", "SetAutoBrightnessTask");
            json.insert("_type", "SetAutoBrightnessTask");
            if(! isAdaptToOld) getScheduleJson(json, 0);
            if(gSelCards->count() == 1) {
                if(isAdaptToOld) getScheduleJson(json, gSelCards->at(0)->BrightnessLevel);
                auto waitingDlg = new WaitingDlg(this, tr("SetAutoBrightnessTask"));
                Def_CtrlReqPre;
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    if(isAdaptToOld) getScheduleJson(json, card->BrightnessLevel);
                    Def_CtrlSetMulti(tr("SetAutoBrightnessTask"))
                }
            }
        });
        hBox->addWidget(btnScheSet);

        hBox->addStretch();

        btnScheGet = new QPushButton;
        btnScheGet->setMinimumSize(QSize(60, 30));
        btnScheGet->setProperty("ssType", "progManageTool");
        connect(btnScheGet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetAutoBrightnessTask");
            json.insert("_type", "GetAutoBrightnessTask");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetAutoBrightnessTask"));
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] {
                    Def_CtrlSingleGetReply
                    waitingDlg->success();
                    restoreScheduleJson(json, card->BrightnessLevel);
                });
            }
        });
        hBox->addWidget(btnScheGet);

        hBox->addStretch();
    }
    stack->setCurrentIndex(0);

    auto group = new QButtonGroup;
    group->addButton(radioAuto, 0);
    group->addButton(radioManual, 1);
    group->addButton(radioSchedule, 2);
    connect(group, &QButtonGroup::idToggled, stack, [=](int idx, bool checked) {
        if(checked) stack->setCurrentIndex(idx);
    });

    connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] {
        if(isVisible()) init();
    });
    transUi();
}

void CtrlBrightPanel::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    init();
}
void CtrlBrightPanel::init() {
    bool isSingle = gSelCards->count()==1;
    btnTableGet->setEnabled(isSingle);
    btnScheGet->setEnabled(isSingle);
    if(! isSingle) return;
    auto card = gSelCards->at(0);

    mSensi = -1;
    mTask = -1;

    QJsonObject json;
    json.insert("_id", "GetAutoBrightnessTask");
    json.insert("_type", "GetAutoBrightnessTask");
    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [this, reply, card] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mTask = restoreScheduleJson(json, card->BrightnessLevel);
        if(mTask) radioSchedule->setChecked(true);
        else if(mSensi > 0) radioAuto->setChecked(true);
        else if(mSensi == 0) radioManual->setChecked(true);
    });
    
    json = QJsonObject();
    json.insert("_id", "GetBrightnessSensitivity");
    json.insert("_type", "GetBrightnessSensitivity");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [this, reply] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        mSensi = json["sensitivity"].toInt();
        fdSensi->setValue(mSensi);
        if(mTask != 0) return;
        if(mSensi > 0) radioAuto->setChecked(true);
        else radioManual->setChecked(true);
    });

    json = QJsonObject();
    json.insert("_id", "GetMinBrightness");
    json.insert("_type", "GetMinBrightness");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [this, reply, card] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        auto value = json["minBrightnessPercentage"].toInt(-1);
        if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel);
        fdMinBright->setValue(value);
    });

    json = QJsonObject();
    json.insert("_id", "GetBrightness");
    json.insert("_type", "GetBrightness");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [this, reply, card] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        card->bright = json["brightnessPercentage"].toInt(-1);
        if(card->bright==-1) card->bright = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel);
        fdFixedBright->setValue(card->bright);
    });
}

void CtrlBrightPanel::changeEvent(QEvent *event) {
    QWidget::changeEvent(event);
    if(event->type() == QEvent::LanguageChange) transUi();
}
void CtrlBrightPanel::transUi() {
    lbBrightCfg->setText(tr("Brightness Configuration"));
    radioAuto->setText(tr("Auto"));
    radioManual->setText(tr("Manual"));
    radioSchedule->setText(tr("Schedule"));
    fdAdaptToOld->setText(tr("Adapt to Old Devices"));

    fdBrightTip->setText(tr("BrightTip1"));
    fdSensiTypeTip->setText(tr("BrightTip2"));
    lbSensi->setText(tr("Sensitivity"));
    lbMinBright->setText(tr("Minbrightness"));
    btnMinBrightSet->setText(tr("Set"));
    btnSensiSet->setText(tr("Set"));
    btnUpload->setText(tr("Upload"));
    btnMinBrightGet->setText(tr("Readback"));
    btnSensiGet->setText(tr("Readback"));
    btnTableGet->setText(tr("ReadbackTable"));
    btnCurBrightGet->setText(tr("Refresh"));
    lbCurBright->setText(tr("Cur Brigntness")+": ");

    lbFixedBright->setText(tr("Brightness value"));
    btnFixedSet->setText(tr("Set"));
    btnFixedGet->setText(tr("Readback"));

    lbDefBright->setText(tr("Default brightness"));
    btnScheAdd->setText(tr("Add"));
    btnScheClear->setText(tr("Clear"));
    btnScheDel->setText(tr("Delete"));
    btnScheImport->setText(tr("Import"));
    btnScheExport->setText(tr("Export"));

    tableSche->setHeaderText("bright", tr("BrightnessValue"));
    tableSche->setHeaderText("start", tr("Start Time"));
    tableSche->setHeaderText("end", tr("End Time"));

    btnScheSet->setText(tr("Apply"));
    btnScheGet->setText(tr("Readback"));
    fdScheTip->setText(tr("Default brightness tip"));
}

bool CtrlBrightPanel::restoreScheduleJson(QJsonDocument &json, int max) {
    tableSche->setRowCount(0);
    auto taskBrightness = json["taskBrightness"];
    auto brightness = json["defaultBrightnessPercentage"].toInt(-1);
    if(brightness==-1) brightness = qRound(taskBrightness["defaultBrightness"].toInt() * 100.0 / max);
    fdDefBright->setValue(brightness);
    auto jsitems = taskBrightness["items"].toArray();
    auto brightnesses = json["brightnessPercentageList"].toArray();
    for(int i=0; i<jsitems.size(); i++) {
        auto schedule = jsitems.at(i)["schedules"][0];
        int row = tableSche->rowCount();
        tableSche->insertRow(row);

        auto cellWgt = new QWidget;
        auto hBox = new QHBoxLayout(cellWgt);

        auto slider = new QSlider(Qt::Horizontal);
        slider->setRange(1, 100);
        if(brightnesses.size() > i) slider->setValue(brightnesses[i].toInt());
        else slider->setValue(qRound(jsitems.at(i)["brightness"].toInt() * 100.0 / max));
        hBox->addWidget(slider);

        auto lb = new QLabel(QString::number(slider->value())+"%");
        connect(slider, &QSlider::valueChanged, lb, [lb](int value) {
            lb->setText(QString::number(value)+"%");
        });
        hBox->addWidget(lb);
        tableSche->setCellWidget(row, "bright", cellWgt);

        auto timeEdit = new QTimeEdit(QTime::fromString(schedule["startTime"].toString(), "HH:mm"));
        timeEdit->setDisplayFormat("HH:mm");
        timeEdit->setAlignment(Qt::AlignCenter);
        tableSche->setCellWidget(row, "start", timeEdit);

        timeEdit = new QTimeEdit(QTime::fromString(schedule["endTime"].toString(), "HH:mm"));
        timeEdit->setDisplayFormat("HH:mm");
        timeEdit->setAlignment(Qt::AlignCenter);
        tableSche->setCellWidget(row, "end", timeEdit);
    }
    return jsitems.count() > 0;
}
void CtrlBrightPanel::getScheduleJson(QJsonObject &json, int max) {
    QJsonArray items, brightnesses;
    for(int i=0; i<tableSche->rowCount(); i++) {
        QJsonObject item;
        auto brightness = static_cast<QSlider*>(tableSche->cellWidget(i, "bright")->layout()->itemAt(0)->widget())->value();
        if(max==0) brightnesses.append(brightness);
        else item.insert("brightness", (brightness * max + 50) / 100);
        item.insert("schedules", QJsonArray{QJsonObject{
            {"timeType", "Range"},
            {"startTime", static_cast<QTimeEdit*>(tableSche->cellWidget(i, "start"))->text()},
            {"endTime", static_cast<QTimeEdit*>(tableSche->cellWidget(i, "end"))->text()},
            {"dateType", "All"},
            {"filterType", "None"},
            {"monthFilter", QJsonArray()},
            {"weekFilter", QJsonArray()}
        }});
        items.append(item);
    }
    QJsonObject taskBrightness{
            {"createBy", "alahover"},
            {"name", "TimingBrightness"},
            {"items", items}
    };
    if(max==0) {
        json.insert("defaultBrightnessPercentage", fdDefBright->value());
        json.insert("brightnessPercentageList", brightnesses);
    } else {
        auto def = (fdDefBright->value() * max + 50) / 100;
        taskBrightness.insert("defaultBrightness", def);
        taskBrightness.insert("brightness", def);
    }
    json.insert("taskBrightness", taskBrightness);
}
