# -*- coding: utf-8 -*-
import os
import sys
import json
import utils
import importlib, sys

from osgeo import ogr

from tools.PostgreSQL.PostgreSQL import PostgreSQL
from tools.StringUtils import (getConnectionStr, getNow)

importlib.reload(sys)


def run(fun, data):
    try:
        message = eval("{0}".format(fun))(data)
        print(message)
        # 输出成功信息 做交互用
        # print("####OK####")
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)


# 测试
def test(data):
    print(data["bsm"])


# postgisupdate
def postgisupdate(data):
    print("===========进行数据更新开始===========")
    # 当前时间
    now = getNow()
    # 获取参数
    # ogrLayer = "D:\\gisdata\\三亚\\规划地块部分数据\\4525.shp"
    # allowoverlap = True
    # tablename = "vector.updatetest"
    ogrLayer = data["source"]
    allowoverlap = data["allowoverlap"]
    tablename = data["target"]
    pgconn = PostgreSQL(schema='base')
    srid = pgconn.getVectorTableSrid(tablename=tablename)
    geomtype = pgconn.getVectorTableGeomType(tablename=tablename)
    ds = ogr.Open(ogrLayer, 0)
    layer = ds.GetLayer()
    layer_spatial_ref = layer.GetSpatialRef()
    layer_def = layer.GetLayerDefn()
    vectorepsg = layer_spatial_ref.GetAttrValue('AUTHORITY', 1)
    alltablefiled = pgconn.getAllTableField(tablename=tablename)
    insertcount = 0
    misscount = 0
    for feature in layer:
        geom_wkt = feature.GetGeometryRef().ExportToWkt()
        # 判断是否允许更新重叠数据
        updatebool = True
        if allowoverlap == False:
            instersectsCount = pgconn.getInstersectsCount(tablename=tablename, tablesrid=srid, wkts=[geom_wkt],
                                                          wktsrid=vectorepsg)
            count = int(instersectsCount)
            if count > 0:
                updatebool = False
                misscount += 1
        if updatebool == True:
            # 遍历当前数据的属性信息
            attributes = {}
            for i in range(layer_def.GetFieldCount()):
                field_def = layer_def.GetFieldDefn(i)
                field_name = field_def.GetName()
                field_value = feature.GetField(i)
                attributes[field_name] = field_value
                # print(field_value)
                # if self.is_string(field_value) == True:
                #     print(field_value.encode('utf-8'))
            # 拼接insert into语句
            insertvalus = []
            for field in alltablefiled:
                b = utils.contains_keys(attributes, [field.lower()])
                if b == True:
                    insertvalus.append(attributes[field.lower()])
                else:
                    b = utils.contains_keys(attributes, [field.upper()])
                    if b == True:
                        insertvalus.append(attributes[field.upper()])
                    else:
                        insertvalus.append(None)
            pgconn.insertVectorFeature(tablename=tablename, fields=alltablefiled, values=insertvalus, wkt=geom_wkt,
                                       wktsrid=vectorepsg, geomtype=geomtype, rksj=now)
            insertcount += 1
    pgconn.updateVectorVersion(tablename=tablename, version=now)
    pgconn.close()
    return str({
        "status": "更新成功",
        "insert": str(insertcount) + "条记录",
        "miss": str(misscount) + "条记录，存在空间叠加。"
    })


if __name__ == '__main__':
    if len(sys.argv) == 3:
        fun = sys.argv[1]
        jsonData = utils.b64Decode(sys.argv[2])
        print(jsonData)
        run(fun, json.loads(jsonData))
