#include "controlvolumeschedule.h"
#include "ui_controlvolumeschedule.h"
#include "LoUIClass/x_uimsgboxok.h"
#include "QFileDialog"
#include "QDir"
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <globaldefine.h>
#include <QStandardItem>
#include "loappconfig.h"
#include "QSettings"
#include "LoUIClass/x_spinboxdelegate.h"
#include "LoUIClass/x_timeeditdelegate.h"
#include "LoUIClass/x_checkboxdelegate.h"
ControlVolumeSchedule::ControlVolumeSchedule(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlVolumeSchedule)
{
    m_pLedlist=list;
    ui->setupUi(this);
    refreshLable();

    ui->pushButtonAdd->setProperty("ssType", "progManageTool");
    ui->pushButtonAdd->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonAdd->setFlat(true);
    ui->pushButtonDelete->setProperty("ssType", "progManageTool");
    ui->pushButtonDelete->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonDelete->setFlat(true);
    ui->pushButtonClear->setProperty("ssType", "progManageTool");
    ui->pushButtonClear->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonClear->setFlat(true);
    ui->pushButtonApply->setProperty("ssType", "progManageTool");
    ui->pushButtonApply->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonApply->setFlat(true);
    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->pushButtonReadback->setProperty("ssType", "progManageTool");
    ui->pushButtonReadback->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->lineEdit->setText("10");
    m_pModel = new QStandardItemModel(this);
    m_pModel->setColumnCount(10);
    m_pModel->setHeaderData(0,Qt::Horizontal, tr("Volume value"));
    m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time"));
    m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time"));
    m_pModel->setHeaderData(3,Qt::Horizontal, tr("SUN"));
    m_pModel->setHeaderData(4,Qt::Horizontal, tr("MON"));
    m_pModel->setHeaderData(5,Qt::Horizontal, tr("TUE"));
    m_pModel->setHeaderData(6,Qt::Horizontal, tr("WED"));
    m_pModel->setHeaderData(7,Qt::Horizontal, tr("THU"));
    m_pModel->setHeaderData(8,Qt::Horizontal, tr("FRI"));
    m_pModel->setHeaderData(9,Qt::Horizontal, tr("SAT"));
    ui->tableView->setModel(m_pModel);
    SpinBoxDelegate *pVolumeDelegate=new SpinBoxDelegate(this,1);
    ui->tableView->setItemDelegateForColumn(0,pVolumeDelegate);

    X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this);
    ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate);
    ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate);
    X_CheckBoxDelegate *WeekDelegate=new X_CheckBoxDelegate(this);
    ui->tableView->setItemDelegateForColumn(3,WeekDelegate);
    ui->tableView->setItemDelegateForColumn(4,WeekDelegate);
    ui->tableView->setItemDelegateForColumn(5,WeekDelegate);
    ui->tableView->setItemDelegateForColumn(6,WeekDelegate);
    ui->tableView->setItemDelegateForColumn(7,WeekDelegate);
    ui->tableView->setItemDelegateForColumn(8,WeekDelegate);
    ui->tableView->setItemDelegateForColumn(9,WeekDelegate);


    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // ui->tableView->verticalHeader()->hide();
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setFocusPolicy(Qt::NoFocus);


    //  connect(parent->parent()->parent(),SIGNAL(sigSelectedDeviceList(QList<LedCard *> *)),this,SLOT(onSelectedDeviceList(QList<LedCard *> *)));
    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()));
}

ControlVolumeSchedule::~ControlVolumeSchedule()
{
    delete ui;
    if(pHpptClient != nullptr)
    {
        qDebug() <<"delete pHpptClient in ~NetComm";
        delete pHpptClient;
        pHpptClient=nullptr;
    }
    if(pHpptClientAll != nullptr)
    {
        qDebug() <<"delete pHpptClientAll in ~NetComm";
        delete pHpptClientAll;
        pHpptClientAll=nullptr;
    }
}
void ControlVolumeSchedule::refreshLable()
{
    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->labelVolumeScheduleTip->setText(tr("Default volume tip"));
    ui->labelDefalutVolume->setText(tr("Default volume"));

}

