#include "formhistory.h"
#include "ui_formhistory.h"

#include "commondata.h"
#include "mainwindow.h"
#include "dialogcalendar.h"
#include "formcalendarview.h"

FormHistory::FormHistory(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormHistory)
{
    ui->setupUi(this);

    ui->widgetList->ChangeHeader();

    ui->pushButton_DateEnd->hide();

    m_nSearchDurationType = 0;
}

FormHistory::~FormHistory()
{
    delete ui;
}

void FormHistory::ClickSearchDateStartEnd()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    QDate dateStart = pCommonData->GetDateSearchHistoryStart();
    QDate dateEnd = pCommonData->GetDateSearchHistoryEnd();

    QDate date = QDate::currentDate();

    if(m_nSearchDurationType==0)
    {

    }

    DialogCalendar dlg(this);
    dlg.SetCalendarDate(date.year(), date.month(), 1);
    dlg.SetDateStart(dateStart);
    dlg.SetDateEnd(dateEnd);
    //dlg.SetModeChangeStart();

    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    pMainWindow->StopScreenSaverTimer();

    connect(&dlg, SIGNAL(SetSearchDateUpdate(int)), this, SLOT(SetSearchDateUpdate(int)));

    dlg.exec();
    m_nSearchDurationType = dlg.GetTypeSearchDuration();

    disconnect(&dlg, SIGNAL(SetSearchDateUpdate(int)), this, SLOT(SetSearchDateUpdate(int)));

    pMainWindow->ResetScreenSaverTimer();
    pMainWindow->StartScreenSaverTimer();
}

void FormHistory::on_pushButton_DateStart_clicked()
{
    WRITE_FUNCTION_LOG();
    ClickSearchDateStartEnd();

}

void FormHistory::on_pushButton_DateEnd_clicked()
{
    WRITE_FUNCTION_LOG();
    ClickSearchDateStartEnd();
}

void FormHistory::SetSearchDateUpdate(int nTypeSearchDuration)
{
    WRITE_FUNCTION_LOG();
    CommonData* pCommonData = MainWindow::GetCommonData();
    //QDate dateStart = pMainWindow->GetDateSearchWorklistStart();// FormCalendarView::GetDateStart();
    //QDate dateEnd = pMainWindow->GetDateSearchWorklistEnd();// FormCalendarView::GetDateEnd();
    QDate dateStart = FormCalendarView::GetDateStart();
    QDate dateEnd = FormCalendarView::GetDateEnd();
    QDate dateToday = QDate::currentDate();

    m_nSearchDurationType = nTypeSearchDuration;

    pCommonData->GetSearchDateStartEnd(m_nSearchDurationType, dateStart, dateEnd);
    pCommonData->SetDateSearchHistoryStart(dateStart);
    pCommonData->SetDateSearchHistoryEnd(dateEnd);

    QString strDateStart;
    QString strDateEnd;

    int nStartYear = dateStart.year();
    int nStartMonth = dateStart.month();
    int nStartDay = dateStart.day();

    int nEndYear = dateEnd.year();
    int nEndMonth = dateEnd.month();
    int nEndDay = dateEnd.day();

    strDateStart = QString("%1/%2/%3").arg(QString::number(nStartYear).rightJustified(4, '0')).arg(QString::number(nStartMonth).rightJustified(2, '0')).arg(QString::number(nStartDay).rightJustified(2, '0'));

    strDateEnd = QString("%1/%2/%3").arg(QString::number(nEndYear).rightJustified(4, '0')).arg(QString::number(nEndMonth).rightJustified(2, '0')).arg(QString::number(nEndDay).rightJustified(2, '0'));

    if(dateToday==dateStart)
    {
        ui->label_DateStart->setText("Today");
    }
    else
    {
        QString strSearchDate = QString("%1 ~ %2").arg(strDateStart).arg(strDateEnd);
        ui->label_DateStart->setText(strSearchDate);
    }

    if(dateToday==dateEnd)
    {
        ui->label_DateEnd->setText("Today");
    }
    else
    {
        ui->label_DateEnd->setText(strDateEnd);
    }


    SEARCH_ITEM* pSearchItem = pCommonData->GetSearchItemHistory();
    pSearchItem->m_strStudyDate = QString("%1-%2").arg(strDateStart).arg(strDateEnd);
}




