# -*- coding: GBK -*-
# ---------------------------------------------------------------------------
# PointsClusterDefault.py
# Created on: 2015-07-02 11:08:02.00000
#   (generated by ArcGIS/ModelBuilder)
# Usage: PointsClusterDefault <InputExcel> <ClusterDistance> <OutPolygon> <OutPointsExcel> <OutPolygonsExecl> 
# Description: 
# ---------------------------------------------------------------------------

# Set the necessary product code
# import arcinfo


# Import arcpy module
import arcpy
from arcpy import env
import cx_Oracle
import re
import logging
import os
import os.path
import time,datetime

spatialReference = arcpy.SpatialReference(4326)
arcpy.ImportToolbox("C:\\Users\\Administrator\\AppData\\Roaming\\ESRI\\Desktop10.2\\ArcToolbox\\My Toolboxes\\ClusterTools.tbx")
ArcCatalogPath = "C:\\Users\\Administrator\\AppData\\Roaming\\ESRI\\Desktop10.3\\ArcCatalog"
LOG_FILE_NAME = "E:\\GisPython\\logs\\DSSSCluster.log"
logging.basicConfig(filename=LOG_FILE_NAME,level=logging.INFO)
logging.basicConfig(filename=LOG_FILE_NAME,level=logging.ERROR)
clusterCacheDB = "E:\PointsClusterDir\cachedb.gdb"
env.workspace = clusterCacheDB

def createFeatureFromXY(featureTable,lonField,latField,featurePath,Fields):
    resultFeatcur = arcpy.InsertCursor(featurePath)
    featRows = arcpy.SearchCursor(featureTable)
    for CellRow in featRows:
        p_lon = CellRow.getValue(lonField)
        p_lat = CellRow.getValue(latField)
        resultRow = resultFeatcur.newRow()
        featurePoint = arcpy.Point(p_lon, p_lat)
        resultRow.shape = featurePoint
        for Field in Fields:
            FieldName = Field.name
            if(FieldName!="OBJECTID" and FieldName!="SHAPE"):
                resultRow.setValue(FieldName,CellRow.getValue(FieldName))
        resultFeatcur.insertRow(resultRow)
    del resultFeatcur,featRows

