#include "controlbrightnessschedule.h"
#include "ui_controlbrightnessschedule.h"
#include "LoUIClass/x_uimsgboxok.h"
#include "QFileDialog"
#include "QDir"
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <globaldefine.h>
#include "controlbrightnessscheduleedit.h"
#include "LoUIClass/x_spinboxdelegate.h"
#include "LoUIClass/x_timeeditdelegate.h"
#include "loappconfig.h"
#include "QSettings"
ControlBrightnessSchedule::ControlBrightnessSchedule(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlBrightnessSchedule)
{
    m_pLedlist=list;
    ui->setupUi(this);
    refreshLable();
    ui->pushButtonAdd->setProperty("ssType", "progManageTool");
    ui->pushButtonAdd->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");

    ui->pushButtonImport->setProperty("ssType", "progManageTool");
    ui->pushButtonImport->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonExport->setProperty("ssType", "progManageTool");
    ui->pushButtonExport->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");

    ui->pushButtonDelete->setProperty("ssType", "progManageTool");
    ui->pushButtonDelete->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");

    ui->pushButtonClear->setProperty("ssType", "progManageTool");
    ui->pushButtonClear->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");

    ui->pushButtonApply->setProperty("ssType", "progManageTool");
    ui->pushButtonApply->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");

    ui->pushButtonReadback->setProperty("ssType", "progManageTool");
    ui->pushButtonReadback->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->lineEdit->setText("255");
    m_pModel = new QStandardItemModel(this);
    m_pModel->setColumnCount(3);
    m_pModel->setHeaderData(0,Qt::Horizontal, tr("BrightnessValue"));
    m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time"));
    m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time"));
    ui->tableView->setModel(m_pModel);
    SpinBoxDelegate *pBrightnessDelegate=new SpinBoxDelegate(this,0);
    ui->tableView->setItemDelegateForColumn(0,pBrightnessDelegate);

    X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this);
    ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate);
    ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate);

    //! [0]
    //ui->tableView->horizontalHeader()->setStretchLastSection(true);


    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // ui->tableView->verticalHeader()->hide();
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setFocusPolicy(Qt::NoFocus);
    //ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); //只读
    //设置表格的单元为只读属性，即不能编辑
    //ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent())
            connect(ui->pushButtonAdd,SIGNAL(clicked()),this,SLOT(OnClickAdd()));
    connect(ui->pushButtonImport,SIGNAL(clicked()),this,SLOT(OnClickImport()));
    connect(ui->pushButtonExport,SIGNAL(clicked()),this,SLOT(OnClickExport()));
    connect(ui->pushButtonDelete,SIGNAL(clicked()),this,SLOT(OnClickDelete()));
    connect(ui->pushButtonClear,SIGNAL(clicked()),this,SLOT(OnClickClear()));
    connect(ui->pushButtonApply,SIGNAL(clicked()),this,SLOT(OnClickApply()));
    connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnClickReadback()));


}

ControlBrightnessSchedule::~ControlBrightnessSchedule()
{
    delete ui;
}
void ControlBrightnessSchedule::refreshLable()
{
    ui->labelDefaultBrightness->setText(tr("Default brightness"));
    ui->pushButtonAdd->setText(tr("Add"));
    ui->pushButtonApply->setText(tr("Apply"));
    ui->pushButtonClear->setText(tr("Clear"));
    ui->pushButtonDelete->setText(tr("Delete"));
    ui->pushButtonImport->setText(tr("Import"));
    ui->pushButtonExport->setText(tr("Export"));
    ui->pushButtonReadback->setText(tr("Readback"));
    ui->label->setText(tr("Default brightness tip"));
}

void ControlBrightnessSchedule::onSelectedDeviceList(QList<LedCard*> *list)
{
    m_pLedlist=list;
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()==1)
    {
        ui->pushButtonReadback->setEnabled(true);
    }
    else {
        ui->pushButtonReadback->setEnabled(false);
    }
    MACRO_DEFINE_CONTROL_FUNC3

}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlBrightnessSchedule::OnProHttpResponse(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("wDevicesItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "GetAutoBrightnessTask")
            {

            }
            else if(strType == "SetAutoBrightnessTask")
            {
                //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetBrightness")+":"+tr("success"));
            }

            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK

        }
    }
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlBrightnessSchedule::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("wDevicesItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "GetAutoBrightnessTask")
            {           
                emit sigHaveSchedule(JieXiJsonTaskBrightness(jsonObject["taskBrightness"].toObject()));
            }

        }
    }
}