void FormHistory::on_pushButton_Search_clicked()
{
    WRITE_FUNCTION_LOG();
    CommonData* pCommonData = MainWindow::GetCommonData();
    QDate dateStart = pCommonData->GetDateSearchHistoryStart();
    QDate dateEnd = pCommonData->GetDateSearchHistoryEnd();
    SDatabase* pDatabase = NULL;
    SEARCH_ITEM si;

    pCommonData->GetSearchDateStartEnd(m_nSearchDurationType, dateStart, dateEnd);
    pCommonData->SetDateSearchHistoryStart(dateStart);
    pCommonData->SetDateSearchHistoryEnd(dateEnd);

    pCommonData->ClearHistorySearchResult();

    QDate dt = QDate::currentDate();
    int nYear = dt.year();
    int nMonth = dt.month();
    int nDay = dt.day();


    QString strSearchDate;
    if(dateStart.isValid()==true)
    {
    }
    else
    {
        strSearchDate = QString("%1/%2/%3").arg(nYear, 4, 10, QChar('0')).arg(nMonth, 2, 10, QChar('0')).arg(nDay, 2, 10, QChar('0'));
    }

    if(dateEnd.isValid()==true)
    {

    }
    else
    {
        strSearchDate += QString("-%1/%2/%3").arg(nYear, 4, 10, QChar('0')).arg(nMonth, 2, 10, QChar('0')).arg(nDay, 2, 10, QChar('0'));
    }

    if(strSearchDate.length()<21)
    {
        QDate dt = dateStart;
        int nYear = dt.year();
        int nMonth = dt.month();
        int nDay = dt.day();

        strSearchDate += QString("%1/%2/%3").arg(nYear, 4, 10, QChar('0')).arg(nMonth, 2, 10, QChar('0')).arg(nDay, 2, 10, QChar('0'));

        dt = dateEnd;
        nYear = dt.year();
        nMonth = dt.month();
        nDay = dt.day();
        strSearchDate += QString("-%1/%2/%3").arg(nYear, 4, 10, QChar('0')).arg(nMonth, 2, 10, QChar('0')).arg(nDay, 2, 10, QChar('0'));
    }


    si.m_strStudyDate = strSearchDate;

    si.m_strPatientName = ui->plainTextEdit_PatientName->toPlainText();
    si.m_strPatientID = ui->plainTextEdit_PatientID->toPlainText();


    // 1. 결과를 담을 벡터를 먼저 가져옵니다. (기존 데이터를 비우는 처리는 ClearHistorySearchResult에서 담당)
    vector<HISTORY_STUDY*>* pListHistorySearch = pCommonData->GetHistorySearchResult();
    // pCommonData->ClearHistorySearchResult(); // 필요하다면 여기서 기존 결과를 비웁니다.

    // 2. 이 작업을 위한 지역 DB 인스턴스를 생성하고 연결합니다.
    SUTIL::SDatabase db(QString("GetHistoryStudyTask_%1").arg(reinterpret_cast<quintptr>(this)));
    if (db.OpenDatabase("/home/birdhead/test.db") == 0) // 0이 성공
    {
        // 3. 새로운 API를 호출하여 결과 리스트 "값"을 직접 받습니다.
        //    (bWithDelete는 false라고 가정)
        QList<QStringList> result = db.GetHistoryStudy(&si, false);

        // 4. 새로운 range-based for 문으로 코드를 더 간결하게 만듭니다.
        for (const QStringList& rowData : result)
        {
            HISTORY_STUDY* pHistoryStudy = new HISTORY_STUDY;

            // 컬럼 순서가 일치한다고 가정하고 데이터를 복사합니다.
            // SDI_TOTAL은 m_List의 크기를 넘어가지 않도록 하는 안전장치입니다.
            for (int j = 0; j < rowData.size() && j < SDI_TOTAL; ++j)
            {
                QString* pData = pHistoryStudy->m_List[j];
                if (pData) { // 포인터 유효성 검사
                    *pData = rowData.at(j);
                }
            }
            pListHistorySearch->push_back(pHistoryStudy);
        }
    }
    else
    {
        qWarning() << "DB open failed for GetHistoryStudy.";
    }

    /*
    pDatabase = pCommonData->GetDatabase();
    pDatabase->GetHistoryStudy(&si);

    vector<HISTORY_STUDY*>* pListHistorySearch = pCommonData->GetHistorySearchResult();
    QList<QStringList*>* pResult = pDatabase->GetResult();


    int i=0;

    for(i=0 ; i<pResult->size() ; i++)
    {
        HISTORY_STUDY* pHistoryStudy = new HISTORY_STUDY;
        pListHistorySearch->push_back(pHistoryStudy);

        QStringList* pListData = (*pResult)[i];
        int j=0;
        for(j=0 ; j<pListData->size() ; j++)
        {
            QString* pData = pHistoryStudy->m_List[j];
            *pData = (*pListData)[j];
        }
    }

    pCommonData->ReleaseDatabase();
    */

    Init();
}

