# -*- coding: utf-8 -*-

import log
import zbmx.arcTools
import appconfig
import os


# 面积统计
def Area_statistics(inList, comObj, outGdb, xzq):
    mjField = "F__MJ"
    in_node = inList[0]
    data = in_node['sjy']
    areaU = "!shape.area@SQUAREMETERS!"
    if comObj["danwei"] == "km2":
        areaU = "!shape.area@SQUAREKILOMETERS!"
    if comObj["danwei"] == "hm2":
        areaU = "!shape.area@HECTARES!"  # 公顷
    if comObj["danwei"] == "mu":
        areaU = "!shape.area@HECTARES!"  # 亩=> 1公顷=15亩
    if comObj["danwei"] == "wmu":
        areaU = "!shape.area@HECTARES!"  # 万亩

    if comObj["par1_field"] == "":
        arcTools.AddField_management(data, mjField, "DOUBLE")
        arcTools.CalculateField_management(data, mjField, areaU)
    else:
        mjField = comObj["par1_field"]
    list = arcTools.GetFieldValueList(data, mjField)
    tj = round(sum(list), 2)

    if comObj["danwei"] == "mu":
        tj = round(sum(list) * 15, 2)
    if comObj["danwei"] == "wmu":
        tj = round(sum(list) * 15 / 10000, 2)

    log.info("面积统计结束")
    return tj


# 求面积占比(默认使用平方米 !shape.area@SQUAREMETERS!)
def Area_proportion(inList, comObj, outGdb, xzq):
    divisor = 0  # 除数
    dividend = 0  # 被除数

    for in_node in inList:
        mjField = "F__MJ"
        data = in_node['sjy']
        type = "divisor" if in_node["key"] == comObj["divisor"] else "dividend"

        # 数据源
        if in_node['category'] == "sjy":
            sdeTable = in_node['sjy'].split('.')
            sde = appconfig.SDE[sdeTable[0]]
            data = sde + os.sep + sdeTable[1]

        # 面积
        if comObj["{0}_field".format(type)] == "":
            arcTools.AddField_management(data, mjField, "DOUBLE")
            arcTools.CalculateField_management(data, mjField, "!shape.area@SQUAREMETERS!")
        else:
            mjField = comObj["{0}_field"]

        # 汇总
        list = arcTools.GetFieldValueList(data, mjField)
        if type == "divisor":
            divisor = sum(list)
        else:
            dividend = sum(list)

    zb = round(divisor / dividend * 100, 2)
    log.info("面积占比结束")
    return zb


# 求行政区占比(默认使用平方米 !shape.area@SQUAREMETERS!)
def Area_xzqzb(inList, comObj, outGdb, xzq):
    divisor = 0  # 除数
    dividend = 0  # 被除数
    in_node = inList[0]
    in_data = in_node['sjy']
    in_xzq = in_node['xzq']
    mjField = "F__MJ"
    areaU = "!shape.area@SQUAREMETERS!"

    # 除数
    if comObj["par1_field"] == "":
        arcTools.AddField_management(in_data, mjField, "DOUBLE")
        arcTools.CalculateField_management(in_data, mjField, areaU)
    else:
        mjField = comObj["par1_field"]
    list = arcTools.GetFieldValueList(in_data, mjField)
    divisor = sum(list)

    # 被除数
    arcTools.AddField_management(in_xzq, mjField, "DOUBLE")
    arcTools.CalculateField_management(in_xzq, mjField, areaU)
    list = arcTools.GetFieldValueList(in_xzq, mjField)
    dividend = sum(list)

    zb = round(divisor / dividend * 100, 2)
    log.info("行政区占比结束")
    return zb
