#include "controlpowerschedule.h"
#include "ui_controlpowerschedule.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <globaldefine.h>
#include <QStandardItem>
#include "cfg.h"
#include "QSettings"
#include "base/x_spinboxdelegate.h"
#include "base/x_timeeditdelegate.h"
#include "base/x_checkboxdelegate.h"
#include "tools.h"

ControlPowerSchedule::ControlPowerSchedule(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlPowerSchedule)
{
    m_pLedlist=list;
    ui->setupUi(this);
    ui->labelPowerScheduleTip->setVisible(false);
    refreshLable();
setStyleSheet(css);
    ui->pushButtonAdd->setProperty("ssType", "progManageTool");
    ui->pushButtonAdd->setFlat(true);
    ui->pushButtonDelete->setProperty("ssType", "progManageTool");
    ui->pushButtonDelete->setFlat(true);
    ui->pushButtonClear->setProperty("ssType", "progManageTool");
    ui->pushButtonClear->setFlat(true);
    ui->pushButtonApply->setProperty("ssType", "progManageTool");
    ui->pushButtonApply->setFlat(true);
    ui->pushButtonImport->setProperty("ssType", "progManageTool");
    ui->pushButtonExport->setProperty("ssType", "progManageTool");
    ui->pushButtonReadback->setProperty("ssType", "progManageTool");
    ui->pushButtonClearSchedule->setProperty("ssType", "progManageTool");

    m_pModel = new QStandardItemModel(this);
    m_pModel->setColumnCount(10);
    m_pModel->setHeaderData(0,Qt::Horizontal, tr("Power On State"));
    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);

    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);


    ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate();
    ui->tableView->setItemDelegateForColumn(0, readOnlyDelegate); //设置某列只读

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


    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()));
    connect(ui->pushButtonClearSchedule,SIGNAL(clicked()),this,SLOT(OnClickClearSchedule()));


}

ControlPowerSchedule::~ControlPowerSchedule()
{
    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 ControlPowerSchedule::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"));
}

