# -*- coding: utf-8 -*-
import os
import sys
import log
import uuid
import appconfig
import arcpy
import datetime
import time
import utils
from arcpy import env
from db.postgresql import Postgresql

import importlib, sys

importlib.reload(sys)


class ClipFeature:
    def __init__(self):
        # 数据项配置
        self.clipF = "SDE.TKQFW"
        self.GlobalField = "KCXKZH"
        self.GlobalType = "TKQ"
        self.analyseF = "SDE.DLTB"
        self.bsm = self.getUUID()
        self.db = Postgresql(appconfig.DB_CONN)
        # 输出GDB
        self.root = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(self.root, "out")
        if not os.path.exists(path):
            os.makedirs(path)
        self.outGdb = os.path.join(path, "{0}.gdb".format(self.bsm))
        arcpy.Delete_management(self.outGdb)
        arcpy.CreateFileGDB_management(path, "{0}.gdb".format(self.bsm))
        # 输出文件夹里面已经有内容的，就覆盖掉
        env.overwriteOutput = True
        # 设置工作空间
        env.workspace = appconfig.SDE["SDE"]

    def run(self):
        self.out = r"{0}\ClipResults".format(self.outGdb)
        # 第一步裁剪要素
        arcpy.Intersect_analysis([self.clipF, self.analyseF], self.out)
        # 裁剪完成的数据增加字段
        arcpy.AddField_management(self.out, "YZMJ", "DOUBLE")
        arcpy.AddField_management(self.out, "TARGETID", "TEXT")
        arcpy.AddField_management(self.out, "TARGETTYPE", "TEXT")
        # 算压占面积
        arcpy.CalculateField_management(self.out, "YZMJ", "!shape.area@SQUAREMETERS!", "PYTHON_9.3")
        with arcpy.da.UpdateCursor(self.out, ["TARGETTYPE"]) as cursor:
            for row in cursor:
                row[0] = self.GlobalType
                cursor.updateRow(row)
        # 遍历数据 计算TARGETID
        ufields = [self.GlobalField]
        with arcpy.da.UpdateCursor(self.clipF, ufields) as cursor:
            for row in cursor:
                targetid = row[0]
                # 将数据设置为FeatureLayer进行操作
                arcpy.MakeFeatureLayer_management(self.clipF, "clipF")
                arcpy.MakeFeatureLayer_management(self.out, "out")
                arcpy.SelectLayerByAttribute_management("clipF", "NEW_SELECTION",
                                                        self.GlobalField + " = '" + targetid + "'")
                arcpy.SelectLayerByLocation_management("out", "INTERSECT", "clipF")
                with arcpy.da.UpdateCursor("out", ["TARGETID"]) as cursor:
                    for row in cursor:
                        row[0] = targetid
                        cursor.updateRow(row)
        print("####OK####")

    def getUUID(self):
        return ''.join(str(uuid.uuid1()).split('-'))
