#include "MainWidget.h"
#include "../component/FrequentShower.h"
#include "../component/TopMenuBar.h"
#include "../menu/BaseWidgetMenu.h"
#include "../subWidget/ServerSettingWidget.h"
#include "IntermediateFrequencyWidget.h"
#include "RadioWidget.h"
#include "SweepFrequencyWidget.h"
#include "Widget/base/export.h"
#include <QScreen>
#include <QTime>

#include "../FileDialog/FileExplorer.h"
Main_Widget::Main_Widget(QWidget *parent) : QWidget(parent) {
    setFocusPolicy(Qt::FocusPolicy::NoFocus);
    setObjectName("主界面");
    audioRecorder = new QAudioRecorder(this);
    audioRecorder->setAudioInput(audioRecorder->defaultAudioInput());
    QAudioEncoderSettings audio_settings;
    audio_settings.setCodec("audio/pcm");
    audio_settings.setQuality(QMultimedia::HighQuality);
    audio_settings.setSampleRate(44100);  // 设置采样率
    audio_settings.setChannelCount(2);    // 设置立体声
    audioRecorder->setAudioSettings(audio_settings);

    mediaPlayer = new QMediaPlayer(this);


    main_layout = new QVBoxLayout(this);
    main_layout->setMargin(8);
    main_layout->setSpacing(0);
    top_menu_bar = new Top_Menu_Bar();
    main_layout->addWidget(top_menu_bar, 1);
    radio_widget = new Radio_Widget;
    sweep_frequency_widget = new Sweep_Frequency_Widget;
    intermediate_frequency_widget = new Intermediate_Frequency_Widget;
    main_layout->addWidget(radio_widget, 31);
    main_layout->addWidget(sweep_frequency_widget, 31);
    main_layout->addWidget(intermediate_frequency_widget, 31);
    main_menu = new Base_Widget_Menu(this);
    main_menu->setObjectName("主菜单");
    top_menu = new Base_Widget_Menu(this);
    top_menu->setObjectName("顶部菜单");
    server_setting_widget = new Server_Setting_Widget(this);
    show_radio_widget();
    int font_size = 30;
    auto btn11 = new Menu_Button("电台模式", font_size, [&]() {
        show_radio_widget();
        main_menu->hide();
    });

    auto btn12 = new Menu_Button("中频模式", font_size, [&]() {
        show_intermediate_frequency_widget();
        main_menu->hide();
    });

    auto btn13 = new Menu_Button("扫频模式", font_size, [&]() {
        show_sweep_frequency_widget();
        main_menu->hide();
    });

    auto btn14 = new Menu_Button("服务端设置", font_size, [&]() {
        main_menu->hide();
        show_server_setting_widget();
    });
    select_shot_screen_dialog = new file_explorer();
    // select_shot_screen_dialog->setGeometry(QApplication::primaryScreen()->geometry());
    // select_shot_screen_dialog->setAcceptMode(QFileDialog::AcceptSave);
    // select_shot_screen_dialog->setOption(QFileDialog::DontUseNativeDialog, false);

    auto btn15 = new Menu_Button("截屏", font_size, [&]() {
        QTimer::singleShot(500, [this]() {
          QPixmap pixmap = this->grab();
          auto be = Back_End::instance();
          QString save_path = be->get_screenshot_save_dir_path() + be->get_screenshot_save_file_name();
          if(pixmap.save(save_path)) {
              qDebug() << "Screenshot saved successfully at" << save_path;
          }
          else {
              qDebug() << "Failed to save screenshot at" << save_path;
          }
        });
        // hide_cur_hover_widget();
        // current_hover_widget = select_shot_screen_dialog;
        // main_menu->hide();
        // QString default_file_name = "截屏" + QDateTime::currentDateTime().toString("yyyy年MM月dd日_hh：mm：ss");
        // select_shot_screen_dialog->selectFile(Back_End::instance()->getScreenshotPath() + default_file_name + ".png");
        // select_shot_screen_dialog->setFocus();
        // select_shot_screen_dialog->show();
        // if(select_shot_screen_dialog_first){
        //     select_shot_screen_dialog_first = false;
        //     auto that = select_shot_screen_dialog->findChild<QLineEdit*>();
        //     if(that){
        //         Toolbox::VirtualKeyBoard::instance()->setEdit(that);
        //         qDebug() << "设置成功!";
        //     }
        // }
        //
        // connect(select_shot_screen_dialog, &QFileDialog::fileSelected, [&](const QString &filePath) {
        //     QPixmap pixmap = this->grab();
        //     if (pixmap.save(filePath)) {
        //         qDebug() << "截屏保存到了" << filePath;
        //     } else {
        //         qDebug() << "截屏保存失败，路径不对" << filePath;
        //     }
        // });
    });

    auto be = Back_End::instance();
    select_audio_file = new file_explorer();
    select_audio_file->setParent(this);
    select_audio_file->hide();
    select_audio_file->setObjectName("选择音频文件播放");
    select_audio_file->change_root(be->get_audio_file_location());

    connect(select_audio_file->cancelButton, &QPushButton::clicked, [this]() {
        qDebug() << "播放音频已取消!";
        Main_Widget::instance()->get_current_base_widget()->setFocus();
        select_audio_file->hide();
    });
    connect(select_audio_file->confirmButton, &QPushButton::clicked, [this]() {
        QString path = select_audio_file->focus.absoluteFilePath();
        if(!path.endsWith(".wav")){
            qWarning() << "选择的文件结尾不是wav 选择的文件为" + path;
        }
        mediaPlayer->setMedia(QUrl::fromLocalFile(path));
        mediaPlayer->play();
        Main_Widget::instance()->get_current_base_widget()->setFocus();
        select_audio_file->hide();
    });
    auto btn21 = new Menu_Button("播放音频", font_size, [this]() {
        select_audio_file->setGeometry(rect());
        select_audio_file->show();
        select_audio_file->setFocus();
       // qDebug() << "2222222222222222";
        set_current_hover_widget(select_audio_file);
       // qDebug() << "2222222222222222";
    });


    auto btn22 = new Menu_Button("打卡sdk卡", font_size, [&](){

    });
    auto btn23 = new Double_Text_Menu_Button("开始录音", "停止录音", font_size, [&](bool is_first){
        if(is_first) {
            QString wav_path = "file:///" + QString(be->get_audio_file_location() + "%1.wav").arg(
            QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss"));
            audioRecorder->setOutputLocation(wav_path);
            if (audioRecorder->audioInput().isEmpty()) {
                qDebug() << "没有找到音频输入设备！";
            } else {
                qDebug() << "音频输入设备已设置。audioInput:" + audioRecorder->audioInput() +"  path:" + wav_path;
            }
            audioRecorder->record();
        } else {
            qDebug() << "停止录音" << audioRecorder->error() <<   audioRecorder->errorString();
            audioRecorder->stop();
        }
    });

    auto btn24 = new Double_Text_Menu_Button("开始发射", "停止发射", font_size, [&](bool is_first){
        if(is_first){

        } else {

        }
    });
    main_menu->add_menu_button_on_layout1({btn11, btn12, btn13, btn14, btn15});
    main_menu->add_menu_button_on_layout2({btn21, btn22, btn23, btn24}, 1);



    auto btnt21 = new Menu_Button("PRE", font_size, [&]() {
        qDebug() << "PRE 按下";
    });
    auto btnt22 = new Menu_Button("ATT", font_size, [&]() {
        qDebug() << "PRE 按下";
    });
    top_menu->add_menu_button_on_layout1({btnt21, btnt22}, 3);


#ifndef MockBackEnd
    showFullScreen();
#else
    showMaximized();
#endif
}

void Main_Widget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    //qDebug() << "Main_Widget::paintEvent" ;
    //painter.fillRect(rect(), Qt::red);
    painter.end();
}

