import os
import re
from datetime import datetime

from qgis.PyQt.QtCore import QVariant, QThread, pyqtSignal
from qgis.PyQt.QtGui import QColor
from qgis.PyQt import uic, QtWidgets, QtCore
from qgis._core import QgsFeatureRequest, QgsMapLayer, QgsWkbTypes, QgsCoordinateReferenceSystem, \
    QgsCoordinateTransform, QgsProject, QgsGeometry, QgsGeometryCollection, QgsVectorLayer, QgsFields, QgsField, \
    QgsFeature, Qgis, QgsPointXY, QgsGradientColorRamp, QgsGradientStop, QgsHeatmapRenderer, QgsSingleSymbolRenderer, \
    QgsSymbol, QgsEmbeddedSymbolRenderer
from qgis.utils import iface

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'cyanlove_create_hotmap_base.ui'))


class cyanlove_create_hotmap(QtWidgets.QDockWidget, FORM_CLASS):
    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        super(cyanlove_create_hotmap, self).__init__(parent)
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.setupUi(self)
        self.setFloating(True)

        self.setWindowFlags(QtCore.Qt.Dialog)  # 使对话框始终在前
        # 设置为模态窗口
        # self.setWindowModality(QtCore.Qt.ApplicationModal)  # 或者使用 Qt.WindowModal
        self.plainTextEdit.setPlainText('5')
        self.toolButton.clicked.connect(self.draw_hotmap)
        self.toolButton_clear.clicked.connect(self.clear_hotmap)
        self.mMapLayerComboBox.currentIndexChanged.connect(self.selectindexchange)
        self.mFieldComboBox.setLayer(self.mMapLayerComboBox.currentLayer())
        self.horizontalSlider.valueChanged.connect(self.slider_value_changed)

    def slider_value_changed(self, value):
        self.plainTextEdit.setPlainText(str(value))

    def selectindexchange(self):
        self.mFieldComboBox.setLayer(self.mMapLayerComboBox.currentLayer())

    def clear_hotmap(self):
        layerselect = self.mMapLayerComboBox.currentLayer()
        if isinstance(layerselect, QgsVectorLayer):
            # 判断是否是热力图渲染器
            renderer = layerselect.renderer()
            if isinstance(renderer, QgsHeatmapRenderer):
                # 清除热力图渲染器设置，恢复为默认的单符号渲染器
                symbol = QgsSymbol.defaultSymbol(layerselect.geometryType())
                default_renderer = QgsEmbeddedSymbolRenderer(symbol)
                layerselect.setRenderer(default_renderer)

                # 触发图层重新绘制
                layerselect.triggerRepaint()
            self.label_show.setText('清空完毕！')

    def draw_hotmap(self):
        self.label_show.setText("")
        input_value = self.horizontalSlider.value()
        layerselect = self.mMapLayerComboBox.currentLayer()
        colname = self.mFieldComboBox.currentField()
        if layerselect is None or colname is None or input_value is None:
            self.label_show.setText('填写项不正确')
            return
        geom_type1 = layerselect.wkbType()
        if geom_type1 not in [QgsWkbTypes.Point, QgsWkbTypes.MultiPoint]:
            self.label_show.setText('不是点图层，无法创建热力图！')
            return

        # 如果是矢量图层
        if isinstance(layerselect, QgsVectorLayer):
            try:

                colour_ramp_gradient = QgsGradientColorRamp()

                # 设置第一个颜色为透明的蓝色
                transparent_blue = QColor(0, 0, 0, 0)  # 透明度为0
                colour_ramp_gradient.setColor1(transparent_blue)
                colour_ramp_gradient.setColor2(QColor(255, 0, 0))

                # 定义颜色渐变的停靠点
                colour_ramp_gradient.setStops([
                    QgsGradientStop(0.45, QColor(0, 0, 255)),
                    QgsGradientStop(0.55, QColor(0, 255, 255)),
                    QgsGradientStop(0.65, QColor(0, 255, 0)),
                    QgsGradientStop(0.95, QColor("yellow")),
                    QgsGradientStop(1, QColor(255, 0, 0))
                ])

                # 创建热力图渲染器并设置颜色渐变
                heatmap_renderer = QgsHeatmapRenderer()
                heatmap_renderer.setRenderQuality(1)
                heatmap_renderer.setWeightExpression(colname)
                heatmap_renderer.setColorRamp(colour_ramp_gradient)  # 设置热力图的颜色渐变
                heatmap_renderer.setRadius(int(input_value))  # 设置热力图的半径（你可以调整此值）

                # 应用渲染器
                layerselect.setRenderer(heatmap_renderer)

                # 刷新图层以应用样式
                layerselect.triggerRepaint()
                self.label_show.setText(f"创建完毕！")
            except Exception as e:
                self.label_show.setText(f"{str(e)}")
        else:
            self.label_show.setText('不是矢量图层')