#include "expertscreenconnwin.h"
#include "gqt.h"
#include <QGroupBox>
#include <QLabel>
#include <QToolButton>
#include <QPushButton>
#include <QPainter>
#include <QTableWidget>
#include <QHeaderView>
#include <QMouseEvent>
#include <QDebug>
#include <math.h>
#define M_PI 3.14159265358979323846
QColor cardColors[] {QColor(0xff2222), QColor(0xffaa00), QColor(0x00bb00), QColor(0x00bbcc), QColor(0x0044ff), QColor(0xffffff), QColor(0xffff00)};

ExpertScreenConnWin::ExpertScreenConnWin(QWidget *parent) : QWidget{parent} {
    auto vv = new QVBoxLayout(this);
    vv->setContentsMargins(4, 4, 4, 4);

    auto hh = new QHBoxLayout;
    vv->addLayout(hh);

    auto leftWgt = new QWidget;
    auto poli = leftWgt->sizePolicy();
    poli.setHorizontalPolicy(QSizePolicy::Maximum);
    leftWgt->setSizePolicy(poli);
    hh->addWidget(leftWgt);

    auto vvv = new QVBoxLayout(leftWgt);
    vvv->setContentsMargins(0,0,0,0);

    auto gBox = new QGroupBox(tr("起始位置"));
    vvv->addWidget(gBox);

    auto fdX = new QSpinBox;
    auto fdY = new QSpinBox;
    {
        auto hhh = new QHBoxLayout(gBox);

        auto lb = new QLabel(tr("X坐标: "));
        hhh->addWidget(lb);

        fdX->setRange(0, 99999);
        fdX->setValue(0);
        hhh->addWidget(fdX);

        lb = new QLabel(tr("Y坐标: "));
        hhh->addWidget(lb);

        fdY->setRange(0, 99999);
        fdY->setValue(0);
        hhh->addWidget(fdY);
    }

    gBox = new QGroupBox(tr("接收卡设置"));
    vvv->addWidget(gBox);

    auto fdCardColNum = new QSpinBox;
    auto fdCardRowNum = new QSpinBox;
    {
        auto vBox = new QVBoxLayout(gBox);
        auto hhh = new QHBoxLayout;
        vBox->addLayout(hhh);

        auto lb = new QLabel(tr("卡列数: "));
        hhh->addWidget(lb);

        fdCardColNum->setRange(0, 9999);
        fdCardColNum->setValue(2);
//        connect(fdCardColNum, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) {
//            table->setColumnCount(value);
//        });
        hhh->addWidget(fdCardColNum);

        lb = new QLabel(tr("卡行数: "));
        hhh->addWidget(lb);

        fdCardRowNum->setRange(0, 9999);
        fdCardRowNum->setValue(2);

        hhh->addWidget(fdCardRowNum);

        vBox->addLayout(hhh = new QHBoxLayout);

        lb = new QLabel(tr("卡宽度: "));
        hhh->addWidget(lb);

        fdCardWidth = new QSpinBox;
        fdCardWidth->setRange(0, 9999);
        fdCardWidth->setValue(128);
        hhh->addWidget(fdCardWidth);

        lb = new QLabel(tr("卡高度: "));
        hhh->addWidget(lb);

        fdCardHeight = new QSpinBox;
        fdCardHeight->setRange(0, 9999);
        fdCardHeight->setValue(128);
        hhh->addWidget(fdCardHeight);
    }

    gBox = new QGroupBox(tr("网口选择"));
    vvv->addWidget(gBox);
    auto hhh = new QHBoxLayout(gBox);

    auto pal = palette();
    fdNet = new QButtonGroup(gBox);
    for(int i=0; i<netss.size(); i++) {
        auto bn = new QPushButton(QString::number(i+1));
        bn->setCheckable(true);
        if(i==0) bn->setChecked(true);
        bn->setMinimumHeight(30);
        pal.setColor(QPalette::ButtonText, cardColors[i%(sizeof(cardColors)/sizeof(cardColors[0]))]);
        bn->setPalette(pal);
        hhh->addWidget(bn);
        fdNet->addButton(bn, i);
    }

    gBox = new QGroupBox(tr("快速串线:"));
    gBox->setStyleSheet("QToolButton {border: none; }");
    vvv->addWidget(gBox);
    {
        auto vvv = new QVBoxLayout(gBox);
        hhh = new QHBoxLayout;
        vvv->addLayout(hhh);

        auto bnConn1 = new QToolButton;
        bnConn1->setIconSize(QSize(48,48));
        bnConn1->setIcon(QIcon(":/imgs/conn1.png"));
        hhh->addWidget(bnConn1);

        auto bnConn2 = new QToolButton;
        bnConn2->setIconSize(QSize(48,48));
        bnConn2->setIcon(QIcon(":/imgs/conn2.png"));
        hhh->addWidget(bnConn2);

        auto bnConn3 = new QToolButton;
        bnConn3->setIconSize(QSize(48,48));
        bnConn3->setIcon(QIcon(":/imgs/conn3.png"));
        hhh->addWidget(bnConn3);

        auto bnConn4 = new QToolButton;
        bnConn4->setIconSize(QSize(48,48));
        bnConn4->setIcon(QIcon(":/imgs/conn4.png"));
        hhh->addWidget(bnConn4);

        hhh = new QHBoxLayout;
        vvv->addLayout(hhh);

        auto bnConn5 = new QToolButton;
        bnConn5->setIconSize(QSize(48,48));
        bnConn5->setIcon(QIcon(":/imgs/conn5.png"));
        hhh->addWidget(bnConn5);

        auto bnConn6 = new QToolButton;
        bnConn6->setIconSize(QSize(48,48));
        bnConn6->setIcon(QIcon(":/imgs/conn6.png"));
        hhh->addWidget(bnConn6);

        auto bnConn7 = new QToolButton;
        bnConn7->setIconSize(QSize(48,48));
        bnConn7->setIcon(QIcon(":/imgs/conn7.png"));
        hhh->addWidget(bnConn7);

        auto bnConn8 = new QToolButton;
        bnConn8->setIconSize(QSize(48,48));
        bnConn8->setIcon(QIcon(":/imgs/conn8.png"));
        hhh->addWidget(bnConn8);
    }

    vvv->addLayout(hhh = new QHBoxLayout);

    auto bnRefresh = new QPushButton(tr("重新开始"));
    connect(bnRefresh, &QPushButton::clicked, this, [this] {
        table->clearContents();
        for(int i=0; i<netss.size(); i++) if(! netss[i].isEmpty()) netss[i].clear();
    });
    hhh->addWidget(bnRefresh);

    auto bnBack = new QPushButton(tr("后退"));
    connect(bnBack, &QPushButton::clicked, this, &ExpertScreenConnWin::connBack);
    hhh->addWidget(bnBack);

    hhh->addStretch();

    vvv->addStretch();

    table = new CardTable(fdCardRowNum->value(), fdCardColNum->value());
    table->win = this;
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
    table->horizontalHeader()->setDefaultSectionSize(90);
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    table->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
    table->verticalHeader()->setDefaultSectionSize(90);
    table->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    table->verticalHeader()->setMinimumWidth(30);
    table->setSelectionMode(QTableWidget::NoSelection);
    connect(table, &QTableWidget::currentCellChanged, this, &ExpertScreenConnWin::conn);
    connect(fdCardColNum, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, table, &QTableWidget::setColumnCount);
    connect(fdCardRowNum, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, table, &QTableWidget::setRowCount);
    hh->addWidget(table);
}

