import os
import re
import subprocess
import tempfile
from datetime import datetime

import requests
from PyQt5.QtCore import QVariant, QThread, pyqtSignal
from PyQt5.QtGui import QColor
from qgis.PyQt import uic, QtWidgets, QtCore
from qgis._core import QgsProject, QgsVectorLayer, QgsPoint, QgsGeometry, QgsFields, QgsFeature, QgsLineSymbol, \
    QgsSingleSymbolRenderer, QgsMarkerLineSymbolLayer, QgsSimpleLineSymbolLayer, QgsArrowSymbolLayer, QgsFillSymbol, \
    QgsSvgMarkerSymbolLayer, QgsField, QgsCategorizedSymbolRenderer, QgsRendererCategory

from qgis.utils import iface

from .cyanlove_transform_gps_to_gps import CoordinateConverter
from .cyanlove_config_read_intfile import readconfig

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


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

    def __init__(self, parent=None):
        super(cyanlove_create_luxianguihua, 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.pushButton.clicked.connect(self.draw_luxianguihua)

    def draw_luxianguihua(self):
        print("start...")
        self.label_show.setText("start...")
        # 处理事件以更新界面
        QtWidgets.QApplication.processEvents()
        lnglat1 = self.plainTextEdit.toPlainText().strip()
        lnglat2 = self.plainTextEdit_2.toPlainText().strip()
        lnglat1 = self.formatlnglat(lnglat1)
        lnglat2 = self.formatlnglat(lnglat2)

        keyname = readconfig.read_ini_file('Settings', 'baidu_key')
        if keyname == "":
            self.label_show.setText("没有百度key值，需要配置！")
            return
        url = "https://api.map.baidu.com/direction/v2/driving"
        params = {
            "origin": lnglat1,
            "destination": lnglat2,
            "ak": keyname,
            "alternatives": 1,  # 是否添加备用路线
            "coord_type": 'wgs84'
        }
        try:
            response = requests.get(url=url, params=params, timeout=5)
            jsondata = response.json()

            # with tempfile.NamedTemporaryFile(delete=False, suffix='.txt', mode='w') as temp_file:
            #     temp_file.write(str(jsondata))  # 写入一些数据
            #
            # temp_file_path = temp_file.name  # 获取临时文件路径
            # if os.path.exists(temp_file_path):
            #     print(temp_file_path)
            #     subprocess.run(['notepad.exe', temp_file_path])  # Windows上调用记事本打开文件

            if jsondata['status'] == 0:
                layName = "SSJ_路线规划"
                layers = QgsProject.instance().mapLayersByName(layName)
                if layers:
                    for layer in layers:
                        QgsProject.instance().removeMapLayer(layer.id())

                layer = QgsVectorLayer("LineString?crs=EPSG:4326", layName, "memory")
                provider = layer.dataProvider()  # 获取图层的数据提供者
                fields = QgsFields()  # 创建字段集合
                fields.append(QgsField('name', QVariant.String))  # 添加字符串类型字段
                provider.addAttributes(fields)  # 将字段添加到数据提供者
                layer.updateFields()  # 更新图层的字段

                # 刷新图层以应用更改
                layer.triggerRepaint()
                # 所有的放入里面
                output_linemutistring = []
                for route in jsondata['result']['routes']:
                    all_paths = []  #
                    for step in route['steps']:
                        all_paths.append(step['path'])
                    # 主备均放入
                    output_linemutistring.append(all_paths)

                count = len(output_linemutistring)  # 计数器
                for index, item in enumerate(reversed(output_linemutistring)):

                    if index == count - 1:  # 判断是否为最后一个元素
                        for item1 in item:
                            feature = QgsFeature(fields)  # 创建新特征
                            self.writerline(item1, provider, feature, "主")
                    else:
                        for item1 in item:
                            feature = QgsFeature(fields)  # 创建新特征
                            self.writerline(item1, provider, feature, "备")

                # 创建符号层，定义颜色
                categoryA = QgsRendererCategory('主', QgsLineSymbol.createSimple({'color': 'red', 'width': '1'}), '主')
                categoryB = QgsRendererCategory('备', QgsLineSymbol.createSimple({'color': 'blue', 'width': '1'}), '备')
                # 创建箭头符号图层
                # arrow_layer = QgsArrowSymbolLayer()
                # arrow_layer.setHeadLength(3)
                # arrow_layer.setHeadThickness(3)
                # # 将箭头符号图层添加到线符号
                # line_symbol.appendSymbolLayer(arrow_layer)

                # 创建分类渲染器
                renderer = QgsCategorizedSymbolRenderer('name', [categoryA, categoryB])  # 替换为您的分类字段
                # 将渲染器应用到图层
                layer.setRenderer(renderer)

                QgsProject.instance().addMapLayer(layer, True)
                iface.mapCanvas().refresh()
                print("ok")
                self.label_show.setText("路线规划完毕！")
            else:
                self.label_show.setText("出错，没有获取到！")

        except Exception as e:
            self.label_show.setText(f"{str(e)}")

    @staticmethod
    def formatlnglat(value):
        pattern = r'(?<=\d)\s*[^0-9.]+\s*(?=\d)'
        input_string = value.strip().replace("，", ",")
        # 替换匹配到的内容为逗号
        output_string = re.sub(pattern, ',', input_string)
        lon, lat = map(float, output_string.split(','))  # 转换为浮点数
        coords = str(lat) + "," + str(lon)
        return coords

    @staticmethod
    def writerline(valustr, provider, feature, setstr):
        points = []  # 存储点的列表
        for pair in valustr.split(';'):  # 分割每一组坐标
            coords = pair.split(',')
            if len(coords) == 2:
                try:
                    lon = float(coords[0])  # 尝试转换第一个坐标为浮点数
                    lat = float(coords[1])  # 尝试转换第二个坐标为浮点数
                    # 转为WGS84
                    lon2, lat2 = CoordinateConverter.bd09_to_wgs84(lon, lat)
                    points.append(QgsPoint(lon2, lat2))  # 创建 QgsPoint 对象并添加到列表
                except ValueError:
                    continue

        if len(points) > 1:  # 确保至少有三个点构成多边形

            geom = QgsGeometry.fromPolyline(points)

            if geom.isGeosValid():  # 检查几何对象的有效性

                feature["name"] = setstr  # 设置属性值
                feature.setGeometry(geom)  # 设置几何对象
                provider.addFeatures([feature])  # 将特征添加到数据提供者
            else:
                print(f"无效图形")

        else:
            print(f"无效的几何图形在索引,{valustr}")  # 打印无效几何信息