void FormHistory::Init()
{
    WRITE_FUNCTION_LOG();
    ui->widgetList->Clear();
    ui->widgetList->ChangeHeader();

    ui->widgetList->UpdateHistoryList();
    ui->widgetList->Init();
}


void FormHistory::resizeEvent(QResizeEvent *event)
{
    WRITE_FUNCTION_LOG();
    int nDisplayType = MainWindow::GetCommonData()->GetDisplayType();

    int nFontSize = 22;
    if(nDisplayType==SDISPLAY_1280X1024)
    {
        nFontSize = 16;

        ui->frame_PatientID->setGeometry(20, 28, 156, 32);
        ui->frame_PatientName->setGeometry(195, 28, 156, 32);
        ui->pushButton_DateStart->setGeometry(376, 28, 278, 32);
        //ui->
        ui->pushButton_DateEnd->setGeometry(580, 28, 178, 32);

        ui->plainTextEdit_PatientID->setGeometry(30, 31, 140, 40);
        ui->plainTextEdit_PatientName->setGeometry(205, 31, 140, 40);

        ui->label_DateStart->setGeometry(18, 0, 260, 36);
        ui->label_DateEnd->setGeometry(18, 0, 160, 36);

        ui->widgetList->setGeometry(20, 91, 1150, 665);

        ui->pushButton_USBExport->setGeometry(20, 91+665+30, 145, 45);


        ui->pushButton_Search->setGeometry(1025, 21, 145, 45);
    }
    else if(nDisplayType==SDISPLAY_1920X1080)
    {
        ui->frame_PatientID->setGeometry(30, 34, 195, 40);
        ui->frame_PatientName->setGeometry(250, 34, 195, 40);
        ui->pushButton_DateStart->setGeometry(477, 34, 268, 40);
        ui->pushButton_DateEnd->setGeometry(770, 34, 268, 40);

        ui->plainTextEdit_PatientID->setGeometry(40, 40, 175, 50);
        ui->plainTextEdit_PatientName->setGeometry(260, 40, 175, 50);

        ui->label_DateStart->setGeometry(20, 0, 201, 40);
        ui->label_DateEnd->setGeometry(20, 0, 201, 40);

        ui->widgetList->setGeometry(30, 108, 1750, 640);

        ui->pushButton_Search->setGeometry(1600, 24, 180, 56);
    }

    QString strPushButton = QString(
    "QPushButton \
    { \
           background: #153B44; \
           font-family: 'Roboto'; \
           font-size: %1px; \
           font-weight: bold; \
           border-radius: 8px; \
           color: white; \
    } \
     \
    QPushButton:pressed \
    { \
           background: #1B4C54; \
    }").arg(nFontSize);

    ui->pushButton_Search->setStyleSheet(strPushButton);



}

#include "dialogexportusb.h"

void FormHistory::on_pushButton_USBExport_clicked()
{
    WRITE_FUNCTION_LOG();
    ui->widgetList->GetExportList();

    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<QString>* pListExport = pCommonData->GetExportList();

    if(pListExport->size()==0)
    {
        return;
    }
    DialogExportUSB dlg(this);

    int nRet = dlg.exec();
}

void FormHistory::keyReleaseEvent(QKeyEvent *event)
{
    WRITE_FUNCTION_LOG();
    int nKey = event->key();

    SThreadImageSave* pThread = MainWindow::GetCommonData()->GetThreadCaptureImage();

    if(nKey==Qt::Key_F10)
    {
        pThread->MissCapture();
    }
    else if(nKey==Qt::Key_F11)
    {
        pThread->MissCapture();
    }

}
