#include <QLabel>
#include <QDesktopServices>
#include <QMessageBox>
#include <QTableWidgetItem>
#include "RasterMainWidget.h"
#include "ui_RasterMainWidget.h"

#include <sponsorwindow.h>
#include <taskwindow.h>
#include <tmslayer.h>
#include <QDockWidget>
#include "ToolBoxWidget.h"
#include "BaseTool.h"
#include "FileOperator.h"

#include "RasterWidgetMessageShow.h"


#pragma execution_character_set("utf-8")

namespace LAMPMainWidget {

QString
RasterMainWidget::tutorialUrl() {
  return QString{R"(https://gitee.com/qizr_admin/LAMPMainWidget)"};
}

QString
RasterMainWidget::srcUrl() {
  return QString{R"(https://gitee.com/qizr_admin/LAMPMainWidget)"};
}

QHash<QString, MapLayer *>RasterMainWidget::mMaps{};

RasterMainWidget::RasterMainWidget(QWidget *parent)
    : mUi(new Ui::RasterMainWidget),
      mMapConvas(new MapCanvas),
      mScaleText(new QLineEdit),
      mScaleLabel(new QLabel),
      mCenterText(new QLineEdit),
      mCenterLabel(new QLabel),
      mZoomText(new QLineEdit),
      mZoomLabel(new QLabel),
      mMapActionGroup(new QActionGroup(dynamic_cast<QObject *>(this))),
      mSetLeftTop(true),
      mLayerList(),
      mLeftTop(),
      mRightBottom() {
	this->setWindowTitle(tr(u8"LAMP影像处理软件"));
	mUi->setupUi(dynamic_cast<QMainWindow*>(this));
	setupWindow();
	setupTaskWindow();
	setupLayers();
	setupStatusBar();
	setupActions();
	setRightToolbox();

	//mUi->panAction->trigger();
	//mUi->layerList->setCurrentItem(mLayerList.first());

   


}

RasterMainWidget::~RasterMainWidget() {
  delete mUi;
  delete mMapConvas;
  delete mScaleText;
  delete mScaleLabel;
  delete mCenterText;
  delete mCenterLabel;
}

void
RasterMainWidget::setupTaskWindow() {
  mUi->taskTable->setColumnCount(5);
  mUi->taskTable->setHorizontalHeaderLabels(QStringList{
      "名称", "范围", "zoom值", "数据源", "进度"
  });
  mUi->taskTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

void
RasterMainWidget::setupActions() {
  mMapActionGroup->addAction(mUi->panAction);
  mMapActionGroup->addAction(mUi->zoomInAction);
  mMapActionGroup->addAction(mUi->zoomOutAction);
  mMapActionGroup->addAction(mUi->selectAction);

  mUi->selectAction->setEnabled(false);

  QObject::connect(mUi->panAction, &QAction::triggered, this, &RasterMainWidget::panHandle);
  QObject::connect(mUi->zoomInAction, &QAction::triggered, this, &RasterMainWidget::zoomInHandle);
  QObject::connect(mUi->zoomOutAction, &QAction::triggered, this, &RasterMainWidget::zoomOutHandle);
  QObject::connect(mUi->tutorialAction, &QAction::triggered, this, &RasterMainWidget::tutorialHanle);
  QObject::connect(mUi->srcAction, &QAction::triggered, this, &RasterMainWidget::srcHandle);
  QObject::connect(mUi->refreshAction, &QAction::triggered, this, &RasterMainWidget::refreshHandle);
  QObject::connect(mUi->sponsorAction, &QAction::triggered, this, &RasterMainWidget::sponsorHandle);
  QObject::connect(mUi->selectAction, &QAction::triggered, this, &RasterMainWidget::selectHandle);
  QObject::connect(mUi->downloadAction, &QAction::triggered, this, &RasterMainWidget::createDownloadTask);
  QObject::connect(mUi->drawlineAction, &QAction::triggered, this, &RasterMainWidget::drawlineHandle);
}

void RasterMainWidget::setupWindow() {
  mUi->mapCanvasLayout->addWidget(mMapConvas);
  //setFixedSize(size());
  //setWindowFlags(windowFlags() | Qt::WindowMinMaxButtonsHint | Qt::WindowSystemMenuHint);

  QObject::connect(mMapConvas, &MapCanvas::zoomChanged, this, &RasterMainWidget::zoomChangedHandle);
  QObject::connect(mMapConvas, &MapCanvas::clicked, this, &RasterMainWidget::clickedHandle);
  QObject::connect(mMapConvas, &MapCanvas::mapCenterChanged, this, &RasterMainWidget::centerChangedHandle);
  QObject::connect(mUi->layerList, &QListWidget::currentItemChanged, this, &RasterMainWidget::layerChanged);
  QObject::connect(mUi->leftTopBtn, &QPushButton::clicked, this, &RasterMainWidget::leftTopClickedHandle);
  QObject::connect(mUi->rightBottomBtn, &QPushButton::clicked, this, &RasterMainWidget::rightBottomClickedHandle);

    
  RasterMessageShow::RasterWidgetMessageShow* messageshow = RasterMessageShow::RasterWidgetMessageShow::getInstance(this);
  messageshow->bandingTextBrowserMessage(this->mUi->textBrowserMessage);


}

void RasterMainWidget::setupStatusBar() {
  /// 比例尺
  mScaleLabel->setText("比例尺");
  mScaleText->setText(QString("1cm : %1m").arg(mMapConvas->scale()));
  mScaleText->setFixedWidth(150);
  mScaleText->setReadOnly(true);
  mUi->statusbar->addWidget(mScaleLabel);
  mUi->statusbar->addWidget(mScaleText);

  /// 空白间隔
  mUi->statusbar->addWidget(spacerWiget(30));

  /// zoom值
  mZoomLabel->setText("Zoom值=>");
  mZoomText->setText(QString("%1").arg(mMapConvas->zoomValue()));
  mZoomText->setFixedWidth(80);
  mZoomText->setReadOnly(true);
  mUi->statusbar->addWidget(mZoomLabel);
  mUi->statusbar->addWidget(mZoomText);

  /// 空白间隔
  mUi->statusbar->addWidget(spacerWiget(30));

  /// 视图中心坐标
  mCenterLabel->setText("视图中心坐标=>");
  PointXY center = mMapConvas->mapCenter();
  mCenterText->setText(QString("lon:%1, lat:%2").arg(center.x()).arg(center.y()));
  mCenterText->setFixedWidth(300);
  mCenterText->setReadOnly(true);
  mUi->statusbar->addWidget(mCenterLabel);
  mUi->statusbar->addWidget(mCenterText);
}

void RasterMainWidget::setupLayers() {
  initMaps();
  auto i = mMaps.constBegin();
  for (; i != mMaps.constEnd(); ++i) {
    mLayerList.append(new QListWidgetItem(i.key(), mUi->layerList));
  }
}

void
RasterMainWidget::initMaps() {
  if (mMaps.isEmpty()) {
    mMaps = QHash<QString, MapLayer *>{
        {"Openstreet地图", new TmsLayer(OSTNormalMap, "ostnormalmap", mMapConvas)},
        {"高德地图", new TmsLayer(GaodeNormapMap, "gaodenormalmap", mMapConvas)}
    };
  }
}

void RasterMainWidget::setRightToolbox()
{
    this->toolboxDockWidget = new QDockWidget(tr(u8"工具箱"), this);
    toolboxDockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    toolBoxWidget = new ToolBoxWidget(this);
    toolboxDockWidget->setWidget(toolBoxWidget);
    addDockWidget(Qt::LeftDockWidgetArea, toolboxDockWidget);
    setDockOptions(QMainWindow::AllowNestedDocks | QMainWindow::AllowTabbedDocks);
    this->initToolbox();
}

void RasterMainWidget::initToolbox()
{
    QString appPath = QCoreApplication::applicationDirPath();
    QString pluginPath = JoinPath(appPath, "Toolbox");

    toolBoxWidget->initToolbox(pluginPath);
   

}

QWidget *RasterMainWidget::spacerWiget(int width) const {
  auto spacer = new QWidget{};
  spacer->setHidden(true);
  spacer->setVisible(true);
  spacer->setFixedWidth(width);

  return spacer;
}

void
RasterMainWidget::panHandle(bool checked) {
  mMapConvas->selectTool(QString{"pan_tool"});
}

void
RasterMainWidget::zoomInHandle(bool checked) {
  mMapConvas->selectTool(QString{"zoomin_tool"});
}

void
RasterMainWidget::zoomOutHandle(bool checked) {
    mMapConvas->selectTool(QString{"zoomout_tool"});
}

void RasterMainWidget::drawlineHandle(bool checked)
{
    mMapConvas->selectTool("drawline_tool");
}

void
RasterMainWidget::tutorialHanle(bool checked) {
  if (!QDesktopServices::openUrl(tutorialUrl())) {
    QMessageBox::critical(dynamic_cast<QWidget *>(this), "异常", "未能打开系统浏览器");
  }
}

void
RasterMainWidget::srcHandle(bool checked) {
  if (!QDesktopServices::openUrl(srcUrl())) {
    QMessageBox::critical(dynamic_cast<QWidget *>(this), "异常", "未能打开系统浏览器");
  }
}

void
RasterMainWidget::sponsorHandle(bool checked) {
  auto *window = new SponsorWindow(dynamic_cast<QWidget *>(this));
  window->exec();
  window->deleteLater();
}

void
RasterMainWidget::refreshHandle(bool checked) {
  mMapConvas->refreshMap();
}

void
RasterMainWidget::selectHandle(bool checked) {
  mMapConvas->selectTool(QString{"select_tool"});
}

void
RasterMainWidget::centerChangedHandle(LAMPMainWidget::PointXY pos) {
  mCenterText->setText(QString("lon:%1, lat:%2").arg(pos.x()).arg(pos.y()));
}

void
RasterMainWidget::zoomChangedHandle(int zoom) {
  mZoomText->setText(QString("%1").arg(zoom));
  mScaleText->setText(QString("1cm:%1m").arg(this->mMapConvas->scale()));
}

void
RasterMainWidget::clickedHandle(LAMPMainWidget::PointXY pos) {
  QString posText = QString("%1, %2").arg(pos.x()).arg(pos.y());
  if (mSetLeftTop) {
    mUi->leftTopText->setText(posText);
    mLeftTop = pos;
  } else {
    mUi->rightBottomText->setText(posText);
    mRightBottom = pos;
  }
}

void
RasterMainWidget::leftTopClickedHandle() {
  mSetLeftTop = true;
  mUi->selectAction->trigger();
}

void
RasterMainWidget::rightBottomClickedHandle() {
  mSetLeftTop = false;
  mUi->selectAction->trigger();
}

void
RasterMainWidget::layerChanged(QListWidgetItem *current, QListWidgetItem *previous) {
  auto mapName = current->text();
  if (!mMaps.contains(mapName)) {
    qDebug() << mapName << "不支持";
    return;
  }

  auto layer = mMaps.value(mapName);
  auto i = mMaps.begin();
  for (; i != mMaps.end(); ++i) {
    if (i.key() == mapName) {
      i.value()->setVisiblity(true);
      qDebug() << i.key() << i.value()->isVisible();
      continue;
    }

    i.value()->setVisiblity(false);
  }

  mMapConvas->addLayer(layer);
  mMapConvas->setCurrentLayer(layer->id());
  mMapConvas->refreshMap();

  zoomChangedHandle(mMapConvas->zoomValue());
  centerChangedHandle(mMapConvas->mapCenter());
}

void
RasterMainWidget::createDownloadTask() {
  auto taskWindow = new TaskWindow(dynamic_cast<QWidget *>(this));
  taskWindow->exec();
  taskWindow->deleteLater();
}

void
RasterMainWidget::changeTaskTable(int row, int col, QString text) {
  mUi->taskTable->takeItem(row, col);
  mUi->taskTable->setItem(row, col, new QTableWidgetItem(text));
}


void RasterMainWidget::on_drawArea_triggered()
{
     mMapConvas->selectTool("drawarea_tool");
}


void RasterMainWidget::on_addPlaneaction_triggered()
{
    mMapConvas->selectTool("addplane_tool");
}

QTableWidget* RasterMainWidget::getTaskTable()
{
    return this->mUi->taskTable;
}

}
