#include "dialoglogin.h"
#include "ui_dialoglogin.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QSettings>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include "appserial.h"
#include "modbusrtu.h"
#include <windef.h>
#include <QTranslator>
#include <QThread>
#include <QMetaType>

DialogLogin::DialogLogin(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DialogLogin)
{
    ui->setupUi(this);
    qRegisterMetaType<QList<int>>("QList<int>");
    init();
    serialInit();
    mainwindowInit();
}

DialogLogin::~DialogLogin()
{
    delete ui;
    free(m_MainWindow);
    free(m_Serial);
    free(m_ModbusRTU);
}

void DialogLogin::init()
{
    /*  设置标题  */
    setWindowTitle("Login");
    /*  设置Logo  */
    setWindowIcon(QIcon(":/Image/icon.png"));
    /*  隐藏Dialog问号按钮  */
    setWindowFlags(Qt::WindowCloseButtonHint);
    /*  设置模态化，无法选中其他界面  */
    setModal(true);
    /*  设置固定大小  */
    // setFixedSize(260, 320);

    /*  实例化对象  */
    m_MainWindow = new MainWindow;
    // m_MainWindow->show();
    m_Serial = new AppSerial;
    m_Serial->setHWND((HWND)this->winId());
    m_ModbusRTU = new ModbusRTU;

    ini = new QSettings("config.ini", QSettings::IniFormat);
    connect(ui->btnConnect, &QPushButton::clicked, this, &DialogLogin::slot_btnConnect_clicked);

    ui->groupBox->setStyleSheet("QGroupBox { border: none; }");

    ui->label_bluesunLogo->setStyleSheet("QLabel { background-image: url(:/Image/bluesun.png); "
                                         "background-repeat: no-repeat; background-size: cover; background-position: center center;}");
    // //将背景设置为白色
    // ui->groupBox->setStyleSheet("background-color: #FFFFFF;");

    m_MainWindow->setStyleSheet("background-color: #FFFFFF;");

    // //传递BCU个数的信号与槽
    // BCUNumbers = ui->comboBoxBCUQuantity->currentText().toInt();
    // qDebug() << "the number of the BCU: " << BCUNumbers;
    // emit sendBCUNumberSignals(BCUNumbers);

    // connect(ui->comboBoxBCUQuantity, &QComboBox::currentTextChanged, m_MainWindow, [&]{
    //     BCUNumbers = ui->comboBoxBCUQuantity->currentText().toInt();
    //     emit sendBCUNumberSignals(BCUNumbers);
    // });

    connect(this, &DialogLogin::sendBCUNumberSignals, m_MainWindow, &MainWindow::slot_getBcuNumberFromDialoglogin);

    //报文的信号与槽的连接
    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_sgl_tempt, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info1_45, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info57_78, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info83_106, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);

    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData, m_MainWindow, &MainWindow::slot_pageHomeSglDataMessage);

    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_sgl_tempt, m_MainWindow, &MainWindow::slot_pageHomeSglTempt);

    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info1_45, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo1_45);

    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info57_78, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo57_78);

    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info83_106, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo83_106);

    connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info_list_47_49_51_53_55, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo47_49_51_53_55);

    //写寄存器的信号与槽的连接
    connect(m_MainWindow, &MainWindow::write_regs_signals, m_ModbusRTU, &ModbusRTU::write_regs_slot);

    //读寄存器的信号与槽的连接
    connect(m_MainWindow, &MainWindow::read_regs_signals, m_ModbusRTU, &ModbusRTU::read_regs_slot);
    connect(m_ModbusRTU, &ModbusRTU::sig_showReadHoldingRegs, m_MainWindow, &MainWindow::slot_pageParaSetShow);

    //主窗口关闭时，关闭线程
    connect(m_MainWindow, &MainWindow::quitThread, this, [=]{
        qDebug() << "关闭线程";
        m_ModbusRTU->quit();
    });

    connect(m_MainWindow, &MainWindow::closeThread, m_ModbusRTU, &ModbusRTU::slot_pauseThread);

    connect(m_MainWindow, &MainWindow::openThread, m_ModbusRTU, &ModbusRTU::slot_resumeThread);

    // ui->btnConnect->setStyleSheet("QPushButton { background-color: lightgray; color: black; border: none; }");

    //主窗口接受语言选择number的信号与槽的连接
    connect(this, &DialogLogin::sendLanNumberSignals, m_MainWindow, &MainWindow::getLanNumberSlot);

    //故障解析的信号与槽
    connect(m_ModbusRTU, &ModbusRTU::sig_showFault, m_MainWindow, &MainWindow::slot_pageHomeFault);

    //电池界面中，点击bmu发送对应的数据
    // connect(m_MainWindow, &MainWindow::read_regs_input_signals_vol, m_ModbusRTU, &ModbusRTU::read_regs_input_slot_vol);
    // connect(m_MainWindow, &MainWindow::read_regs_input_signals_temp, m_ModbusRTU, &ModbusRTU::read_regs_input_slot_temp);

    //上面的方法太low了，直接将row的索引传到modbus的线程中去
    connect(m_MainWindow, &MainWindow::row_of_bmus_index, m_ModbusRTU, &ModbusRTU::change_BMUIndex_slot);


    // ui->btnConnect->setStyleSheet("QPushButton { background-color: #87CEFA; color: white; }"
    //                                      "QPushButton:hover { background-color: #77B5D6; color: white; }");

    // QMetaObject::invokeMethod(m_ModbusRTU,"read_regs_slot",Qt::QueuedConnection);
    // connect(m_ModbusRTU, &ModbusRTU::sig_readMoveToThread, m_ModbusRTU, &ModbusRTU::read_regs_slot, Qt::QueuedConnection);
    // thread = new QThread;

    // m_ModbusRTU->moveToThread(thread);
    // thread->start();
}