void Main_Widget::show_intermediate_frequency_widget() const {
    sweep_frequency_widget->hide();
    radio_widget->hide();
    intermediate_frequency_widget->show();
    intermediate_frequency_widget->setFocus();
}

void Main_Widget::show_sweep_frequency_widget() const {
    intermediate_frequency_widget->hide();
    radio_widget->hide();
    sweep_frequency_widget->show();
    sweep_frequency_widget->setFocus();
}

void Main_Widget::show_radio_widget() const {
    intermediate_frequency_widget->hide();
    sweep_frequency_widget->hide();
    radio_widget->show();
    radio_widget->setFocus();
}

void Main_Widget::show_server_setting_widget(){
    server_setting_widget->raise();
    server_setting_widget->show();
    server_setting_widget->setFocus();
    set_current_hover_widget(server_setting_widget);

}

Base_Widget *Main_Widget::get_current_base_widget() const {
    if (radio_widget->isVisible()) return radio_widget;
    else if (sweep_frequency_widget->isVisible()) return sweep_frequency_widget;
    else return intermediate_frequency_widget;
}


void Main_Widget::set_current_hover_widget(QWidget* widget) {
    qDebug() << "set_current_hover_widget  pre" <<  ( current_hover_widget_value ? current_hover_widget_value->objectName() : "nullptr");
    qDebug() << "set_current_hover_widget  set" <<  ( widget ? widget->objectName() : "nullptr");
    if(current_hover_widget_value) {
        current_hover_widget_value->hide();
    }
    current_hover_widget_value = widget;
}



void Main_Widget::hide_cur_hover_widget() {
    qDebug() << "hide_cur_hover_widget() ";
    if(current_hover_widget_value){
        qDebug()  << current_hover_widget_value->objectName();
        current_hover_widget_value->hide();
        current_hover_widget_value = nullptr;
    }
}

void Main_Widget::resizeEvent(QResizeEvent *event) {
    server_setting_widget->resize(size());
    QWidget::resizeEvent(event);
}


void Main_Widget::keyPressEvent(QKeyEvent *event) {
    //qDebug()<<"Main_Widget::keyPressEvent"<<event->text();
    if (event->type() == QEvent::KeyPress) {
        Back_End* g = Back_End::instance();
        if(g->match(event, "主菜单")){
            if(!main_menu->isVisible()){
                hide_cur_hover_widget();
                int base_height = (int)((double)height() * 0.2);
                main_menu->setGeometry(0, height() - base_height, width(), base_height);
                main_menu->raise();
                main_menu->show();
                set_current_hover_widget(main_menu);
                main_menu->setFocus();
            } else {
                main_menu->hide();
                get_current_base_widget()->setFocus();
            }
        }
        if(g->match(event, "属性菜单")){
            get_current_base_widget()->reserver_menu();
            event->accept();
            return;
        }
        if(g->match(event, "顶部菜单")){
            if(!top_menu->isVisible()){
                hide_cur_hover_widget();
                int base_height = (int)((double)height() * 0.2);
                top_menu->setGeometry(0, 0, width(), base_height);
                top_menu->raise();
                top_menu->show();
                set_current_hover_widget(top_menu);
                top_menu->setFocus();
            } else {
                top_menu->hide();
                get_current_base_widget()->setFocus();
            }
        }
        if(g->match(event, "退出")){
            hide_cur_hover_widget();
            get_current_base_widget()->setFocus();
        }
    }
    event->accept();
}





void Main_Widget::wheelEvent(QWheelEvent *event) {
    event->accept();
}

