import os
import subprocess
import psycopg2
import config
from osgeo import ogr

from qgis.core import *
from PyQt5.QtWidgets import QFileDialog

# 初始化 QGIS 环境（如果在独立 Python 环境中）
# QgsApplication.setPrefixPath("D:\\Program Files\\QGIS 3.34.9", True)
# qgs = QgsApplication([], False)
# qgs.initQgis()

gdb_folder = "D:\\gisdata\\三亚\\海域数据和三区三线数据\\三亚三线数据.gdb"
# 打开 GDB 文件夹（通过 ogr 驱动）
driver = ogr.GetDriverByName('OpenFileGDB')
if not driver:
    print("OpenFileGDB 驱动不可用")
# 打开 GDB 文件夹
gdb = driver.Open(gdb_folder, 0)  # 0 表示只读模式

if not gdb:
    print(f"无法打开 {gdb_folder} 文件夹")


def getLayerGeometryType(geom_type):
    geom_type_str = ""
    if geom_type == ogr.wkbPoint:
        geom_type_str = "Point"
    elif geom_type == ogr.wkbLineString:
        geom_type_str = "LineString"
    elif geom_type == ogr.wkbPolygon:
        geom_type_str = "Polygon"
    elif geom_type == ogr.wkbMultiPoint:
        geom_type_str = "MultiPoint"
    elif geom_type == ogr.wkbMultiLineString:
        geom_type_str = "MultiLineString"
    elif geom_type == ogr.wkbMultiPolygon:
        geom_type_str = "MultiPolygon"
    elif geom_type == ogr.wkbGeometryCollection:
        geom_type_str = "GeometryCollection"
    else:
        geom_type_str = None
    return geom_type_str


layer_count = gdb.GetLayerCount()
if layer_count > 0:
    # 全局参数修改
    db_config = config.CONFIG['db']

    # 数据库连接参数
    db_params = {
        'host': db_config['host'],
        'port': db_config['port'],
        'dbname': db_config['name'],
        'user': db_config['user'],
        'password': db_config['password'],
        'schema': db_config['schema']
    }
    # 将每个图层导入到 PostGIS
    pg_conn_string = f'PG:"host={db_params["host"]} port={db_params["port"]} dbname={db_params["dbname"]} user={db_params["user"]} password={db_params["password"]} active_schema={db_params["schema"]}"'

    for i in range(layer_count):
        layer = gdb.GetLayerByIndex(i)
        # 获取图层的几何类型
        geom_type = getLayerGeometryType(layer.GetGeomType())
        print(geom_type)
        layer_name = layer.GetName()
        print(f"图层 {i}: {layer.GetName()}")
        command = f'"D:\\Program Files\\QGIS 3.34.9\\bin\\ogr2ogr.exe" -f "PostgreSQL" {pg_conn_string} "{gdb_folder}" {layer_name}  -overwrite  -nln {layer_name}'
        if geom_type:
            command = f'{command} -nlt {geom_type}'
        print(command)
        subprocess.run(command, check=True)
        print(f"图层 {layer_name} 导入成功")
else:
    print(f"{gdb_folder} 文件夹不包含任何图层")

# 退出 QGIS 环境
# qgs.exitQgis()
