from qgis._core import QgsRectangle
from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsVectorFileWriter, QgsField, QgsWkbTypes
from PyQt5.QtCore import QVariant

# 输入shapefile路径
input_shp = "E:\\projects\\遥感技术部需求\\裁剪栅格\\data\\grid.shp"

# 输出shapefile路径
output_shp = "E:\\projects\\遥感技术部需求\\裁剪栅格\\data\\grid_extent.shp"

expand_distance = 50

# 加载输入shapefile
input_layer = QgsVectorLayer(input_shp, "input_layer", "ogr")

if not input_layer.isValid():
    print(f"Failed to load input shapefile: {input_shp}")
else:
    # 获取输入图层的字段信息
    fields = input_layer.fields()

    # 创建输出shapefile
    writer = QgsVectorFileWriter(output_shp, 'UTF-8', fields, QgsWkbTypes.MultiPolygon, input_layer.crs(),
                                 'ESRI Shapefile')

    output_layer = QgsVectorLayer(output_shp, "output_shp", "ogr")

    # 检查文件是否成功创建
    if writer.hasError() != QgsVectorFileWriter.NoError:
        print(f"Error creating output shapefile: {output_shp}")
    else:
        # 遍历输入shapefile中的要素
        for feature in input_layer.getFeatures():
            # 获取要素的geometry和extent
            geometry = feature.geometry()
            extent = geometry.boundingBox()  # 获取要素的extent（bounding box）
            # 对extent进行外扩
            # 使用 grow 方法来将bounding box外扩100米
            # extent.grow(expand_distance)  # 扩展100米
            # print(f"Feature ID: {feature.id()}, Extent: {extent}")
            # 获取四至坐标
            minX = extent.xMinimum()
            maxX = extent.xMaximum()
            minY = extent.yMinimum()
            maxY = extent.yMaximum()

            # 手动扩展extent，向四个方向扩展100米
            expanded_minX = minX - expand_distance  # 向左扩展
            expanded_maxX = maxX + expand_distance  # 向右扩展
            expanded_minY = minY - expand_distance  # 向下扩展
            expanded_maxY = maxY + expand_distance  # 向上扩展

            # 创建新的扩展后的QgsRectangle
            expanded_extent = QgsRectangle(expanded_minX, expanded_minY, expanded_maxX, expanded_maxY)

            # 使用extent创建一个新的几何（矩形geometry）
            new_geometry = QgsGeometry.fromRect(expanded_extent)

            # 创建一个新的要素，并将新几何设置到要素中
            new_feature = QgsFeature(fields)  # 创建新的空要素，使用相同的字段定义
            new_feature.setGeometry(new_geometry)  # 设置新的几何（extent）
            # 复制原始要素的属性到新的要素
            new_feature.setAttributes(feature.attributes())  # 将原要素的属性复制到新要素
            # 将修改后的要素添加到输出shapefile
            writer.addFeature(new_feature)

        # 完成写入并关闭输出文件
        del writer
        print(f"Features copied from {input_shp} to {output_shp} with modified extent.")