void ControlVolumeSchedule::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 ControlVolumeSchedule::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 == "GetAutoVolumeTask")
            {
                JieXiJsonTaskVolume(jsonObject["taskVolume"].toObject());
            }
            else if(strType == "SetAutoVolumeTask")
            {
            }

            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK

        }
    }
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlVolumeSchedule::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 == "GetAutoVolumeTask")
            {
                emit sigHaveSchedule(JieXiJsonTaskVolume(jsonObject["taskVolume"].toObject()));

            }
        }
    }
}

void ControlVolumeSchedule::OnControlTypeSwitchIndexChanged(int index)
{
    if(index==ENUM_CONTRL_WIDGET_VOLUME)
    {
        m_bSelected=true;
        if(m_pLedCard!=nullptr)
            onReadbackAllThisPage();
    }
    else {
        m_bSelected=false;
    }
}
void  ControlVolumeSchedule::onReadbackAllThisPage()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()!=1)
        return;
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetAutoVolumeTask");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json);

}
void  ControlVolumeSchedule::OnClickAdd()
{
    QList<QStandardItem *> Item;
    Item.append(new QStandardItem(tr("10")));
    Item.append(new QStandardItem("00:00"));
    Item.append(new QStandardItem("01:00"));
//    Item.append(new QStandardItem(true));
//    Item.append(new QStandardItem(true));
//    Item.append(new QStandardItem(true));
//    Item.append(new QStandardItem(true));
//    Item.append(new QStandardItem(true));
//    Item.append(new QStandardItem(true));
//    Item.append(new QStandardItem(true));

    Item.at(0)->setTextAlignment(Qt::AlignCenter);
    Item.at(1)->setTextAlignment(Qt::AlignCenter);
    Item.at(2)->setTextAlignment(Qt::AlignCenter);
    m_pModel->appendRow(Item);
    //m_lineEidt[i]->installEventFilter(this);
    //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this));
    int i=m_pModel->rowCount()-1;
    m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole);
    m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole);
    m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole);
    m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole);
    m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole);
    m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole);
    m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole);

    if(m_pModel->rowCount()>0)
    {
        ui->labelVolumeScheduleTip->setVisible(true);
    }
    else {
        ui->labelVolumeScheduleTip->setVisible(false);
    }

    //bool data = index.model()->data(index, Qt::UserRole).toBool();

//    ControlBrightnessScheduleEdit *pDlg=new ControlBrightnessScheduleEdit(this);
//    connect(pDlg,SIGNAL(sigAddOneItem(QString,QString,int)),this,SLOT(OnAddOneItem(QString,QString,int)));
//    pDlg->show();
}
void  ControlVolumeSchedule::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("Volume Schedule (*.vols)"));
    if(strBrightScheduleFile.isEmpty())
        return;
    QFile fJson(strBrightScheduleFile);
    if(fJson.open(QIODevice::ReadOnly)){
        QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll());
       QJsonObject oTaskVolume=jBrightSchedule.object();
       JieXiJsonTaskVolume(oTaskVolume);
        fJson.close();
    }
    delete settings;
}
bool ControlVolumeSchedule::JieXiJsonTaskVolume(QJsonObject oTaskVolume)
{
    OnClickClear();
    QJsonArray items;
    QString strDefaultVolume=QString::number(oTaskVolume["defaultVolume"].toInt());
    if(!strDefaultVolume.isEmpty())
        ui->lineEdit->setText(strDefaultVolume);
    items=oTaskVolume["items"].toArray();
    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["volume"].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(oSchedule["filterType"].toString()=="None")
        {
            m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole);
            m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole);
            m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole);
            m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole);
            m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole);
            m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole);
            m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole);
        }
        else if(oSchedule["filterType"].toString()=="Week")
        {
            QJsonArray oWeeks;
            oWeeks=oSchedule["weekFilter"].toArray();
            for(int m=0;m<7;m++)
            {
                bool bHave=false;
                for (int j=0;j<oWeeks.count();j++)
                {
                    int iWeek=oWeeks.at(j).toInt();
                    if(iWeek==m)
                    {
                        bHave=true;
                        break;
                    }

                }
                m_pModel->setData(m_pModel->index(i, m+3),bHave,Qt::UserRole);
            }
        }
    }
    if(items.count()>0)
        return true;
    else {
        return false;
    }
}
void  ControlVolumeSchedule::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("Volume Schedule (*.vols)"));

    if( saveFileName.isEmpty() )
        return;
    settings->setValue("lasOpendFileDlgtDir",saveFileName);
    QJsonObject oTaskSync=GetJsonObjectVolumeSchedule();
    QJsonDocument tSyncScheduleJsonDoc;
    tSyncScheduleJsonDoc.setObject(oTaskSync);


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

    }
    delete settings;

}
void  ControlVolumeSchedule::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());

    }
    if(m_pModel->rowCount()>0)
    {
        ui->labelVolumeScheduleTip->setVisible(true);
    }
    else {
        ui->labelVolumeScheduleTip->setVisible(false);
    }
}
void ControlVolumeSchedule:: OnClickClear()
{
    //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0);

    if(m_pModel->rowCount()>0)
        m_pModel->removeRows(0,m_pModel->rowCount());
    if(m_pModel->rowCount()>0)
    {
        ui->labelVolumeScheduleTip->setVisible(true);
    }
    else {
        ui->labelVolumeScheduleTip->setVisible(false);
    }
 }