void ControlBrightnessSchedule::OnControlTypeSwitchIndexChanged(int index)
{
    if(index==ENUM_CONTRL_WIDGET_BRIGHTNESS)
    {
        m_bSelected=true;
        if(m_pLedCard!=nullptr)
            onReadbackAllThisPage();
    }
    else {
        m_bSelected=false;
    }
}
void  ControlBrightnessSchedule::onReadbackAllThisPage()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()!=1)
        return;

    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetAutoBrightnessTask");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json);
}
void  ControlBrightnessSchedule::OnClickAdd()
{
    QList<QStandardItem *> Item;
    Item.append(new QStandardItem(QString::number(255)));
    Item.append(new QStandardItem("00:00"));
    Item.append(new QStandardItem("01:00"));

    Item.at(0)->setTextAlignment(Qt::AlignCenter);
    Item.at(1)->setTextAlignment(Qt::AlignCenter);
    Item.at(2)->setTextAlignment(Qt::AlignCenter);
    //m_lineEidt[i]->installEventFilter(this);
    //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this));
    m_pModel->appendRow(Item);

//    ControlBrightnessScheduleEdit *pDlg=new ControlBrightnessScheduleEdit(this);
//    connect(pDlg,SIGNAL(sigAddOneItem(QString,QString,int)),this,SLOT(OnAddOneItem(QString,QString,int)));
//    pDlg->show();
}
void  ControlBrightnessSchedule::OnClickImport()
{
    LoAppConfig *cfg = LoAppConfig::getInstance();
    QSettings *settings = new QSettings(cfg->OrganizationName(), cfg->ApplicationName());
    QString strDir="/";
    if(settings->value("lasOpendFileDlgtDir").isValid()) {
           strDir=settings->value("lasOpendFileDlgtDir").toString();
    }
    else
    {

    }
    QFileDialog dlg;
    QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog",
                                             strDir,
                                             tr("BrightnessSchedule (*.bjs)"));
    if(strBrightScheduleFile.isEmpty())
        return;
    QFile fJson(strBrightScheduleFile);
    if(fJson.open(QIODevice::ReadOnly)){
        QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll());
       QJsonObject oTaskBrightness=jBrightSchedule.object();
       JieXiJsonTaskBrightness(oTaskBrightness);
        fJson.close();
    }
    delete settings;
}
bool  ControlBrightnessSchedule::JieXiJsonTaskBrightness(QJsonObject oTaskBrightness)
{
    OnClickClear();
    QJsonArray items;
    QString strDefaultBrightness=QString::number(oTaskBrightness["defaultBrightness"].toInt());
    if(!strDefaultBrightness.isEmpty())
        ui->lineEdit->setText(strDefaultBrightness);
    items=oTaskBrightness["items"].toArray();
    //bool bHaveSchedule=false;
    for(int i=0;i<items.count();i++)
    {
        QJsonObject item=items.at(i).toObject();
        QJsonArray oSchedules;
        oSchedules=item["schedules"].toArray();
        QJsonObject oSchedule=oSchedules.at(0).toObject();

        QList<QStandardItem *> Item;
        Item.append(new QStandardItem(QString::number(item["brightness"].toInt())));
        Item.append(new QStandardItem(oSchedule["startTime"].toString()));
        Item.append(new QStandardItem(oSchedule["endTime"].toString()));

        Item.at(0)->setTextAlignment(Qt::AlignCenter);
        Item.at(1)->setTextAlignment(Qt::AlignCenter);
        Item.at(2)->setTextAlignment(Qt::AlignCenter);
        //m_lineEidt[i]->installEventFilter(this);
        //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this));
        m_pModel->appendRow(Item);
    }
    if(items.count()>0)
        return true;
    else {
        return false;
    }
}
void  ControlBrightnessSchedule::OnClickExport()
{

    LoAppConfig *cfg = LoAppConfig::getInstance();
    QSettings *settings = new QSettings(cfg->OrganizationName(), cfg->ApplicationName());
    QString strDir="/";
    if(settings->value("lasOpendFileDlgtDir").isValid()) {
           strDir=settings->value("lasOpendFileDlgtDir").toString();
    }
    else {

    }
    QFileDialog dlg;
    QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("BrightnessSchedule (*.bjs)"));

    if( saveFileName.isEmpty() )
        return;
    settings->setValue("lasOpendFileDlgtDir",saveFileName);
    QJsonObject oTaskBrightness=GetJsonObjectBrightnessSchedule();
    QJsonDocument tBrightnessScheduleJsonDoc;
    tBrightnessScheduleJsonDoc.setObject(oTaskBrightness);


    QFile f(saveFileName);
    if(f.open(QIODevice::WriteOnly)) {
        f.write(tBrightnessScheduleJsonDoc.toJson());
        f.close();

    }
    delete settings;

}
void  ControlBrightnessSchedule::OnClickDelete()
{
   if(m_pModel->rowCount()>0)
   {
       QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0);
       if(selected.count()>0)
         m_pModel->removeRows(selected.begin()->row(),selected.count());
   }

}
void ControlBrightnessSchedule:: OnClickClear()
{
    //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0);

    if(m_pModel->rowCount()>0)
        m_pModel->removeRows(0,m_pModel->rowCount());

 }
