# -*- 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 Hgxfx:
    def __init__(self, data):
        self.bsm = data
        # self.bsm = 'b9ca0e7812544e8ba1d10ac59b5e0f4d'
        self.db = Postgresql(appconfig.DB_CONN)
        log.info(data)
        self.fxlog(self.bsm, "info", "开始进行合规性分析")
        # 读任务
        self.task()
        # 选址GDB
        self.root = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(self.root, "out")
        # self.tbxPath = os.path.abspath(os.path.join(self.root,"../tbxs"))
        if not os.path.exists(path):
            os.makedirs(path)
        self.outGdb = os.path.join(path, "{0}.gdb".format(data))
        arcpy.Delete_management(self.outGdb)
        arcpy.CreateFileGDB_management(path, "{0}.gdb".format(data))

        # 输出文件夹里面已经有内容的，就覆盖掉
        env.overwriteOutput = True
        # 设置工作空间
        env.workspace = appconfig.SDE["KJGH"]

    def task(self):
        '''加载数据-任务、因子'''
        sql = "SELECT BSM as \"BSM\",cast(FXMJ as VARCHAR) as \"FXMJ\",XMMC as \"XMMC\",XMLX as \"XMLX\",JSDW as \"JSDW\",YDXZ_BSM as \"YDXZ_BSM\" FROM onemap.T_FZSS_HGXFX WHERE BSM='{0}'".format(
            self.bsm)
        tasks = self.db.query(sql)
        if len(tasks) == 0:
            self.fxlog(self.bsm, "error", "任务标识错误[{0}]".format(self.bsm))
            raise Exception("任务标识错误[{0}]".format(self.bsm))
        self.task = tasks[0]

        sql = "SELECT A.BSM as \"BSM\",A.RWBSM as \"RWBSM\",A.SCXBSM as \"SCXBSM\",B.YSDM as \"YSDM\",B.YSMC as \"YSMC\",B.SJY as \"SJY\" FROM onemap.T_FZSS_HGXFX_HGSCX A LEFT JOIN onemap.T_FZSS_HGXFX_SCX B ON A.SCXBSM = B.BSM WHERE A.RWBSM = '{0}' ORDER BY B.XSSX,B.KZXJB".format(
            self.bsm)
        self.hgscx = self.db.query(sql)

        yznames = ""
        for yz in self.hgscx:
            yznames = yznames + yz['YSMC'] + "、"
        self.fxlog(self.bsm, "info", "检查要素：{0}".format(yznames[:-1]))

    def run(self):
        # 1.范围导入
        # 设置工作空间
        self.fw = r"{0}\FW".format(self.outGdb)
        # 范围
        where = '"rwbsm"=\'{0}\''.format(self.bsm)
        arcpy.Select_analysis("KJGH.T_FZSS_FXRW_GIS", self.fw, where)
        self.fxlog(self.bsm, "info", "载入审查范围完成")

        # 2.用地用海单独处理
        # ydyh = r"{0}\SJY".format(self.outGdb)
        # arcpy.Intersect_analysis(["KJGH_QY.XZYDYH"], self.fw] , ydyh)
        # arcpy.ImportToolbox(os.path.join(self.tbxPath,"xzydyh.tbx"),"xzydyh")
        # arcpy.hgxfx_xzydyh(ydyh)
        # self.fxlog(self.bsm, "info", "用地用海分析完成")

        # 2.分析-检查项
        for scx in self.hgscx:
            out = r"{0}\FX_{1}".format(self.outGdb, scx['SCXBSM'])
            yzsjy = scx['SJY']  # 数据
            mj = 0  # 占压面积和距离
            sfhg = ""  # 是否合规
            bz = ""
            jcjg = ""  # 检查结果
            mjField = "YZMJ"  # 面积和距离字段
            arcpy.Intersect_analysis([self.fw, yzsjy], out)
            fid = "FID_{0}".format(yzsjy.split('.')[1]);
            # 删
            attrs = ["objectid", "shape", "shape_length", "shape_area", "rwbsm", fid.lower()]
            fields = arcpy.ListFields(out)
            for field in fields:
                if field.name.lower() not in attrs:
                    arcpy.DeleteField_management(out, field.name)
            # 加
            arcpy.AddField_management(out, "BSM", "TEXT")
            arcpy.AddField_management(out, "SCXBSM", "TEXT")
            arcpy.AddField_management(out, "YSDM", "TEXT")
            arcpy.AddField_management(out, "YSMC", "TEXT")
            arcpy.AddField_management(out, "YZMJ", "DOUBLE")
            arcpy.AddField_management(out, "OBJID", "DOUBLE")
            arcpy.AddField_management(out, "CJSJ", "DATE")
            # 算
            arcpy.CalculateField_management(out, "YZMJ", "!shape.area@SQUAREMETERS!", "PYTHON_9.3")

            ufields = ["BSM", "SCXBSM", "YSDM", "YSMC", "OBJID", "CJSJ", fid]
            with arcpy.da.UpdateCursor(out, ufields) as cursor:
                for row in cursor:
                    guid = ''.join(str(uuid.uuid1()).split('-'))
                    row[0] = guid
                    row[1] = scx['BSM']
                    row[2] = scx['YSDM']
                    row[3] = scx['YSMC']
                    row[4] = row[6]
                    row[5] = datetime.datetime.now()
                    cursor.updateRow(row)
            with arcpy.da.SearchCursor(out, [mjField]) as cursor:
                for row in cursor:
                    mj = mj + row[0]
            if mj > 0:
                jcjg = "项目范围共涉及" + scx["YSMC"] + "约" + str(round(mj, 2)) + "㎡";
            else:
                jcjg = "项目范围未涉及" + scx["YSMC"];
            # 分析结果更新
            self.fxjggx(scx["BSM"], mj, jcjg, sfhg, bz);
            arcpy.Append_management([out], "KJGH.T_FZSS_HGXFX_JG_GIS", "NO_TEST")
            self.fxlog(self.bsm, "info", "{0}审查分析完成".format(scx['YSMC']))
        time.sleep(1)
        self.fxlog(self.bsm, "info", "审查完成")
        print("####OK####")

    def fxlog(self, bsm, rzlx, msg):
        sql = "INSERT INTO onemap.T_FZSS_FXRWRZ(RWLX,RWBSM,RZLX,FXJG,RZSJ,RZLR,BSM) VALUES ('{0}','{1}','{2}','{3}',to_date('{4}','yyyy-mm-dd hh24:mi:ss'),'{5}','{6}')";
        sql = sql.format(
            '合规性审查'
            , bsm
            , rzlx
            , ''
            , utils.getNowTimeStr("%Y-%m-%d %H:%M:%S")
            , msg
            , ''.join(str(uuid.uuid1()).split('-'))
        )
        self.db.insert(sql)

    def fxjggx(self, bsm, zdmj, jcjg, sfhg, bz):
        sql = "UPDATE onemap.T_FZSS_HGXFX_HGSCX SET ZDMJ = " + str(zdmj);
        if jcjg != "" and jcjg != None:
            sql = sql + " ,JCJG = '" + jcjg + "'";
        sql = sql + " WHERE BSM = '" + bsm + "'";
        self.db.insert(sql)
