#include "FormHome.h"
#include "ui_FormHome.h"

#include <QDebug>
#include <QShowEvent>

#include "workspace/home/FormStandby.h"

#include "workspace/settings/FormSettings.h"
#include "workspace/settings/general/FormGeneralSettings.h"
#include "workspace/settings/device/FormDeviceInfo.h"
#include "workspace/settings/key/FormConfigurationKey.h"
#include "workspace/settings/charging/FormChargeRecords.h"
#include "workspace/settings/firmware/FormFirmwareInfo.h"
#include "workspace/settings/transfer/FormTransfer.h"
#include "workspace/settings/log/FormLogView.h"
#include "workspace/settings/log/FormLogShow.h"
#include "workspace/settings/payment/FormPayment.h"
#include "workspace/settings/general/FormLanguageConfig.h"
#include "workspace/settings/general/FormPasswordManage.h"
#include "workspace/settings/general/FormChargingSetup.h"

#include "LanguageManager.h"

FormHome::FormHome(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::FormHome)
    , m_currentForm(workspace_form_enum::STANDBY)
{
    ui->setupUi(this);

    // 安装事件过滤器到应用程序对象
    qApp->installEventFilter(this);
}

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

void FormHome::init()
{
    initWidget();

    setupConnections();
}

void FormHome::initWidget()
{
    m_login = new FormLogin();
    // 设置父窗口
    m_login->setParent(this);
    // 设置为独立窗口
    m_login->setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    // 设置为应用程序的模态窗口，阻止本应用所有窗口的输入
    m_login->setWindowModality(Qt::WindowModal);

    m_formMap[STANDBY]              = new FormStandby();
    m_formMap[SETTINGS]             = new FormSettings();
    m_formMap[GENERAL_SETTINGS]     = new FormGeneralSettings();
    m_formMap[DEVICE_INFORMATION]   = new FormDeviceInfo();
    m_formMap[CONFIGURATION_KEY]    = new FormConfigurationKey();
    m_formMap[CHARGING_RECORDS]     = new FormChargeRecords();
    m_formMap[FIRMWARE_INFORMATION] = new FormFirmwareInfo();
    m_formMap[IMPORT_EXPORT]        = new FormTransfer();
    m_formMap[LOG_VIEW]             = new FormLogView();
    m_formMap[LOG_SHOW]             = new FormLogShow();
    m_formMap[PAYMENT]              = new FormPayment();
    m_formMap[LANGUAGE]             = new FormLanguageConfig();
    m_formMap[ADMIN_PWD]            = new FormPasswordManage();
    m_formMap[CHARGING_SETUP]       = new FormChargingSetup();

    // 添加页面到堆叠窗口并隐藏
    auto widgets = m_formMap.values();
    foreach (const auto& widget, std::as_const(widgets)) {
        ui->workspace->addWidget(widget);

        // 强制布局系统更新
        ui->workspace->updateGeometry();
    }

    // 显示初始页面
    showForm(STANDBY);
}

void FormHome::setupConnections()
{
    // 自定义标题栏 settings 按钮点击事件
    connect(ui->titleBar, &TitleBar::showLogin, this, [=]() {
        m_login->show();
    });

    // 自定义标题栏 return 按钮点击事件
    connect(ui->titleBar, &TitleBar::signalReturn, this, [this]() {
        BaseWidget *widget = qobject_cast<BaseWidget *>(ui->workspace->currentWidget());
        if (!widget) return;
        if (widget->returnParent()) {
            setPrevForm();          // 设置前一页面为 STANDBY
            showForm(m_prevForm);   // 需要维护历史记录
        }
    });

    // 显示 settings 界面事件
    connect(m_login, &FormLogin::showSetings, this, [=]() { showForm(SETTINGS); });

    // 设置页面信号统一处理
    auto settings = qobject_cast<FormSettings*>(m_formMap[SETTINGS]);
    const QVector<QPair<void (FormSettings::*)(), workspace_form_enum>> settingsSignals = {
        {&FormSettings::showGeneralSettings,    GENERAL_SETTINGS},
        {&FormSettings::showDeviceInformation,  DEVICE_INFORMATION},
        {&FormSettings::showConfigurationKey,   CONFIGURATION_KEY},
        {&FormSettings::showChargingRecords,    CHARGING_RECORDS},
        {&FormSettings::showFirmwareInfo,       FIRMWARE_INFORMATION},
        {&FormSettings::showTransfer,           IMPORT_EXPORT},
        {&FormSettings::showLogView,            LOG_VIEW},
        {&FormSettings::showPayment,            PAYMENT},
    };

    for (const auto& signal : std::as_const(settingsSignals)) {
        connect(settings, signal.first, this, [=]() {
            m_prevForm = m_currentForm;
            showForm(signal.second);
        });
    }

    // auto standby_form = qobject_cast<FormStandby*>(m_formMap[STANDBY]);
    // connect(standby_form, &FormStandby::signalError, this, [](int error_code, const QString& message) {
    //     LoggerHelper::instance()->warning(QString("%1 : %2").arg(message, QString::number(error_code)));
    // });

    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });

    auto generalSetting = qobject_cast<FormGeneralSettings*>(m_formMap[GENERAL_SETTINGS]);
    connect(generalSetting, &FormGeneralSettings::generalSettingClicked, this, [this](const int& index) {
        m_prevForm = m_currentForm;
        showForm(getGeneralSettingForm(index));
    });

    auto logSetting = qobject_cast<FormLogView*>(m_formMap[LOG_VIEW]);
    connect(logSetting, &FormLogView::itemClicked, this, [this](const int& type) {
        m_prevForm = m_currentForm;
        auto logShow = qobject_cast<FormLogShow*>(m_formMap[LOG_SHOW]);
        logShow->setLogType(type);
        showForm(LOG_SHOW);
    });
}

void FormHome::showForm(workspace_form_enum form)
{
    if (!m_formMap.contains(form)) {
        return;
    }

    m_currentForm = form;
    ui->workspace->setCurrentWidget(m_formMap[form]);

    // 更新标题栏状态
    ui->titleBar->setSettingsEnable(form < SETTINGS);
    ui->titleBar->setReturnVisible(form != STANDBY);

    // 更新标题栏标题
    ui->titleBar->setTitle(m_formMap[form]->windowTitle());
}

void FormHome::setPrevForm()
{
    switch (m_currentForm) {
    case SETTINGS:          m_prevForm = STANDBY; break;
    case GENERAL_SETTINGS:
    case DEVICE_INFORMATION:
    case CONFIGURATION_KEY:
    case CHARGING_RECORDS:
    case FIRMWARE_INFORMATION:
    case IMPORT_EXPORT:
    case LOG_VIEW:
    case PAYMENT:
        m_prevForm = SETTINGS;
        break;
    default:
        break;
    }
}

workspace_form_enum FormHome::getGeneralSettingForm(const int &index)
{
    switch (index) {
    case General::Form::LANGUAGE:           return LANGUAGE;
    case General::Form::ADMIN_PWD:          return ADMIN_PWD;
    case General::Form::CHARGING_SETUP:     return CHARGING_SETUP;
    default:                                return GENERAL_SETTINGS;
    }

    return GENERAL_SETTINGS;
}

void FormHome::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    // ui->retranslateUi(this);
}