void DialogLogin::serialInit()
{
    connect(m_Serial, SIGNAL(comChangeStatus(QString,bool)), this, SLOT(slot_comChangeStatus(QString,bool)));

    if(ini->contains("Serial/SerialPort") == false || ini->contains("Serial/BaudRate") == false ||
        ini->contains("Serial/DataBits") == false || ini->contains("Serial/StopBits") == false ||
        ini->contains("Serial/Parity") == false || ini->contains("Serial/FlowControl") == false) {
        ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
        ui->comboBoxBaudRate->setCurrentIndex(3);
        ui->comboBoxDataBits->setCurrentIndex(3);
        ui->comboBoxStopBits->setCurrentIndex(0);
        ui->comboBoxParity->setCurrentIndex(0);
        ui->comboBoxLanguage->setCurrentIndex(ini->value("System/Language").toUInt());
        // qDebug() << "lan currentIndex false:" << ini->value("System/Language").toUInt();
    }
    else {
        ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
        ui->comboBoxBaudRate->setCurrentIndex(ini->value("Serial/BaudRate").toUInt());
        ui->comboBoxDataBits->setCurrentIndex(ini->value("Serial/DataBits").toUInt());
        ui->comboBoxStopBits->setCurrentIndex(ini->value("Serial/StopBits").toUInt());
        ui->comboBoxParity->setCurrentIndex(ini->value("Serial/Parity").toUInt());
        ui->comboBoxLanguage->setCurrentIndex(ini->value("System/Language").toUInt());
        // ui->comboBoxLanguage->setCurrentIndex(ini->value());
        // qDebug() << "lan currentIndex " << ini->value("System/Language").toUInt();
    }
}

void DialogLogin::modbusRTUInit()
{

}