void  ControlVolumeSchedule::OnClickApply()
{
    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", "SetAutoVolumeTask");
    QJsonObject oTaskVolume=GetJsonObjectVolumeSchedule();
    json.insert("taskVolume", oTaskVolume);
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetAutoVolumeTask"),tr("Success"),tr("failed"))

}
void  ControlVolumeSchedule::OnClickReadback()
{
    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", "GetAutoVolumeTask");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetAutoVolumeTask"),tr("Success"),tr("failed"))

}
QJsonObject ControlVolumeSchedule::GetJsonObjectVolumeSchedule()
{
    QJsonObject oTaskVolume;
    QJsonArray oItems;

    oTaskVolume["createDate"]          = QJsonValue::Null;
    oTaskVolume["createBy"]            = "alahover";
    oTaskVolume["defaultVolume"]   = ui->lineEdit->text().toInt();
    oTaskVolume["volume"]   = ui->lineEdit->text().toInt();
    oTaskVolume["name"]                = "TimingVolume";


    for(int i=0; i<m_pModel->rowCount(); i++)
    {
        QJsonObject oItem;
        oItem["volume"]         = 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();

        bool bSun=m_pModel->data(m_pModel->index(i, 3),Qt::UserRole).toBool();
        bool bMon=m_pModel->data(m_pModel->index(i, 4),Qt::UserRole).toBool();
        bool bTur=m_pModel->data(m_pModel->index(i, 5),Qt::UserRole).toBool();
        bool bWed=m_pModel->data(m_pModel->index(i, 6),Qt::UserRole).toBool();
        bool bThu=m_pModel->data(m_pModel->index(i, 7),Qt::UserRole).toBool();
        bool bFri=m_pModel->data(m_pModel->index(i, 8),Qt::UserRole).toBool();
        bool bSat=m_pModel->data(m_pModel->index(i, 9),Qt::UserRole).toBool();


        if(bMon && bTur && bWed && bThu && bFri && bSat && bSun)
        {
            oSchedule["filterType"]     = "None";
            oSchedule["weekFilter"]     = QJsonArray();

        }
        else {
            oSchedule["filterType"]     = "Week";
            QJsonArray tempArray;
            if( bSun)
            {
                tempArray.append(0);
            }
            if(bMon)
            {
                tempArray.append(1);
            }
            if(bTur)
            {
                tempArray.append(2);
            }
            if( bWed)
            {
                tempArray.append(3);
            }
            if( bThu)
            {
                tempArray.append(4);
            }
            if( bFri)
            {
                tempArray.append(5);
            }
            if( bSat)
            {
                tempArray.append(6);
            }


            oSchedule["weekFilter"]     = tempArray;

        }


        oSchedules.append(oSchedule);
        oItem["schedules"]        = oSchedules;
        oItems.append(oItem);
    }

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

}
void ControlVolumeSchedule::DeletePostingDlg()
{
    if(m_PostingDlg!=nullptr)
    {
        delete m_PostingDlg;
        m_PostingDlg=nullptr;
    }
}
