#include "controlhdmischedule.h"
#include "ui_controlhdmischedule.h"
#include "base/x_uimsgboxok.h"
#include "QFileDialog"
#include "QDir"
#include <QJsonValue>
#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"
ControlHdmiSchedule::ControlHdmiSchedule(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlHdmiSchedule)
{
    m_pLedlist=list;
    ui->setupUi(this);
    refreshLable();
setStyleSheet(Tools::styleSheet());
    ui->labelSyncScheduleTip->setVisible(false);

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

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


    ReadOnlyDelegate1* readOnlyDelegate = new ReadOnlyDelegate1();
    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()));
}

ControlHdmiSchedule::~ControlHdmiSchedule()
{
    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 ControlHdmiSchedule::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 ControlHdmiSchedule::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 ControlHdmiSchedule::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)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "GetHdminScheduleTask")
            {

            }
            else if(strType == "etHdminScheduleTask")
            {
            }

            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK

        }
    }
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlHdmiSchedule::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)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "GetHdminScheduleTask")
            {

            }
        }
    }
}

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

}
void  ControlHdmiSchedule::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->labelSyncScheduleTip->setVisible(true);
    }
    else {
        ui->labelSyncScheduleTip->setVisible(false);
    }
}
void  ControlHdmiSchedule::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("SyncSchedule (*.syncs)"));
    if(strBrightScheduleFile.isEmpty()) return;
    QFile fJson(strBrightScheduleFile);
    if(fJson.open(QIODevice::ReadOnly)){
        QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll());
        QJsonObject oTaskSync=jBrightSchedule.object();
        JieXiJsonTaskSync(oTaskSync);
        fJson.close();
    }
}
bool ControlHdmiSchedule::JieXiJsonTaskSync(QJsonObject oTaskSync)
{
    OnClickClear();
    QJsonArray oSchedules;
    oSchedules=oTaskSync["schedules"].toArray();
    if(oSchedules.count()>0)
    {
        ui->labelSyncScheduleTip->setVisible(true);
    }
    else
    {
        ui->labelSyncScheduleTip->setVisible(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  ControlHdmiSchedule::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("Sync Schedule (*.syncs)"));
    if( saveFileName.isEmpty() ) return;
    settings.setValue("lasOpendFileDlgtDir",saveFileName);
    QJsonObject oTaskSync=GetJsonObjectSyncSchedule();
    QJsonDocument tSyncScheduleJsonDoc;
    tSyncScheduleJsonDoc.setObject(oTaskSync);

    QFile f(saveFileName);
    if(f.open(QIODevice::WriteOnly)) {
        f.write(tSyncScheduleJsonDoc.toJson());
        f.close();
    }
}
void  ControlHdmiSchedule::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->labelSyncScheduleTip->setVisible(true);
    }
    else {
        ui->labelSyncScheduleTip->setVisible(false);
    }
}
void ControlHdmiSchedule:: 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->labelSyncScheduleTip->setVisible(true);
    }
    else {
        ui->labelSyncScheduleTip->setVisible(false);
    }
 }
void  ControlHdmiSchedule::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", "SetTimingHdmiInTask");
    QJsonObject oTaskSync=GetJsonObjectSyncSchedule();
    json.insert("HdmiInTask", oTaskSync);
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetTimingHdmiInTask"),tr("Success"),tr("failed"))

}
void  ControlHdmiSchedule::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", "GetTimingHdmiInTask");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetTimingHdmiInTask"),tr("Success"),tr("failed"))

}
QJsonObject ControlHdmiSchedule::GetJsonObjectSyncSchedule()
{
    QJsonObject oTaskSync;
    QJsonArray oItems;

    oTaskSync["createDate"]          = QJsonValue::Null;
    oTaskSync["createBy"]            = "alahover";
    oTaskSync["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);
    }

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

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