void ExpertScreenConnWin::conn(int row, int column) {
    if(row < 0) return;
    auto item = table->item(row, column);
    if(item) return;
    auto netIdx = fdNet->checkedId();
    netss[netIdx].append(QPoint(column, row));
    item = new QTableWidgetItem("网口: "+QString::number(netIdx+1)+"\n"+tr("接收卡: ")+QString::number(netss[netIdx].size())+"\n"+tr("宽度: ")+QString::number(fdCardWidth->value())+"\n高度: "+QString::number(fdCardHeight->value()));
    auto color = cardColors[netIdx % (sizeof(cardColors)/sizeof(cardColors[0]))];
    item->setForeground(QColor(255,255,255));
    color.setAlpha(100);
    item->setBackground(color);
    item->setData(Qt::UserRole, netIdx);
    table->setItem(row, column, item);
    table->update();
}
void ExpertScreenConnWin::connBack() {
    auto netIdx = fdNet->checkedId();
    if(netss[netIdx].isEmpty()) return;
    table->selectionModel()->clearCurrentIndex();
    auto point = netss[netIdx].takeLast();
    table->setItem(point.y(), point.x(), 0);
    table->update();
}

void CardTable::paintEvent(QPaintEvent *event) {
    QTableWidget::paintEvent(event);
    QPainter painter(viewport());
    for(int i=0; i<win->netss.size(); i++) {
        auto size = win->netss[i].size();
        if(size < 2) continue;
        QColor a=cardColors[i % (sizeof(cardColors)/sizeof(cardColors[0]))];
        //QColor b=QColor(255-a.red(),255-a.green(),255-a.blue(),200);
        QColor b=QColor(a.red(),a.green(),a.blue(),255);

        QPen pen=QPen(b);

        int off = 45 + (i+1)/2 * (i%2 ? -4 : 4);
        for(int j=1; j<size; j++) {
            auto point1 = win->netss[i][j-1];
            auto point2 = win->netss[i][j];
            DrawLineWithArrow(painter,pen,QPoint(point1.x()*90+off, point1.y()*90+off), QPoint(point2.x()*90+off, point2.y()*90+off));
         }
    }
}
void CardTable::mousePressEvent(QMouseEvent *event) {
    if(event->button() != Qt::RightButton) QTableWidget::mousePressEvent(event);
}
void CardTable::mouseReleaseEvent(QMouseEvent *event) {
    QTableWidget::mouseReleaseEvent(event);
    if(event->button() == Qt::RightButton) win->connBack();
}

void CardTable::DrawLineWithArrow(QPainter& painter, QPen pen, QPoint start, QPoint end)
{
    painter.setRenderHint(QPainter::Antialiasing, true);

    qreal arrowSize = 15;
    pen.setWidth(2);
    painter.setPen(pen);
    painter.setBrush(pen.color());

    QLineF line(end, start);

    double angle = atan2(-line.dy(), line.dx());
    QPointF arrowP1 = line.p1() + QPointF(sin(angle + M_PI / 3) * arrowSize,
                                          cos(angle + M_PI / 3) * arrowSize);
    QPointF arrowP2 = line.p1() + QPointF(sin(angle + M_PI - M_PI / 3) * arrowSize,
                                          cos(angle + M_PI - M_PI / 3) * arrowSize);

    QPolygonF arrowHead;
    arrowHead.clear();
    arrowHead << line.p1() << arrowP1 << arrowP2;
    painter.drawLine(line);
    painter.drawPolygon(arrowHead);
}