def doPointsClusterA(InputTable,OutputTable,ClusterDistance="500 Meters"):
    ##params of dbdata
    POI = ArcCatalogPath+"\\WangYouTouSu60.sde\\WangYouTouSu.DBO.GIS_POI_AREA_ALLGRID"
    cacheAggregatePoints2 =  clusterCacheDB+"/cacheAggregatePoints2"
    cacheAggregatePoints2Tbl =  clusterCacheDB+"/cacheAggregatePoints2_Tbl"
    pointCluster3 =  clusterCacheDB+"/pointCluster3"
    OutPolygon4 =  clusterCacheDB+"/OutPolygon4"
    SpatialJoin5  = OutputTable
    OutPolygonPoints6 = clusterCacheDB+"/OutPolygonPoints6"
    SpatialJoinPoint7 = clusterCacheDB+"/SpatialJoinPoint7"
    
    if(arcpy.Exists(cacheAggregatePoints2)):
        arcpy.Delete_management(cacheAggregatePoints2)
    if(arcpy.Exists(cacheAggregatePoints2Tbl)):
        arcpy.Delete_management(cacheAggregatePoints2Tbl)
    if(arcpy.Exists(pointCluster3)):
        arcpy.Delete_management(pointCluster3)
    if(arcpy.Exists(OutPolygon4)):
        arcpy.Delete_management(OutPolygon4)
    if(arcpy.Exists(SpatialJoin5)):
        arcpy.Delete_management(SpatialJoin5)
    if(arcpy.Exists(OutPolygonPoints6)):
        arcpy.Delete_management(OutPolygonPoints6)
    if(arcpy.Exists(SpatialJoinPoint7)):
        arcpy.Delete_management(SpatialJoinPoint7)
        
    print "1.Process:AggregatePoints"
    logging.info("1.Process:AggregatePoints")
    # Process: 聚合点
    arcpy.AggregatePoints_cartography(InputTable, cacheAggregatePoints2, ClusterDistance)

    print "2.Process:PointClusterinsert"
    logging.info("2.Process:PointClusterinsert")
    # Process: 面聚合插入式
    arcpy.gp.toolbox = "C:\\Users\\Administrator\\AppData\\Roaming\\ESRI\\Desktop10.2\\ArcToolbox\\My Toolboxes\\ClusterTools.tbx";    
    arcpy.gp.PointClusterinsert(cacheAggregatePoints2, pointCluster3)
    
    print "3.Process:Dissolve"
    logging.info("3.Process:Dissolve")
    # Process: 融合
    arcpy.Dissolve_management(pointCluster3, OutPolygon4, "CLUSTERID", "", "MULTI_PART", "DISSOLVE_LINES")

    print "4.Process:SpatialJoin"
    logging.info("4.Process:SpatialJoin")
    # Process: 空间连接
    arcpy.SpatialJoin_analysis(InputTable, OutPolygon4, SpatialJoin5, "JOIN_ONE_TO_ONE", "KEEP_ALL", "", "INTERSECT", "", "")

    print "5.Process:FeatureToPoint"
    logging.info("5.Process:FeatureToPoint")
    # Process: 要素转点
    arcpy.FeatureToPoint_management(OutPolygon4, OutPolygonPoints6, "CENTROID")

    print "6.Process:SpatialJoin"
    logging.info("6.Process:SpatialJoin")
    # Process: 空间连接 (2)
    arcpy.SpatialJoin_analysis(OutPolygonPoints6, POI, SpatialJoinPoint7, "JOIN_ONE_TO_ONE", "KEEP_ALL", "", "CLOSEST", "", "DISTANCE")

    print "7.Process:JoinField"
    logging.info("7.Process:JoinField")
    # Process: 连接字段
    arcpy.JoinField_management(SpatialJoin5, "CLUSTERID", SpatialJoinPoint7, "CLUSTERID",  "DISTANCE;CLUSTERID;Name;CITY;COUNTY;GRID;LON;LAT")

    print "8.Process:delete no user field"
    logging.info("8.Process:delete no user field")
    arcpy.DeleteField_management (SpatialJoin5, "Join_Count") 
    arcpy.DeleteField_management (SpatialJoin5, "TARGET_FID")
    arcpy.DeleteField_management (SpatialJoin5, "ObjectID_1")
    arcpy.DeleteField_management (SpatialJoin5, "CLUSTERID_1")
    arcpy.CalculateField_management(SpatialJoin5, "DISTANCE", '!DISTANCE!/0.0009*100' , "PYTHON_9.3")

    #print "9.Process:TableToExcel"
    #logging.info("9.Process:TableToExcel")
    # Process: 表转 Excel
    #arcpy.TableToExcel_conversion(SpatialJoin5, OutputExcel, "NAME", "CODE")

    
if __name__ == '__main__':
    try:
        print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        logging.info("开始时间:"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        OracleGISDBPath = "PDB_PMSDB.sde"
        InputTable = ArcCatalogPath+"\\"+OracleGISDBPath+"\\SDE.WNPM_PORT_XQMX"
        OutputTable = ArcCatalogPath+"\\"+OracleGISDBPath+"\\SDE.WNPM_PORT_XQMX_CLUSTER"
        clusterPointTmp = clusterCacheDB+"/clusterPointTmp"
        clusterPoint1 = clusterCacheDB+"/clusterPoint1"
        Fields = arcpy.ListFields(InputTable)
        if(arcpy.Exists(clusterPoint1)):
            arcpy.Delete_management(clusterPoint1)
        clusterPoint1 = arcpy.CreateFeatureclass_management(os.path.dirname(clusterPoint1),os.path.basename(clusterPoint1),"Point",clusterPointTmp,"DISABLED","DISABLED",arcpy.SpatialReference(4326))
        print "----------"
        createFeatureFromXY(InputTable,"LONGITUDE","LATITUDE",clusterPoint1,Fields)
        
        clusterDist = "200 Meters"
        doPointsClusterA(clusterPoint1,OutputTable,clusterDist)
        logging.info("结束时间:"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    except Exception,e:
        logging.error(e)
        print e.message
    