void DialogLogin::mainwindowInit()
{
    connect(m_MainWindow, &MainWindow::showLogin, this, [=]{
        this->show();
    });
    // connect(this, &DialogLogin::finished, m_MainWindow, [=]{
    //     m_MainWindow->ui->btnSetup->setStyleSheet("#btnSetup{"
    //                                               "background-image: url(:/Image/advance-set-line.png);"
    //                                               "background-repeat: no-repeat;"
    //                                               "background-position: center;"
    //                                               "background-color: rgba(255, 255, 255, 0);"
    //                                               "}"
    //                                               "#btnSetup::hover{"
    //                                               "background-image: url(:/Image/advance-set-line1.png);"
    //                                               "background-repeat: no-repeat;"
    //                                               "background-position: center;"
    //                                               "background-color: rgba(255, 255, 255, 0);"
    //                                               "}");
    // });
    // connect(m_MainWindow->ui->btnSetup, &QPushButton::pressed, this, [=]{
    //     qDebug() << __FUNCTION__ << "disconnected";
    //     m_ModbusRTU->isConnect = false;
    //     m_MainWindow->statusBarConnectedIcon->setPixmap(QPixmap(QIcon(":/Image/connected1.png").pixmap(QSize(24, 24))));
    //     m_Serial->m_SerialPort->close();
    //     m_ModbusRTU->modbusRTUDisconnect();
    //     ui->comboBoxSerialPort->clear();
    //     ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
    // });
}

void DialogLogin::slot_comChangeStatus(QString name, bool flag)
{
    Q_UNUSED(name);
    Q_UNUSED(flag);
    ui->comboBoxSerialPort->clear();
    ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
}