void ControlPowerSchedule::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 ControlPowerSchedule::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("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            if(strType == "GetTimingScreenTask")
            {
                JieXiJsonTaskPower(jsonObject["screenTask"].toObject());
            }
            else if(strType == "SetTimingScreenTask")
            {
            }

            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK

        }
    }
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlPowerSchedule::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("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            if(strType == "GetTimingScreenTask")
            {
                emit sigHaveSchedule(JieXiJsonTaskPower(jsonObject["screenTask"].toObject()));
            }
        }
    }
}

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

}
void  ControlPowerSchedule::OnClickAdd()
{
    QList<QStandardItem *> Item;
    Item.append(new QStandardItem(tr("On")));
    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->labelPowerScheduleTip->setVisible(true);

    }
    else {
        ui->labelPowerScheduleTip->setVisible(false);

    }
}
void  ControlPowerSchedule::OnClickImport(){
    QSettings settings;
    QString strDir="/";
    if(settings.value("lasOpendFileDlgtDir").isValid())
    {
           strDir=settings.value("lasOpendFileDlgtDir").toString();
    }
    QFileDialog dlg;
    QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog",
                                             strDir,
                                             tr("PowerSchedule (*.pjs)"));
    if(strBrightScheduleFile.isEmpty())
        return;
    QFile fJson(strBrightScheduleFile);
    if(fJson.open(QIODevice::ReadOnly)){
        QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll());
       QJsonObject oTaskPower=jBrightSchedule.object();
       JieXiJsonTaskPower(oTaskPower);
        fJson.close();
    }
}
bool ControlPowerSchedule::JieXiJsonTaskPower(QJsonObject oTaskPower)
{
    OnClickClear();
    QJsonArray oSchedules;
    oSchedules=oTaskPower["schedules"].toArray();
    if(oSchedules.count()>0)
    {
        ui->labelPowerScheduleTip->setVisible(true);
    }
    else
    {
        ui->labelPowerScheduleTip->setVisible(false);
    }
    //bool bHaveSchedule=false;
    for(int i=0;i<oSchedules.count();i++)
    {
        QJsonObject oSchedule=oSchedules.at(i).toObject();
         QList<QStandardItem *> Item;
        Item.append(new QStandardItem(tr("On")));
        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_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(oSchedules.count()>0)
        return true;
    else {
        return false;
    }
}
void  ControlPowerSchedule::OnClickExport(){
    QSettings settings;
    QString strDir="/";
    if(settings.value("lasOpendFileDlgtDir").isValid()) {
           strDir=settings.value("lasOpendFileDlgtDir").toString();
    }
    QFileDialog dlg;
    QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("PowerSchedule (*.pjs)"));

    if( saveFileName.isEmpty() )
        return;
    settings.setValue("lasOpendFileDlgtDir",saveFileName);
    QJsonObject oTaskPower=GetJsonObjectPowerSchedule();
    QJsonDocument tPowerScheduleJsonDoc;
    tPowerScheduleJsonDoc.setObject(oTaskPower);

    QFile f(saveFileName);
    if(f.open(QIODevice::WriteOnly)) {
        f.write(tPowerScheduleJsonDoc.toJson());
        f.close();
    }
}
void  ControlPowerSchedule::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->labelPowerScheduleTip->setVisible(true);
    }
    else {
        ui->labelPowerScheduleTip->setVisible(false);
    }
}
void ControlPowerSchedule:: 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->labelPowerScheduleTip->setVisible(true);

    }
    else {
        ui->labelPowerScheduleTip->setVisible(false);

    }
}
extern QWidget *gMainWin;
void ControlPowerSchedule::OnClickApply() {
    if(m_pLedlist==nullptr) return;
    if(m_pLedlist->count()<=1){
        if(m_pLedCard==nullptr||m_pLedlist->count()==0){
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
    }
    if(m_pModel->rowCount()<=0) {
        auto btn = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Clear schedule task?"));
        if(btn == QMessageBox::Yes) {
            QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "CleanTimingScreenTask");
            MACRO_DEFINE_TIPDLG_FUCN(tr("CleanTimingScreenTask"),tr("Success"),tr("failed"))
        }
    } else {
        QJsonObject json;
        json.insert("_id", getRandomString(10));
        json.insert("_type", "SetTimingScreenTask");
        QJsonObject oTaskPower=GetJsonObjectPowerSchedule();
        json.insert("screenTask", oTaskPower);
        MACRO_DEFINE_TIPDLG_FUCN(tr("SetTimingScreenTask"),tr("Success"),tr("failed"))
    }

}
void  ControlPowerSchedule::OnClickReadback() {
    if(m_pLedlist==nullptr) return;
    if(m_pLedlist->count()<=1) {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("NoSelectedController"));
            return;
        }
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetTimingScreenTask");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetTimingScreenTask"),tr("Success"),tr("failed"))

}
void ControlPowerSchedule::OnClickClearSchedule()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()<=1)
    {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0)
        {
            QMessageBox::information(gMainWin, tr("Tip"),tr("NoSelectedController"));
            return;
        }
    }
    auto btn = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Clear schedule task?"));
    if(btn == QMessageBox::Yes) {
        QJsonObject json;
        json.insert("_id", getRandomString(10));
        json.insert("_type", "CleanTimingScreenTask");
        MACRO_DEFINE_TIPDLG_FUCN(tr("CleanTimingScreenTask"),tr("Success"),tr("failed"))
    }
}
QJsonObject ControlPowerSchedule::GetJsonObjectPowerSchedule()
{
    QJsonObject oTaskPower;
    QJsonArray oItems;

    oTaskPower["createDate"]          = QJsonValue::Null;
    oTaskPower["createBy"]            = "alahover";
    oTaskPower["name"]                = "TimingScreen";

    QJsonArray oSchedules;
    for(int i=0; i<m_pModel->rowCount(); i++)
    {

        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);
    }

    oTaskPower["schedules"]               = oSchedules;
    return oTaskPower;

}

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