#include "draglinehandler.h"

DragLineHandler::DragLineHandler(QCustomPlot *plot, QCPItemStraightLine *line1,
                                 QCPItemStraightLine *line2, QCPGraph*graph,
                                 QObject *parent)
    : QObject(parent), _plot(plot), _line1(line1), _line2(line2),_graph(graph)
    ,_enableFlag(false)
{
    _plot->setInteractions(QCP::iSelectItems);
}

DragLineHandler::~DragLineHandler()
{
}

bool DragLineHandler::eventFilter(QObject *obj, QEvent *event)
{
    if(!_enableFlag){
//        qDebug()<<"_enableFlag false.";
#if 0
        if(mPlot){
            mPlot->setCursor(Qt::ArrowCursor);
        }
#endif
        return QObject::eventFilter(obj, event);
    }

    if (obj == _plot)
    {
        if (event->type() == QEvent::MouseMove)
        {
//            qDebug()<<"mouse move...";

            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            QPoint mousePos = mouseEvent->pos();
//            qDebug()<<"x:"<<mousePos.x();

            bool nearLine1 = isNearLine(_line1, mousePos);
            bool nearLine2 = isNearLine(_line2, mousePos);

            if (nearLine1 || nearLine2)
            {
                _plot->setCursor(Qt::SplitHCursor);

//                qDebug()<<"mIconLabel visiable.";
            }
            else
            {
//                qDebug()<<"mIconLabel not visiable.";

                _plot->setCursor(Qt::ArrowCursor);
            }

            if (_draggingLine)
            {
                double x = _plot->xAxis->pixelToCoord(mousePos.x());
                if(_draggingLine == _line1){
                    emit sigSendLineXCoord(1,x);
                }else{
                    emit sigSendLineXCoord(2,x);
                }
                _draggingLine->point1->setCoords(x, _plot->yAxis->range().lower);
                _draggingLine->point2->setCoords(x, _plot->yAxis->range().upper);
                _plot->replot();
                updateSelectedRegion();
            }
        }
        else if (event->type() == QEvent::MouseButtonPress)
        {
//            qDebug()<<"mouse press...";

            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                QPoint mousePos = mouseEvent->pos();
                if (isNearLine(_line1, mousePos))
                {
                    _draggingLine = _line1;
                    _line1->setSelected(true);
                }
                else if (isNearLine(_line2, mousePos))
                {
                    _draggingLine = _line2;
                    _line2->setSelected(true);
                }
            }
        }
        else if (event->type() == QEvent::MouseButtonRelease)
        {
            if (_draggingLine)
            {
                _draggingLine->setSelected(false);
                _draggingLine = nullptr;
            }
        }
    }
    return QObject::eventFilter(obj, event);
}

bool DragLineHandler::isNearLine(QCPItemStraightLine *line, const QPoint &pos)
{
    double lineX = line->point1->coords().x();
    int linePixelX = _plot->xAxis->coordToPixel(lineX);
    return qAbs(pos.x() - linePixelX) < 5;
}

void DragLineHandler::updateSelectedRegion()
{
    double x1 = _line1->point1->coords().x();
    double x2 = _line1->point1->coords().x();
    if (x1 > x2)
        std::swap(x1, x2);

    // 获取曲线数据
    QVector<double> xData, yData;
    //        mGraph->data()->data(xData, yData);
    auto dataContainer = _graph->data();
    for (auto it = dataContainer->begin(); it != dataContainer->end(); ++it)
    {
        xData.append(it->key);
        yData.append(it->value);
    }

    // 查找对应x位置
    int index1 = findClosestIndex(xData, x1);
    int index2 = findClosestIndex(xData, x2);

//    qDebug() << "Selected region: [" << xData[index1] << ", " << xData[index2] << "]";
}

int DragLineHandler::findClosestIndex(const QVector<double> &data, double target)
{
    auto it = std::min_element(data.begin(), data.end(), [target](double a, double b) {
        return qAbs(a - target) < qAbs(b - target);
    });
    return std::distance(data.begin(), it);
}
