# coding=utf-8

"""
@name: 融合工具
@author: 陈蔡东
@datetime: 2024.04.16
"""

import os.path

import arcpy
import sys
import json
import traceback
import codecs

# region 相关参数

# 1.输入数据
inputDatabasePath = ""
# 2.输入图层
inputLayer = ""
# 3.过滤条件
inputLayerWhere = ""

# 4.输出要素类
outputData = ""

# 5.融合字段
dissolveField = []
# 6.统计字段
statisticsField = []

# 7.是否创建多部件要素[MULTI_PART、SINGLE_PART]
isCreateMultiPart = "MULTI_PART"
# 8.是否取消分割线[DISSOLVE_LINES、UNSPLIT_LINES]
isUnSplitLines = "DISSOLVE_LINES"

# endregion


# 初始化
def init():
    if len(sys.argv) < 2:
        raise Exception("未找到输入参数文件")

    argumentsFile = sys.argv[1]
    if not os.path.exists(argumentsFile):
        raise Exception("输入参数文件[" + argumentsFile + "不存在")

    with codecs.open(argumentsFile, 'r', 'utf-8') as f:
        arguments = json.load(f)

    if len(arguments) < 1:
        raise Exception("输入参数文件[" + argumentsFile + ", 内容为空")

    if len(arguments) < 8:
        raise Exception("输入参数至少为8位")

    global inputDatabasePath, inputLayer, inputLayerWhere
    global outputData, dissolveField, statisticsField
    global isCreateMultiPart, isUnSplitLines

    inputDatabasePath = arguments[0]
    inputLayer = arguments[1]
    inputLayerWhere = "" if arguments[2] is None else arguments[2]
    outputMsg("输入数据: " + inputDatabasePath + "\\" + inputLayer)
    if bool(inputLayerWhere.strip()):
        outputMsg("过滤条件: " + inputLayerWhere)

    outputData = arguments[3]
    outputMsg("输出数据："+outputData)

    dissolveField = [] if arguments[4] is None else arguments[4]
    if len(dissolveField) > 0:
        outputMsg("融合字段: ")
        outputMsg(dissolveField)

    isUnSplitLines = [] if arguments[5] is None else arguments[5]
    if len(isUnSplitLines) > 0:
        outputMsg("统计字段: ")
        outputMsg(isUnSplitLines)

    isCreateMultiPart = "MULTI_PART" if bool(arguments[6]) is True else "SINGLE_PART"
    outputMsg("是否创建多部件要素: " + str(isCreateMultiPart))

    isUnSplitLines = "DISSOLVE_LINES" if bool(arguments[7]) is True else "UNSPLIT_LINES"
    outputMsg("是否取消分割线: " + str(isUnSplitLines))


# 图层创建
def createLayer(databasePath, layerName, whereClause, newLayerName):
    arcpy.env.workspace = databasePath
    if bool(whereClause.strip()):
        arcpy.MakeFeatureLayer_management(layerName, newLayerName, whereClause)
    else:
        arcpy.MakeFeatureLayer_management(layerName, newLayerName)

    # 清除历史选择，防止对选择结果造成影响
    # arcpy.SelectLayerByAttribute_management(newLayerName, "CLEAR_SELECTION")
    return newLayerName


# 消息写出
def outputMsg(msg):
    try:
        #if not isinstance(msg, str) and not isinstance(msg, unicode):
        #   arcpy.AddMessage(msg)
        #   return
        msg = msg.decode('utf-8')
        msg = repr(msg)
        arcpy.AddMessage(msg)
    except Exception, e:
        temp = e
        arcpy.AddMessage(msg)


# 输出错误信息
def outputErrorMsg(msg):
    try:
        #if not isinstance(msg, str) and not isinstance(msg, unicode):
        #   arcpy.AddMessage(msg)
        #   return
        msg = msg.decode('utf-8')
        msg = repr(msg)
        arcpy.AddError(msg)
    except Exception, e:
        temp = e
        arcpy.AddError(msg)


# 程序入口，开始执行
def main():
    try:
        # 0.系统编码设置
        reload(sys)
        sys.setdefaultencoding('utf-8')

        # 1.参数初始化
        outputMsg("开始初始化参数...")
        init()

        # 2.图层创建
        inputLayerName = "inputLayer"
        createLayer(inputDatabasePath, inputLayer, inputLayerWhere, inputLayerName)

        # 3.开始执行融合
        arcpy.Dissolve_management(inputLayerName, outputData, dissolveField, statisticsField, isCreateMultiPart, isUnSplitLines)

    except Exception, e:
        outputErrorMsg("融合工具执行异常")
        outputMsg(sys.argv)
        outputErrorMsg(e.message)
        outputErrorMsg(traceback.format_exc())
        raise e


if __name__ == '__main__':
    main()