void  ControlBrightnessSchedule::OnClickApply()
{
    if(ui->lineEdit->text().isEmpty())
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("DefaultInputTip"),this,1);
        pDlg->exec();
        ui->lineEdit->setFocus();
        return;
    }

    if(m_pLedlist==nullptr)
        return;

    if(m_pLedlist->count()<=1)
    {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0)
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
            pDlg->exec();
            return;
        }
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetAutoBrightnessTask");
    QJsonObject oTaskBrightness=GetJsonObjectBrightnessSchedule();
    json.insert("taskBrightness", oTaskBrightness);
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetAutoBrightnessTask"),tr("Success"),tr("failed"))

}
void  ControlBrightnessSchedule::OnClickReadback()
{
    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetAutoBrightnessTask");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetAutoBrightnessTask"),tr("Success"),tr("failed"))

}
QJsonObject ControlBrightnessSchedule::GetJsonObjectBrightnessSchedule()
{
    QJsonObject oTaskBrightness;
    QJsonArray oItems;

    oTaskBrightness["createDate"]          = QJsonValue::Null;
    oTaskBrightness["createBy"]            = "alahover";
    oTaskBrightness["name"]                = "TimingBrightness";
    oTaskBrightness["defaultBrightness"]   = ui->lineEdit->text().toInt();
    oTaskBrightness["brightness"]          = ui->lineEdit->text().toInt();

    for(int i=0; i<m_pModel->rowCount(); i++)
    {
        QJsonObject oItem;
        oItem["brightness"]         = m_pModel->data(m_pModel->index(i, 0)).toInt();

        QJsonArray oSchedules;
        QJsonObject oSchedule;
        oSchedule["timeType"]       = "Range";
        oSchedule["startTime"]      =  m_pModel->data(m_pModel->index(i, 1)).toString();;
        oSchedule["endTime"]        = m_pModel->data(m_pModel->index(i, 2)).toString();;
        oSchedule["dateType"]       = "All";
        oSchedule["startDate"]      = QJsonValue::Null;
        oSchedule["endDate"]        = QJsonValue::Null;
        oSchedule["monthFilter"]    = QJsonArray();
        oSchedule["filterType"]     = "None";
        oSchedule["weekFilter"]     = QJsonArray();
        oSchedules.append(oSchedule);
        oItem["schedules"]        = oSchedules;
        oItems.append(oItem);
    }

    oTaskBrightness["items"]               = oItems;
    return oTaskBrightness;

}
void  ControlBrightnessSchedule::OnAddOneItem(QString strStartTime,QString strEndTime,int iBrightnessValue)
{
    //int iIndex=m_pModel->rowCount();
   // QStanardItem
    QList<QStandardItem *> Item;
    Item.append(new QStandardItem(QString::number(iBrightnessValue)));
    Item.append(new QStandardItem(strStartTime));
    Item.append(new QStandardItem(strEndTime));

    Item.at(0)->setTextAlignment(Qt::AlignCenter);
    Item.at(1)->setTextAlignment(Qt::AlignCenter);
    Item.at(2)->setTextAlignment(Qt::AlignCenter);
    //m_lineEidt[i]->installEventFilter(this);
    //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this));
    m_pModel->appendRow(Item);
  //  ui->tableView->setModel(m_pModel);
//
}
void ControlBrightnessSchedule::DeletePostingDlg()
{
    if(m_PostingDlg!=nullptr)
    {
        delete m_PostingDlg;
        m_PostingDlg=nullptr;
    }
}
