# -*- coding: utf-8 -*-
import os
import sys
import json
import log
import arcpy
import appconfig
from arcpy import env

import importlib, sys

importlib.reload(sys)


# shp转json
def shp2geojson(shpfile, geojson):
    try:
        env.workspace = os.path.dirname(shpfile)
        arcpy.FeaturesToJSON_conversion(shpfile, geojson, geoJSON="GEOJSON")
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)


# json转shp
def esriJson2shp(jsonfile, shpfile):
    try:
        env.workspace = shpfile
        arcpy.JSONToFeatures_conversion(jsonfile, shpfile)
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)


# json存入SDE
def esriJson2sde(jsonfile, target_table):
    try:
        sdeTable = target_table.split('.')
        sde = appconfig.SDE[sdeTable[0]]
        env.workspace = sde
        # Json转Shp（JSON不能追加）
        shpfile = jsonfile.replace('.json', '.shp')
        arcpy.JSONToFeatures_conversion(jsonfile, shpfile)
        arcpy.Append_management(shpfile, target_table, "NO_TEST")
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)


# shp转sde
def shp2sde(shpfile, target_table, fields):
    sdeTable = target_table.split('.')
    sde = appconfig.SDE[sdeTable[0]]
    env.workspace = sde
    if fields != None:
        for field in fields:
            arcpy.AddField_management(shpfile, field["name"], field["type"])
            arcpy.CalculateField_management(shpfile, field["name"], "\"{0}\"".format(field["value"]), "PYTHON_9.3")

    arcpy.Append_management(shpfile, target_table, "NO_TEST")


# sde转geojson
def sde2shp(in_table, shpfile, where):
    try:
        sdeTable = in_table.split('.')
        sde = appconfig.SDE[sdeTable[0]]
        env.workspace = sde
        arcpy.Delete_management(shpfile)

        if where != "" and where != None:
            arcpy.Select_analysis(in_table, shpfile, where)
        else:
            arcpy.Select_analysis(in_table, shpfile, "1=1")

    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)


# dwg转shp
def dwg2shp(dwgfile, espg):
    try:
        log.info(dwgfile)
        # CAD文件路径
        input_cad_dataset = dwgfile
        # 文件路径
        defaultpath = os.path.dirname(input_cad_dataset)
        # 输入CAD文件名称
        CADname = input_cad_dataset.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
        log.info(CADname)
        # 定义工作空间
        arcpy.env.workspace = defaultpath
        # gdb文件路径
        out_gdb_path = os.path.join(defaultpath, CADname + '.gdb')
        log.info("GDB=>" + out_gdb_path)
        # 要素集文件名称
        out_dataset_name = CADname
        # CAD转shp坐标比例
        reference_scale = "1"
        # 先创建一个gdb地理数据库
        if os.path.exists(out_gdb_path):
            arcpy.Delete_management(out_gdb_path)
        arcpy.CreateFileGDB_management(defaultpath, CADname + '.gdb')
        # 将CAD文件导入到gdb地理数据库，新建一个要素集
        arcpy.CADToGeodatabase_conversion(input_cad_dataset, out_gdb_path, out_dataset_name, reference_scale)
        # 切换工作空间到gdb中
        arcpy.env.workspace = out_gdb_path
        # 获取gdb中的文件列表
        datasets = arcpy.ListDatasets(feature_type='feature')
        # 输入shp文件的保存路径
        output_shp_path = os.path.join(defaultpath, CADname + '.shps')
        if not os.path.exists(output_shp_path):
            os.makedirs(output_shp_path)
        datasets = [''] + datasets if datasets is not None else []
        # 获取每个地理数据库中的要素集
        shp = ''
        for ds in datasets:
            for fc in arcpy.ListFeatureClasses(feature_dataset=ds):
                path = os.path.join(arcpy.env.workspace, ds, fc)
                log.info(path)
                outfc = arcpy.ValidateTableName(fc)
                shpfile = os.path.join(output_shp_path, outfc + '.shp')
                log.info(shpfile)
                if outfc == 'Polyline' or outfc == 'Polygon':
                    shp += ";" + shpfile
                # 将要素集里的要素转为shp文件
                arcpy.FeatureClassToShapefile_conversion(outfc, output_shp_path)
                # 直接定义espg编号 - CGCS2000_3_Degree_GK_Zone_38
                coord_sys = arcpy.SpatialReference(espg)
                # 定义地理坐标系
                arcpy.DefineProjection_management(shpfile, coord_sys)
        print("####OK####" + shp)
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)
