from qgis._core import QgsWkbTypes
from qgis.core import QgsVectorLayer, QgsFeature

# 加载Shapefile
layer = QgsVectorLayer("E:\\projects\\遥感技术部需求\\裁剪栅格\\data\\grid.shp", "grid", "ogr")
D = 40
d = 2
# 检查图层是否加载成功
if not layer.isValid():
    print("图层加载失败！")
else:
    # 遍历每一个Feature
    for feature in layer.getFeatures():
        # 获取每个Feature的几何信息
        geometry = feature.geometry()

        # 判断几何类型，如果是点类型，可以直接获取坐标
        if geometry.type() == QgsWkbTypes.PointGeometry:
            point = geometry.asPoint()  # 返回点的坐标 (x, y)
            print(f"点坐标: {point}")

        # 如果是线或面类型，获取所有坐标
        elif geometry.type() == QgsWkbTypes.LineGeometry:
            for point in geometry.asPolyline():  # 获取线的所有点
                print(f"线坐标: {point}")

        elif geometry.type() == QgsWkbTypes.PolygonGeometry:
            rings = None
            try:
                rings = geometry.asPolygon()
            except Exception as e:
                rings = geometry.asMultiPolygon()
                rings = rings[0]
            finally:
                print("读取完成")
            for ring in rings:  # 获取面的所有点（包括外环和内环）
                if len(ring) != 5:
                    print("要素错误！")
                    continue
                print("开始计算")
                p1 = ring[0]
                p2 = ring[1]
                p3 = ring[2]
                p4 = ring[3]
                # ymax = int((max(p1.x(), p2.x(), p3.x(), p4.x()) + D) / d) * d
                # xmin = int((min(p1.x(), p2.x(), p3.x(), p4.x()) - D) / d) * d
                # ymin = int((min(p1.y(), p2.y(), p3.y(), p4.y()) - D) / d) * d
                # xmax = int((max(p1.y(), p2.y(), p3.y(), p4.y()) + D) / d) * d

                ymax = int((max(p1.y(), p2.y(), p3.y(), p4.y()) + D) / d) * d
                xmin = int((min(p1.x(), p2.x(), p3.x(), p4.x()) - D) / d) * d
                ymin = int((min(p1.y(), p2.y(), p3.y(), p4.y()) - D) / d) * d
                xmax = int((max(p1.x(), p2.x(), p3.x(), p4.x()) + D) / d) * d
                
                print(f"{xmin},{ymin},{xmax},{ymax}")
                # for point in ring:
                #     print(f"面坐标: {point}")