void DialogLogin::slot_btnConnect_clicked()
{
    ini->setValue("Serial/BaudRate", ui->comboBoxBaudRate->currentIndex());
    ini->setValue("Serial/DataBits", ui->comboBoxDataBits->currentIndex());
    ini->setValue("Serial/StopBits", ui->comboBoxStopBits->currentIndex());
    ini->setValue("Serial/Parity", ui->comboBoxParity->currentIndex());
    ini->sync();
    // BCUNumbers = ui->comboBoxBCUQuantity->currentText().toInt();

    QString language = ui->comboBoxLanguage->currentText();
    if (language == "English")
    {
        qDebug() << "ini lanuage index" << ini->value("System/Language");
        ini->setValue("System/Language", 1);
        ini->sync();
        QTranslator trans;
        emit sendLanNumberSignals(0);
        trans.load(":/Language/BatteryMonitor_ENG.qm");
        QApplication::installTranslator(&trans);
        m_MainWindow->ui->retranslateUi(m_MainWindow);
    }
    else if (language == "Chinese")
    {
        qDebug() << "ini lanuage index" << ini->value("System/Language");
        ini->setValue("System/Language", 0);
        ini->sync();
        emit sendLanNumberSignals(1);
        QTranslator trans;
        trans.load(":/Language/BatteryMonitor_CHN.qm");
        QApplication::installTranslator(&trans);
        m_MainWindow->ui->retranslateUi(m_MainWindow);
    }

    emit sendBCUNumberSignals(BCUNumbers);
    connect(this, &DialogLogin::sendBCUNumberSignals, m_MainWindow, &MainWindow::slot_getBcuNumberFromDialoglogin);


    if(m_Serial->getAvailablePort().size() == 0) {
        if(ini->value("System/Language") == MainWindow::LANGUAGE_ENG) {
            QMessageBox::critical(this, "Connect Filed", "No Available Serial");
        }
        else if(ini->value("System/Language") == MainWindow::LANGUAGE_CHN) {
            QMessageBox::critical(this, "连接失败", "没有可用的串口");
        }
        return;
    }
    else {
        int index = ui->comboBoxSerialPort->currentText().indexOf("(");
        QString portName = ui->comboBoxSerialPort->currentText().left(index);
        ini->setValue("Serial/SerialPort", portName);

        m_ModbusRTU->comPort = portName.toStdString().c_str();

        m_Serial->m_SerialPort->setPortName(portName);
        if(ui->comboBoxBaudRate->currentText() == "1200") {
            m_ModbusRTU->baudRate = 1200;
        }
        else if(ui->comboBoxBaudRate->currentText() == "2400") {
            m_ModbusRTU->baudRate = 2400;
        }
        else if(ui->comboBoxBaudRate->currentText() == "4800") {
            m_ModbusRTU->baudRate = 4800;
        }
        else if(ui->comboBoxBaudRate->currentText() == "9600") {
            m_ModbusRTU->baudRate = 9600;
        }
        else if(ui->comboBoxBaudRate->currentText() == "19200") {
            m_ModbusRTU->baudRate = 19200;
        }
        else if(ui->comboBoxBaudRate->currentText() == "38400") {
            m_ModbusRTU->baudRate = 38400;
        }
        else if(ui->comboBoxBaudRate->currentText() == "57600") {
            m_ModbusRTU->baudRate = 57600;
        }
        else if(ui->comboBoxBaudRate->currentText() == "115200") {
            m_ModbusRTU->baudRate = 115200;
        }

        if(ui->comboBoxDataBits->currentText() == "5") {
            m_ModbusRTU->dataBit = 5;
        }
        else if(ui->comboBoxDataBits->currentText() == "6") {
            m_ModbusRTU->dataBit = 6;
        }
        else if(ui->comboBoxDataBits->currentText() == "7") {
            m_ModbusRTU->dataBit = 7;
        }
        else if(ui->comboBoxDataBits->currentText() == "8") {
            m_ModbusRTU->dataBit = 8;
        }

        if(ui->comboBoxStopBits->currentText() == "1") {
            m_ModbusRTU->stopBit = 1;
        }
        else if(ui->comboBoxStopBits->currentText() == "2") {
            m_ModbusRTU->stopBit = 2;
        }

        if(ui->comboBoxParity->currentText() == "None") {
            m_ModbusRTU->parity = 'N';
        }
        else if(ui->comboBoxParity->currentText() == "Odd") {
            m_ModbusRTU->parity = 'O';
        }
        else if(ui->comboBoxParity->currentText() == "Even") {
            m_ModbusRTU->parity = 'E';
        }

        bool ret = m_ModbusRTU->modbusRTUConnect(m_ModbusRTU->comPort, m_ModbusRTU->baudRate, m_ModbusRTU->parity, m_ModbusRTU->dataBit, m_ModbusRTU->stopBit);
        if(ret == true) {
            qDebug() << __FUNCTION__ << "connected";
            m_ModbusRTU->isConnect = true;
            m_MainWindow->statusBarConnectedIcon->setPixmap(QPixmap(QIcon(":/Image/connected2.png").pixmap(QSize(24, 24))));
            m_MainWindow->show();
            // m_MainWindow->showMaximized();
            // m_ModbusRTU->start();
            m_ModbusRTU->start();
            m_MainWindow->showMaximized();
        }
        else {
            if(ini->value("System/Language") == MainWindow::LANGUAGE_ENG) {
                QMessageBox::critical(this, "Connect Filed", "Serial prot cannot be opened please check and open it again\n"
                                                             "1.Check USB-Serial is connected\n"
                                                             "2.Check baud rate is set correctly\n"
                                                             "3.Check whether the serial port is being used\n"
                                                             "4.Check Modbus proto is true");
            }
            else if(ini->value("System/Language") == MainWindow::LANGUAGE_CHN) {
                QMessageBox::critical(this, "连接失败", "当前串口号无法打开，请检查后重新打开\n"
                                                        "1.检查USB串口工具是否连接上电脑\n"
                                                        "2.检查波特率是否设置正确\n"
                                                        "3.检查串口号是否被占用了\n"
                                                        "4.检查Modbus通信协议是否有误");
            }
        }
        this->close();
    }
}
