# coding:utf-8
import arcpy
import sys
import traceback

# 消息写出
def outputMsg(msg):
    arcpy.AddMessage(msg)

def main():
    try:
        database = sys.argv[1]  # 数据库路径
        checkLayerName = sys.argv[2]  # 检查图层名称
        checkLayerWhere = sys.argv[3]  # 相关图层筛选条件
        relatedLayerName = sys.argv[4]  # 相关图层名称
        relatedLayerWhere = sys.argv[5]  # 相关图层筛选条件
        spatialRelation = sys.argv[6]  # 空间关系
        checkBuffer = sys.argv[7]  # 检查缓冲值
        filterObjects = sys.argv[8]  # 多个过滤对象(包含图层名称和筛选条件)需解析
        filterBuffer = sys.argv[9]  # 过滤缓冲值
        maxAllowResultNum = sys.argv[10]  # 消息输出最大数量

        # database = arcpy.GetParameter(0)  # 数据库路径
        # checkLayerName = arcpy.GetParameter(1)  # 检查图层名称
        # checkLayerWhere = arcpy.GetParameter(2)  # 相关图层筛选条件
        # relatedLayerName = arcpy.GetParameter(3)  # 相关图层名称
        # relatedLayerWhere = arcpy.GetParameter(4)  # 相关图层筛选条件
        # spatialRelation = arcpy.GetParameter(5)  # 空间关系
        # checkBuffer = arcpy.GetParameter(6)  # 检查缓冲值
        # filterLayerName = arcpy.GetParameter(7)  # 过滤图层名称
        # filterLayerWhere = arcpy.GetParameter(8)  # 过滤图层筛选条件
        # filterBuffer = arcpy.GetParameter(9)  # 过滤缓冲值

        # database = 'E:\\1、测试数据及相关资料\\2023年城市监测\\测试数据\\点面关系测试.gdb'
        # checkLayerName = 'AAAP'
        # checkLayerWhere = ''
        # relatedLayerName = 'AAAM'
        # relatedLayerWhere = ''
        # checkBuffer = 0
        # spatialRelation = '相离'

        arcpy.env.workspace = database

        if checkLayerWhere == 'None':
            checkLayerWhere = ''
        else:
            checkLayerWhere = checkLayerWhere.replace("!?", " ")
        if relatedLayerWhere == 'None':
            relatedLayerWhere = ''
        else:
            relatedLayerWhere = relatedLayerWhere.replace("!?", " ")

        # 多个过滤对象
        filterObjectArr = filterObjects.split(';')
        for index in range(len(filterObjectArr)):
            filterObjectArr[index] = filterObjectArr[index].replace("!?", " ")

        arcpy.MakeFeatureLayer_management(checkLayerName, 'checkLayer', checkLayerWhere)
        arcpy.MakeFeatureLayer_management(relatedLayerName, 'relatedLayer', relatedLayerWhere)

        # 从VS2019传过来的字符串默认是gb2312编码，需要转换比较
        spatialRelation = spatialRelation.decode('gb2312').encode('utf-8')

        # 获取检查图层和相关图层的几何类型
        checkLayerType = arcpy.Describe('checkLayer').shapeType
        relatedLayerType = arcpy.Describe('relatedLayer').shapeType
        if checkLayerType == 'Point' and relatedLayerType == 'Polygon':
            if spatialRelation == '相交(不含边界)':  # 选择检查图层要素中，完全位于检查要素中的要相关图层要素，然后反选
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_CLEMENTINI', 'relatedLayer', None,
                                                       'NEW_SELECTION')
                arcpy.SelectLayerByLocation_management('checkLayer', '', '', None, 'SWITCH_SELECTION')
            elif spatialRelation == '相交(含边界)':
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_A_DISTANCE', 'relatedLayer', checkBuffer,
                                                       'NEW_SELECTION')
                arcpy.SelectLayerByLocation_management('checkLayer', '', '', None, 'SWITCH_SELECTION')
            elif spatialRelation == '相接':
                arcpy.SelectLayerByLocation_management('checkLayer', 'BOUNDARY_TOUCHES', 'relatedLayer', None,
                                                       'NEW_SELECTION')
                arcpy.SelectLayerByLocation_management('checkLayer', '', '', None, 'SWITCH_SELECTION')
            elif spatialRelation == '相离':
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_A_DISTANCE', 'relatedLayer', checkBuffer,
                                                       'NEW_SELECTION')
            else:  # 不相交（相接或相离）
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_CLEMENTINI', 'relatedLayer', None,
                                                       'NEW_SELECTION')
        elif checkLayerType == 'Polygon' and relatedLayerType == 'Point':
            if spatialRelation == '相交(不含边界)':  # 选择检查图层要素中，完全位于检查要素中的要相关图层要素，然后反选
                arcpy.SelectLayerByLocation_management('checkLayer', 'CONTAINS_CLEMENTINI', 'relatedLayer', None,
                                                       'NEW_SELECTION')
                arcpy.SelectLayerByLocation_management('checkLayer', '', '', None, 'SWITCH_SELECTION')
            elif spatialRelation == '相交(含边界)':
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_A_DISTANCE', 'relatedLayer', checkBuffer,
                                                       'NEW_SELECTION')
                arcpy.SelectLayerByLocation_management('checkLayer', '', '', None, 'SWITCH_SELECTION')
            elif spatialRelation == '相接':
                arcpy.SelectLayerByLocation_management('checkLayer', 'BOUNDARY_TOUCHES', 'relatedLayer', None,
                                                       'NEW_SELECTION')
                arcpy.SelectLayerByLocation_management('checkLayer', '', '', None, 'SWITCH_SELECTION')
            elif spatialRelation == '相离':
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_A_DISTANCE', 'relatedLayer', checkBuffer,
                                                       'NEW_SELECTION')
            else:  # 不相交（相接或相离）
                arcpy.SelectLayerByLocation_management('checkLayer', 'CONTAINS_CLEMENTINI', 'relatedLayer', None,
                                                       'NEW_SELECTION')
        if filterObjects != 'None':
            for filterObject in filterObjectArr:  # 排除过滤对象
                filterList = filterObject.split(':')
                filterLayerName = filterList[0]
                filterLayerWhere = filterList[1]
                if filterLayerWhere == 'None':
                    filterLayerWhere = ''
                if arcpy.Exists('filterLayer') == False:
                    arcpy.MakeFeatureLayer_management(filterLayerName, 'filterLayer', filterLayerWhere)
                arcpy.SelectLayerByLocation_management('checkLayer', 'WITHIN_A_DISTANCE', 'filterLayer',
                                                       filterBuffer, 'REMOVE_FROM_SELECTION')
        resultNum = 0  # 输出消息计数
        fields = ['ObjectID']
        outputMsg('检查图层意见OID')
        with arcpy.da.SearchCursor('checkLayer', fields) as cursor:
            for row in cursor:
                resultNum += 1
                if resultNum > int(maxAllowResultNum):
                    return
                outputMsg(row[0])

    except Exception as e:
        outputMsg('错误意见')
        # outputMsg(e.message)
        # msg = traceback.format_exc()
        # outputMsg(msg)
        traceback.print_exc()

if __name__ == "__main__":
    main()